diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 7d24ec22..444d0e03 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -184,6 +184,8 @@ target_link_libraries(engine PUBLIC zlib) add_subdirectory(3rdparty/lua) target_link_libraries(engine PUBLIC vanilla_lua) +add_subdirectory(3rdparty/luasocket) + if (NOT JLE_BUILD_EMSCRIPTEN) # Native build, excluding some Emscripten-embedded libraries else() target_link_libraries(engine PUBLIC ${CMAKE_DL_LIBS}) diff --git a/engine/EngineResources/scripts/3rdparty/LuaPanda.lua b/engine/EngineResources/scripts/3rdparty/LuaPanda.lua new file mode 100644 index 00000000..27e55bf1 --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/LuaPanda.lua @@ -0,0 +1,3606 @@ +-- Tencent is pleased to support the open source community by making LuaPanda available. +-- Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. +-- Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at +-- https://opensource.org/licenses/BSD-3-Clause +-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +-- API: +-- LuaPanda.printToVSCode(logStr, printLevel, type) +-- 打印日志到VSCode Output下 LuaPanda Debugger 中 +-- @printLevel: debug(0)/info(1)/error(2) 这里的日志等级需高于launch.json中配置等级日志才能输出 (可选参数,默认0) +-- @type(可选参数,默认0): 0:VSCode output console 1:VSCode tip 2:VSCode debug console + +-- LuaPanda.BP() +-- 强制打断点,可以在协程中使用。建议使用以下写法: +-- local ret = LuaPanda and LuaPanda.BP and LuaPanda.BP(); +-- 如果成功加入断点ret返回true,否则是nil + +-- LuaPanda.getInfo() +-- 返回获取调试器信息。包括版本号,是否使用lib库,系统是否支持loadstring(load方法)。返回值类型string, 推荐在调试控制台中使用。 + +-- LuaPanda.testBreakpoint() +-- 测试断点,用于分析路径错误导致断点无法停止的情况。测试方法是 +-- 1. launch.json 中开启 stopOnEntry, 或者在代码中加入LuaPanda.BP()。 +-- 2. 运行调试器和 lua 进程,当停止在 stopOnEntry 或者 LuaPanda.BP() 时在调试控制台输入 LuaPanda.testBreakpoint() +-- 3. 根据提示更新断点后再次输入 LuaPanda.testBreakpoint()。此时系统会输出一些提示,帮助用户分析断点可能无法停止的原因。 + +-- LuaPanda.doctor() +-- 返回对当前环境的诊断信息,提示可能存在的问题。返回值类型string, 推荐在调试控制台中使用。 + +-- LuaPanda.getBreaks() +-- 获取断点信息,推荐在调试控制台中使用。 + +-- LuaPanda.serializeTable(table) +-- 把table序列化为字符串,返回值类型是string。 + +-- LuaPanda.stopAttach() +-- 断开连接,停止attach,本次被调试程序运行过程无法再次进行attach连接。 + +-- 其他说明: +-- 关于真机调试,首次使用真机调试时要注意下方"用户设置项"中的配置 +-- 1. 确定 attach 开关打开: openAttachMode = true; 这样可以避免先启动手机app之后启动调试器无法连接。 +-- 2. 把连接时间放长: connectTimeoutSec 设置为 0.5 或者 1。首次尝试真机调试时这个值可以设置大一点,之后再根据自己的网络状况向下调整。 +-- 调试方法可以参考 github 文档 + +--用户设置项 +local openAttachMode = true; --是否开启attach模式。attach模式开启后可以在任意时刻启动vscode连接调试。缺点是没有连接调试时也会略降低lua执行效率(会不断进行attach请求) +local attachInterval = 1; --attach间隔时间(s) +local connectTimeoutSec = 0.005; --lua进程作为Client时, 连接超时时间, 单位s. 时间过长等待attach时会造成卡顿,时间过短可能无法连接。建议值0.005 - 0.05 +local listeningTimeoutSec = 0.5; -- lua进程作为Server时,连接超时时间, 单位s. 时间过长等待attach时会造成卡顿,时间过短可能无法连接。建议值0.1 - 1 +local userDotInRequire = true; --兼容require中使用 require(a.b) 和 require(a/b) 的形式引用文件夹中的文件,默认无需修改 +local traversalUserData = false; --如果可以的话(取决于userdata原表中的__pairs),展示userdata中的元素。 如果在调试器中展开userdata时有错误,请关闭此项. +local customGetSocketInstance = nil; --支持用户实现一个自定义调用luasocket的函数,函数返回值必须是一个socket实例。例: function() return require("socket.core").tcp() end; +local consoleLogLevel = 2; --打印在控制台(print)的日志等级 0 : all/ 1: info/ 2: error. +--用户设置项END + +local debuggerVer = "3.2.0"; --debugger版本号 +LuaPanda = {}; +local this = LuaPanda; +local tools = {}; --引用的开源工具,包括json解析和table展开工具等 +this.tools = tools; +this.curStackId = 0; +--json处理 +local json; +--hook状态列表 +local hookState = { + DISCONNECT_HOOK = 0, --断开连接 + LITE_HOOK = 1, --全局无断点 + MID_HOOK = 2, --全局有断点,本文件无断点 + ALL_HOOK = 3, --本文件有断点 +}; +--运行状态列表 +local runState = { + DISCONNECT = 0, --未连接 + WAIT_CMD = 1, --已连接,等待命令 + STOP_ON_ENTRY = 2, --初始状态 + RUN = 3, + STEPOVER = 4, + STEPIN = 5, + STEPOUT = 6, + STEPOVER_STOP = 7, + STEPIN_STOP = 8, + STEPOUT_STOP = 9, + HIT_BREAKPOINT = 10 +}; + +local TCPSplitChar = "|*|"; --json协议分隔符,请不要修改 +local MAX_TIMEOUT_SEC = 3600 * 24; --网络最大超时等待时间 +--当前运行状态 +local currentRunState; +local currentHookState; +--断点信息 +local breaks = {}; --保存断点的数组 +this.breaks = breaks; --供hookLib调用 +local recCallbackId = ""; +--VSCode端传过来的配置,在VSCode端的launch配置,传过来并赋值 +local luaFileExtension = ""; --vscode传过来的脚本后缀 +local cwd = ""; --工作路径 +local DebuggerFileName = ""; --Debugger文件名(原始,未经path处理), 函数中会自动获取 +local DebuggerToolsName = ""; +local lastRunFunction = {}; --上一个执行过的函数。在有些复杂场景下(find,getcomponent)一行会挺两次 +local currentCallStack = {}; --获取当前调用堆栈信息 +local hitBP = false; --BP()中的强制断点命中标记 +local TempFilePath_luaString = ""; --VSCode端配置的临时文件存放路径 +local recordHost; --记录连接端IP +local recordPort; --记录连接端口号 +local sock; --lua socket 文件描述符 +local server; --server 描述符 +local OSType; --VSCode识别出的系统类型,也可以自行设置。Windows_NT | Linux | Darwin +local clibPath; --chook库在VScode端的路径,也可自行设置。 +local hookLib; --chook库的引用实例 +local adapterVer; --VScode传来的adapter版本号 +local truncatedOPath; --VScode中用户设置的用于截断opath路径的标志,注意这里可以接受lua魔法字符 +local distinguishSameNameFile = false; --是否区分lua同名文件中的断点,在VScode launch.json 中 distinguishSameNameFile 控制 +--标记位 +local logLevel = 1; --日志等级all/info/error. 此设置对应的是VSCode端设置的日志等级. +local variableRefIdx = 1; --变量索引 +local variableRefTab = {}; --变量记录table +local lastRunFilePath = ""; --最后执行的文件路径 +local pathCaseSensitivity = true; --路径是否发大小写敏感,这个选项接收VScode设置,请勿在此处更改 +local recvMsgQueue = {}; --接收的消息队列 +local coroutinePool = setmetatable({}, {__mode = "v"}); --保存用户协程的队列 +local winDiskSymbolUpper = false;--设置win下盘符的大小写。以此确保从VSCode中传入的断点路径,cwd和从lua虚拟机获得的文件路径盘符大小写一致 +local isNeedB64EncodeStr = false;-- 记录是否使用base64编码字符串 +local loadclibErrReason = 'launch.json文件的配置项useCHook被设置为false.'; +local OSTypeErrTip = ""; +local pathErrTip = "" +local winDiskSymbolTip = ""; +local isAbsolutePath = false; +local stopOnEntry; --用户在VSCode端设置的是否打开stopOnEntry +local userSetUseClib; --用户在VSCode端设置的是否是用clib库 +local autoPathMode = false; +local autoExt; --调试器启动时自动获取到的后缀, 用于检测lua虚拟机返回的路径是否带有文件后缀。他可以是空值或者".lua"等 +local luaProcessAsServer; +local testBreakpointFlag = false; -- 测试断点的标志位。结合 LuaPanda.testBreakpoint() 测试断点无法停止的原因 +--Step控制标记位 +local stepOverCounter = 0; --STEPOVER over计数器 +local stepOutCounter = 0; --STEPOVER out计数器 +local HOOK_LEVEL = 3; --调用栈偏移量,使用clib时为3,lua中不再使用此变量,而是通过函数getSpecificFunctionStackLevel获取 +local isUseLoadstring = 0; +local debugger_loadString; +--临时变量 +local recordBreakPointPath; --记录最后一个[可能命中]的断点,用于getInfo以及doctor的断点测试 +local coroutineCreate; --用来记录lua原始的coroutine.create函数 +local stopConnectTime = 0; --用来临时记录stop断开连接的时间 +local isInMainThread; +local receiveMsgTimer = 0; +local isUserSetClibPath = false; --用户是否在本文件中自设了clib路径 +local hitBpTwiceCheck; -- 命中断点的Vscode校验结果,默认true (true是命中,false是未命中) +local formatPathCache = {}; -- getinfo -> format +function this.formatPathCache() return formatPathCache; end +local fakeBreakPointCache = {}; --其中用 路径-{行号列表} 形式保存错误命中信息 +function this.fakeBreakPointCache() return fakeBreakPointCache; end +--5.1/5.3兼容 +if _VERSION == "Lua 5.1" then + debugger_loadString = loadstring; +else + debugger_loadString = load; +end + +--用户在控制台输入信息的环境变量 +local env = setmetatable({ }, { + __index = function( _ , varName ) + local ret = this.getWatchedVariable( varName, _G.LuaPanda.curStackId , false); + return ret; + end, + + __newindex = function( _ , varName, newValue ) + this.setVariableValue( varName, _G.LuaPanda.curStackId, newValue); + end +}); + +----------------------------------------------------------------------------- +-- 流程 +----------------------------------------------------------------------------- + +---this.bindServer 当lua进程作为Server时,server绑定函数 +--- server 在bind时创建, 连接成功后关闭listen , disconnect时置空。reconnect时会查询server,没有的话重新绑定,如果已存在直接accept +function this.bindServer(host, port) + server = sock + server:settimeout(listeningTimeoutSec); + assert(server:bind(host, port)); + server:setoption("reuseaddr", true); --防止已连接状态下新的连接进入,不再reuse + assert(server:listen(0)); +end + +-- 以lua作为服务端的形式启动调试器 +-- @host 绑定ip , 默认 0.0.0.0 +-- @port 绑定port, 默认 8818 +function this.startServer(host, port) + host = tostring(host or "0.0.0.0") ; + port = tonumber(port) or 8818; + luaProcessAsServer = true; + this.printToConsole("Debugger start as SERVER. bind host:" .. host .. " port:".. tostring(port), 1); + if sock ~= nil then + this.printToConsole("[Warning] 调试器已经启动,请不要再次调用start()" , 1); + return; + end + + --尝试初次连接 + this.changeRunState(runState.DISCONNECT); + if not this.reGetSock() then + this.printToConsole("[Error] LuaPanda debugger start success , but get Socket fail , please install luasocket!", 2); + return; + end + recordHost = host; + recordPort = port; + + this.bindServer(recordHost, recordPort); + local connectSuccess = server:accept(); + sock = connectSuccess; + + if connectSuccess then + this.printToConsole("First connect success!"); + this.connectSuccess(); + else + this.printToConsole("First connect failed!"); + this.changeHookState(hookState.DISCONNECT_HOOK); + end +end + +-- 启动调试器 +-- @host adapter端ip, 默认127.0.0.1 +-- @port adapter端port ,默认8818 +function this.start(host, port) + host = tostring(host or "127.0.0.1") ; + port = tonumber(port) or 8818; + this.printToConsole("Debugger start as CLIENT. connect host:" .. host .. " port:".. tostring(port), 1); + if sock ~= nil then + this.printToConsole("[Warning] 调试器已经启动,请不要再次调用start()" , 1); + return; + end + + --尝试初次连接 + this.changeRunState(runState.DISCONNECT); + if not this.reGetSock() then + this.printToConsole("[Error] Start debugger but get Socket fail , please install luasocket!", 2); + return; + end + recordHost = host; + recordPort = port; + + sock:settimeout(connectTimeoutSec); + local connectSuccess = this.sockConnect(sock); + + if connectSuccess then + this.printToConsole("First connect success!"); + this.connectSuccess(); + else + this.printToConsole("First connect failed!"); + this.changeHookState(hookState.DISCONNECT_HOOK); + end +end + +function this.sockConnect(sock) + if sock then + local connectSuccess, status = sock:connect(recordHost, recordPort); + if status == "connection refused" or (not connectSuccess and status == "already connected") then + this.reGetSock(); + end + + return connectSuccess + end + return nil; +end + +-- 连接成功,开始初始化 +function this.connectSuccess() + if server then + server:close(); -- 停止listen + end + + this.changeRunState(runState.WAIT_CMD); + this.printToConsole("connectSuccess", 1); + --设置初始状态 + local ret = this.debugger_wait_msg(); + + --获取debugger文件路径 + if DebuggerFileName == "" then + local info = debug.getinfo(1, "S") + for k,v in pairs(info) do + if k == "source" then + DebuggerFileName = tostring(v); + -- 从代码中去后缀 + autoExt = DebuggerFileName:gsub('.*[Ll][Uu][Aa][Pp][Aa][Nn][Dd][Aa]', ''); + + if hookLib ~= nil then + hookLib.sync_debugger_path(DebuggerFileName); + end + end + end + end + if DebuggerToolsName == "" then + DebuggerToolsName = tools.getFileSource(); + if hookLib ~= nil then + hookLib.sync_tools_path(DebuggerToolsName); + end + end + + if ret == false then + this.printToVSCode("[debugger error]初始化未完成, 建立连接但接收初始化消息失败。请更换端口重试", 2); + return; + end + this.printToVSCode("debugger init success", 1); + + this.changeHookState(hookState.ALL_HOOK); + if hookLib == nil then + --协程调试 + this.changeCoroutinesHookState(); + end + +end + +--重置数据 +function this.clearData() + OSType = nil; + clibPath = nil; + -- reset breaks + breaks = {}; + formatPathCache = {}; + fakeBreakPointCache = {}; + this.breaks = breaks; + if hookLib ~= nil then + hookLib.sync_breakpoints(); --清空断点信息 + hookLib.clear_pathcache(); --清空路径缓存 + end +end + +-- 本次连接过程中停止attach ,以提高运行效率 +function this.stopAttach() + openAttachMode = false; + this.printToConsole("Debugger stopAttach", 1); + this.clearData() + this.changeHookState( hookState.DISCONNECT_HOOK ); + stopConnectTime = os.time(); + this.changeRunState(runState.DISCONNECT); + if sock ~= nil then + sock:close(); + if luaProcessAsServer and server then server = nil; end; + end +end + +--断开连接 +function this.disconnect() + this.printToConsole("Debugger disconnect", 1); + this.clearData() + this.changeHookState( hookState.DISCONNECT_HOOK ); + stopConnectTime = os.time(); + this.changeRunState(runState.DISCONNECT); + + if sock ~= nil then + sock:close(); + sock = nil; + server = nil; + end + + if recordHost == nil or recordPort == nil then + --异常情况处理, 在调用LuaPanda.start()前首先调用了LuaPanda.disconnect() + this.printToConsole("[Warning] User call LuaPanda.disconnect() before set debug ip & port, please call LuaPanda.start() first!", 2); + return; + end + + this.reGetSock(); +end + +function this.replaceCoroutineFuncs() + if hookLib == nil then + if coroutineCreate == nil and type(coroutine.create) == "function" then + this.printToConsole("change coroutine.create"); + coroutineCreate = coroutine.create; + coroutine.create = function(...) + local co = coroutineCreate(...) + table.insert(coroutinePool, co); + --运行状态下,创建协程即启动hook + this.changeCoroutineHookState(co, currentHookState); + return co; + end + end + end +end + +----------------------------------------------------------------------------- +-- 调试器通用方法 +----------------------------------------------------------------------------- +-- 返回断点信息 +function this.getBreaks() + return breaks; +end + +---testBreakpoint 测试断点 +function this.testBreakpoint() + if recordBreakPointPath and recordBreakPointPath ~= "" then + -- testBreakpointFlag = false; + return this.breakpointTestInfo(); + else + local strTable = {}; + strTable[#strTable + 1] = "正在准备进行断点测试,请按照如下步骤操作\n" + strTable[#strTable + 1] = "1. 请[删除]当前项目中所有断点;\n" + strTable[#strTable + 1] = "2. 在当前停止行打一个断点;\n" + strTable[#strTable + 1] = "3. 再次运行 'LuaPanda.testBreakpoint()'" + testBreakpointFlag = true; + + return table.concat(strTable); + end +end + +-- 返回路径相关信息 +-- cwd:配置的工程路径 | info["source"]:通过 debug.getinfo 获得执行文件的路径 | format:格式化后的文件路径 +function this.breakpointTestInfo() + local ly = this.getSpecificFunctionStackLevel(lastRunFunction.func); + if type(ly) ~= "number" then + ly = 2; + end + local runSource = lastRunFunction["source"]; + if runSource == nil and hookLib ~= nil then + runSource = this.getPath(tostring(hookLib.get_last_source())); + end + local info = debug.getinfo(ly, "S"); + local NormalizedPath = this.formatOpath(info["source"]); + NormalizedPath = this.truncatedPath(NormalizedPath, truncatedOPath); + + local strTable = {} + local FormatedPath = tostring(runSource); + strTable[#strTable + 1] = "\n- BreakPoint Test:" + strTable[#strTable + 1] = "\nUser set lua extension: ." .. tostring(luaFileExtension); + strTable[#strTable + 1] = "\nAuto get lua extension: " .. tostring(autoExt); + if truncatedOPath and truncatedOPath ~= '' then + strTable[#strTable + 1] = "\nUser set truncatedOPath: " .. truncatedOPath; + end + strTable[#strTable + 1] = "\nGetInfo: ".. info["source"]; + strTable[#strTable + 1] = "\nNormalized: " .. NormalizedPath; + strTable[#strTable + 1] = "\nFormated: " .. FormatedPath; + if recordBreakPointPath and recordBreakPointPath ~= "" then + strTable[#strTable + 1] = "\nBreakpoint: " .. recordBreakPointPath; + end + + if not autoPathMode then + if isAbsolutePath then + strTable[#strTable + 1] = "\n说明:从lua虚拟机获取到的是绝对路径,Formated使用GetInfo路径。" .. winDiskSymbolTip; + else + strTable[#strTable + 1] = "\n说明:从lua虚拟机获取到的路径(GetInfo)是相对路径,调试器运行依赖的绝对路径(Formated)是来源于cwd+GetInfo拼接。如Formated路径错误请尝试调整cwd或改变VSCode打开文件夹的位置。也可以在Formated对应的文件下打一个断点,调整直到Formated和Breaks Info中断点路径完全一致。" .. winDiskSymbolTip; + end + else + strTable[#strTable + 1] = "\n说明:自动路径(autoPathMode)模式已开启。"; + if recordBreakPointPath and recordBreakPointPath ~= "" then + if string.find(recordBreakPointPath , FormatedPath, (-1) * string.len(FormatedPath) , true) then + -- 短路径断点命中 + if distinguishSameNameFile == false then + strTable[#strTable + 1] = "本文件中断点可正常命中。" + strTable[#strTable + 1] = "同名文件中的断点识别(distinguishSameNameFile) 未开启,请确保 VSCode 断点不要存在于同名 lua 文件中。"; + else + strTable[#strTable + 1] = "同名文件中的断点识别(distinguishSameNameFile) 已开启。"; + if string.find(recordBreakPointPath, NormalizedPath, 1, true) then + strTable[#strTable + 1] = "本文件中断点可被正常命中" + else + strTable[#strTable + 1] = "断点可能无法被命中,因为 lua 虚拟机中获得的路径 Normalized 不是断点路径 Breakpoint 的子串。 如有需要,可以在 launch.json 中设置 truncatedOPath 来去除 Normalized 部分路径。" + end + end + else + strTable[#strTable + 1] = "断点未被命中,原因是 Formated 不是 Breakpoint 路径的子串,或者 Formated 和 Breakpoint 文件后缀不一致" + end + else + strTable[#strTable + 1] = "如果要进行断点测试,请使用 LuaPanda.testBreakpoint()。" + end + end + return table.concat(strTable) +end + +--返回版本号等配置 +function this.getBaseInfo() + local strTable = {}; + local jitVer = ""; + if jit and jit.version then + jitVer = "," .. tostring(jit.version); + end + + strTable[#strTable + 1] = "Lua Ver:" .. _VERSION .. jitVer .." | Adapter Ver:" .. tostring(adapterVer) .. " | Debugger Ver:" .. tostring(debuggerVer); + local moreInfoStr = ""; + if hookLib ~= nil then + local clibVer, forluaVer = hookLib.sync_getLibVersion(); + local clibStr = forluaVer ~= nil and tostring(clibVer) .. " for " .. tostring(math.ceil(forluaVer)) or tostring(clibVer); + strTable[#strTable + 1] = " | hookLib Ver:" .. clibStr; + moreInfoStr = moreInfoStr .. "说明: 已加载 libpdebug 库."; + else + moreInfoStr = moreInfoStr .. "说明: 未能加载 libpdebug 库。原因请使用 LuaPanda.doctor() 查看"; + end + + local outputIsUseLoadstring = false + if type(isUseLoadstring) == "number" and isUseLoadstring == 1 then + outputIsUseLoadstring = true; + end + + strTable[#strTable + 1] = " | supportREPL:".. tostring(outputIsUseLoadstring); + strTable[#strTable + 1] = " | useBase64EncodeString:".. tostring(isNeedB64EncodeStr); + strTable[#strTable + 1] = " | codeEnv:" .. tostring(OSType); + strTable[#strTable + 1] = " | distinguishSameNameFile:" .. tostring(distinguishSameNameFile) .. '\n'; + + strTable[#strTable + 1] = moreInfoStr; + if OSTypeErrTip ~= nil and OSTypeErrTip ~= '' then + strTable[#strTable + 1] = '\n' ..OSTypeErrTip; + end + return table.concat(strTable); +end + +--自动诊断当前环境的错误,并输出信息 +function this.doctor() + local strTable = {}; + if debuggerVer ~= adapterVer then + strTable[#strTable + 1] = "\n- 建议更新版本\nLuaPanda VSCode插件版本是" .. adapterVer .. ", LuaPanda.lua文件版本是" .. debuggerVer .. "。建议检查并更新到最新版本。"; + strTable[#strTable + 1] = "\n更新方式 : https://github.com/Tencent/LuaPanda/blob/master/Docs/Manual/update.md"; + strTable[#strTable + 1] = "\nRelease版本: https://github.com/Tencent/LuaPanda/releases"; + end + --plibdebug + if hookLib == nil then + strTable[#strTable + 1] = "\n\n- libpdebug 库没有加载\n"; + if userSetUseClib then + --用户允许使用clib插件 + if isUserSetClibPath == true then + --用户自设了clib地址 + strTable[#strTable + 1] = "用户使用 LuaPanda.lua 中 clibPath 变量指定了 plibdebug 的位置: " .. clibPath; + if this.tryRequireClib("libpdebug", clibPath) then + strTable[#strTable + 1] = "\n引用成功"; + else + strTable[#strTable + 1] = "\n引用错误:" .. loadclibErrReason; + end + else + --使用默认clib地址 + local clibExt, platform; + if OSType == "Darwin" then clibExt = "/?.so;"; platform = "mac"; + elseif OSType == "Linux" then clibExt = "/?.so;"; platform = "linux"; + else clibExt = "/?.dll;"; platform = "win"; end + local lua_ver; + if _VERSION == "Lua 5.1" then + lua_ver = "501"; + else + lua_ver = "503"; + end + local x86Path = clibPath .. platform .."/x86/".. lua_ver .. clibExt; + local x64Path = clibPath .. platform .."/x86_64/".. lua_ver .. clibExt; + + strTable[#strTable + 1] = "尝试引用x64库: ".. x64Path; + if this.tryRequireClib("libpdebug", x64Path) then + strTable[#strTable + 1] = "\n引用成功"; + else + strTable[#strTable + 1] = "\n引用错误:" .. loadclibErrReason; + strTable[#strTable + 1] = "\n尝试引用x86库: ".. x86Path; + if this.tryRequireClib("libpdebug", x86Path) then + strTable[#strTable + 1] = "\n引用成功"; + else + strTable[#strTable + 1] = "\n引用错误:" .. loadclibErrReason; + end + end + end + else + strTable[#strTable + 1] = "原因是" .. loadclibErrReason; + end + end + + --path + --尝试直接读当前getinfo指向的文件,看能否找到。如果能,提示正确,如果找不到,给出提示,建议玩家在这个文件中打一个断点 + --检查断点,文件和当前文件的不同,给出建议 + local runSource = lastRunFilePath; + if hookLib ~= nil then + runSource = this.getPath(tostring(hookLib.get_last_source())); + end + + -- 在精确路径模式下的路径错误检测 + if not autoPathMode and runSource and runSource ~= "" then + -- 读文件 + local isFileExist = this.fileExists(runSource); + if not isFileExist then + strTable[#strTable + 1] = "\n\n- 路径存在问题\n"; + --解析路径,得到文件名,到断点路径中查这个文件名 + local pathArray = this.stringSplit(runSource, '/'); + --如果pathArray和断点能匹配上 + local fileMatch= false; + for key, _ in pairs(this.getBreaks()) do + if string.find(key, pathArray[#pathArray], 1, true) then + --和断点匹配了 + fileMatch = true; + -- retStr = retStr .. "\n请对比如下路径:\n"; + strTable[#strTable + 1] = this.breakpointTestInfo(); + strTable[#strTable + 1] = "\nfilepath: " .. key; + if isAbsolutePath then + strTable[#strTable + 1] = "\n说明:从lua虚拟机获取到的是绝对路径,format使用getinfo路径。"; + else + strTable[#strTable + 1] = "\n说明:从lua虚拟机获取到的是相对路径,调试器运行依赖的绝对路径(format)是来源于cwd+getinfo拼接。"; + end + strTable[#strTable + 1] = "\nfilepath是VSCode通过获取到的文件正确路径 , 对比format和filepath,调整launch.json中CWD,或改变VSCode打开文件夹的位置。使format和filepath一致即可。\n如果format和filepath路径仅大小写不一致,设置launch.json中 pathCaseSensitivity:false 可忽略路径大小写"; + end + end + + if fileMatch == false then + --未能和断点匹配 + strTable[#strTable + 1] = "\n找不到文件:" .. runSource .. ", 请检查路径是否正确。\n或者在VSCode文件" .. pathArray[#pathArray] .. "中打一个断点后,再执行一次doctor命令,查看路径分析结果。"; + end + end + end + + --日志等级对性能的影响 + if logLevel < 1 or consoleLogLevel < 1 then + strTable[#strTable + 1] = "\n\n- 日志等级\n"; + if logLevel < 1 then + strTable[#strTable + 1] = "当前日志等级是" .. logLevel .. ", 会产生大量日志,降低调试速度。建议调整launch.json中logLevel:1"; + end + if consoleLogLevel < 1 then + strTable[#strTable + 1] = "当前console日志等级是" .. consoleLogLevel .. ", 过低的日志等级会降低调试速度,建议调整LuaPanda.lua文件头部consoleLogLevel=2"; + end + end + + if #strTable == 0 then + strTable[#strTable + 1] = "未检测出问题"; + end + return table.concat(strTable); +end + +function this.fileExists(path) + local f=io.open(path,"r"); + if f~= nil then io.close(f) return true else return false end + end + +--返回一些信息,帮助用户定位问题 +function this.getInfo() + --用户设置项 + local strTable = {}; + strTable[#strTable + 1] = "\n- Base Info: \n"; + strTable[#strTable + 1] = this.getBaseInfo(); + --已经加载C库,x86/64 未能加载,原因 + strTable[#strTable + 1] = "\n\n- User Setting: \n"; + strTable[#strTable + 1] = "stopOnEntry:" .. tostring(stopOnEntry) .. ' | '; + -- strTable[#strTable + 1] = "luaFileExtension:" .. luaFileExtension .. ' | '; + strTable[#strTable + 1] = "logLevel:" .. logLevel .. ' | ' ; + strTable[#strTable + 1] = "consoleLogLevel:" .. consoleLogLevel .. ' | '; + strTable[#strTable + 1] = "pathCaseSensitivity:" .. tostring(pathCaseSensitivity) .. ' | '; + strTable[#strTable + 1] = "attachMode:".. tostring(openAttachMode).. ' | '; + strTable[#strTable + 1] = "autoPathMode:".. tostring(autoPathMode).. ' | '; + + if userSetUseClib then + strTable[#strTable + 1] = "useCHook:true"; + else + strTable[#strTable + 1] = "useCHook:false"; + end + + if logLevel == 0 or consoleLogLevel == 0 then + strTable[#strTable + 1] = "\n说明:日志等级过低,会影响执行效率。请调整logLevel和consoleLogLevel值 >= 1"; + end + + strTable[#strTable + 1] = "\n\n- Path Info: \n"; + strTable[#strTable + 1] = "clibPath: " .. tostring(clibPath) .. '\n'; + strTable[#strTable + 1] = "debugger: " .. DebuggerFileName .. " | " .. this.getPath(DebuggerFileName) .. '\n'; + strTable[#strTable + 1] = "cwd : " .. cwd .. '\n'; + strTable[#strTable + 1] = this.breakpointTestInfo(); + + if pathErrTip ~= nil and pathErrTip ~= '' then + strTable[#strTable + 1] = '\n' .. pathErrTip; + end + + strTable[#strTable + 1] = "\n\n- Breaks Info: \nUse 'LuaPanda.getBreaks()' to watch."; + return table.concat(strTable); +end + +--判断是否在协程中 +function this.isInMain() + return isInMainThread; +end + +--添加路径,尝试引用库。完成后把cpath还原,返回引用结果true/false +-- @libName 库名 +-- path lib的cpath路径 +function this.tryRequireClib(libName , libPath) + this.printToVSCode("tryRequireClib search : [" .. libName .. "] in "..libPath); + local savedCpath = package.cpath; + package.cpath = package.cpath .. ';' .. libPath; + this.printToVSCode("package.cpath:" .. package.cpath); + local status, err = pcall(function() hookLib = require(libName) end); + if status then + if type(hookLib) == "table" and this.getTableMemberNum(hookLib) > 0 then + this.printToVSCode("tryRequireClib success : [" .. libName .. "] in "..libPath); + package.cpath = savedCpath; + return true; + else + loadclibErrReason = "tryRequireClib fail : require success, but member function num <= 0; [" .. libName .. "] in "..libPath; + this.printToVSCode(loadclibErrReason); + hookLib = nil; + package.cpath = savedCpath; + return false; + end + else + -- 此处考虑到tryRequireClib会被调用两次,日志级别设置为0,防止输出不必要的信息。 + loadclibErrReason = err; + this.printToVSCode("[Require clib error]: " .. err, 0); + end + package.cpath = savedCpath; + return false +end +------------------------字符串处理------------------------- +-- 倒序查找字符串 a.b/c查找/ , 返回4 +-- @str 被查找的长串 +-- @subPattern 查找的子串, 也可以是pattern +-- @plain plane text / pattern +-- @return 未找到目标串返回nil. 否则返回倒序找到的字串位置 +function this.revFindString(str, subPattern, plain) + local revStr = string.reverse(str); + local _, idx = string.find(revStr, subPattern, 1, plain); + if idx == nil then return nil end; + return string.len(revStr) - idx + 1; +end + +-- 反序裁剪字符串 如:print(subString("a.b/c", "/"))输出c +-- @return 未找到目标串返回nil. 否则返回被裁剪后的字符串 +function this.revSubString(str, subStr, plain) + local idx = this.revFindString(str, subStr, plain) + if idx == nil then return nil end; + return string.sub(str, idx + 1, str.length) +end + +-- 把字符串按reps分割成并放入table +-- @str 目标串 +-- @reps 分割符。注意这个分隔符是一个pattern +function this.stringSplit( str, separator ) + local retStrTable = {} + string.gsub(str, '[^' .. separator ..']+', function ( word ) + table.insert(retStrTable, word) + end) + return retStrTable; +end + +-- 保存CallbackId(通信序列号) +function this.setCallbackId( id ) + if id ~= nil and id ~= "0" then + recCallbackId = tostring(id); + end +end + +-- 读取CallbackId(通信序列号)。读取后记录值将被置空 +function this.getCallbackId() + if recCallbackId == nil then + recCallbackId = "0"; + end + local id = recCallbackId; + recCallbackId = "0"; + return id; +end + +-- reference from https://www.lua.org/pil/20.1.html +function this.trim (s) + return (string.gsub(s, "^%s*(.-)%s*$", "%1")) +end + +--返回table中成员数量(数字key和非数字key之和) +-- @t 目标table +-- @return 元素数量 +function this.getTableMemberNum(t) + local retNum = 0; + if type(t) ~= "table" then + this.printToVSCode("[debugger Error] getTableMemberNum get "..tostring(type(t)), 2) + return retNum; + end + for k,v in pairs(t) do + retNum = retNum + 1; + end + return retNum; +end + +-- 生成一个消息Table +function this.getMsgTable(cmd ,callbackId) + callbackId = callbackId or 0; + local msgTable = {}; + msgTable["cmd"] = cmd; + msgTable["callbackId"] = callbackId; + msgTable["info"] = {}; + return msgTable; +end + +function this.serializeTable(tab, name) + local sTable = tools.serializeTable(tab, name); + return sTable; +end +------------------------日志打印相关------------------------- +-- 把日志打印在VSCode端 +-- @str: 日志内容 +-- @printLevel: all(0)/info(1)/error(2) +-- @type: 0:vscode console 1:vscode tip +function this.printToVSCode(str, printLevel, type) + type = type or 0; + printLevel = printLevel or 0; + if currentRunState == runState.DISCONNECT or logLevel > printLevel then + return; + end + + local sendTab = {}; + sendTab["callbackId"] = "0"; + if type == 0 then + sendTab["cmd"] = "output"; + elseif type == 1 then + sendTab["cmd"] = "tip"; + else -- type == 2 + sendTab["cmd"] = "debug_console"; + end + sendTab["info"] = {}; + sendTab["info"]["logInfo"] = tostring(str); + this.sendMsg(sendTab); +end + +-- 把日志打印在控制台 +-- @str: 日志内容 +-- @printLevel: all(0)/info(1)/error(2) +function this.printToConsole(str, printLevel) + printLevel = printLevel or 0; + if consoleLogLevel > printLevel then + return; + end + print("[LuaPanda] ".. tostring(str)); +end + +----------------------------------------------------------------------------- +-- 提升兼容性方法 +----------------------------------------------------------------------------- +--生成平台无关的路径。 +--return:nil(error)/path +function this.genUnifiedPath(path) + if path == "" or path == nil then + return ""; + end + --大小写不敏感时,路径全部转为小写 + if pathCaseSensitivity == false then + path = string.lower(path); + end + --统一路径全部替换成/ + path = string.gsub(path, [[\]], "/"); + --处理 /../ /./ + local pathTab = this.stringSplit(path, '/'); + local newPathTab = {}; + for k, v in ipairs(pathTab) do + if v == '.' then + --continue + elseif v == ".." and #newPathTab >= 1 and newPathTab[#newPathTab]:sub(2,2) ~= ':' then + --newPathTab有元素,最后一项不是X: + table.remove(newPathTab); + else + table.insert(newPathTab, v); + end + end + --重新拼合后如果是mac路径第一位是/ + local newpath = table.concat(newPathTab, '/'); + if path:sub(1,1) == '/' then + newpath = '/'.. newpath; + end + + --win下按照winDiskSymbolUpper的设置修改盘符大小 + if "Windows_NT" == OSType then + if winDiskSymbolUpper then + newpath = newpath:gsub("^%a:", string.upper); + winDiskSymbolTip = "路径中Windows盘符已转为大写。" + else + newpath = newpath:gsub("^%a:", string.lower); + winDiskSymbolTip = "路径中Windows盘符已转为小写。" + end + end + + return newpath; +end + +function this.getCacheFormatPath(source) + if source == nil then return formatPathCache end; + return formatPathCache[source]; +end + +function this.setCacheFormatPath(source, dest) + formatPathCache[source] = dest; +end + +-- 处理 opath(info.source) 的函数, 生成一个规范的路径函数(和VScode端checkRightPath逻辑完全一致) +function this.formatOpath(opath) + -- delete @ + if opath:sub(1,1) == '@' then + opath = opath:sub(2); + end + -- change ./ to / + if opath:sub(1,2) == './' then + opath = opath:sub(2); + end + + opath = this.genUnifiedPath(opath); + + -- lower + if pathCaseSensitivity == false then + opath = string.lower(opath); + end + --把filename去除后缀 + if autoExt == nil or autoExt == '' then + -- 在虚拟机返回路径没有后缀的情况下,用户必须自设后缀 + -- 确定filePath中最后一个.xxx 不等于用户配置的后缀, 则把所有的. 转为 / + if not opath:find(luaFileExtension , (-1) * luaFileExtension:len(), true) then + -- getinfo 路径没有后缀,把 . 全部替换成 / ,我们不允许用户在文件(或文件夹)名称中出现"." , 因为无法区分 + opath = string.gsub(opath, "%.", "/"); + else + -- 有后缀,那么把除后缀外的部分中的. 转为 / + opath = this.changePotToSep(opath, luaFileExtension); + end + else + -- 虚拟机路径有后缀 + opath = this.changePotToSep(opath, autoExt); + end + + -- 截取 路径+文件名 (不带后缀) + -- change pot to / + -- opath = string.gsub(opath, "%.", "/"); + return opath; +end + +----------------------------------------------------------------------------- +-- 内存相关 +----------------------------------------------------------------------------- +function this.sendLuaMemory() + local luaMem = collectgarbage("count"); + local sendTab = {}; + sendTab["callbackId"] = "0"; + sendTab["cmd"] = "refreshLuaMemory"; + sendTab["info"] = {}; + sendTab["info"]["memInfo"] = tostring(luaMem); + this.sendMsg(sendTab); +end + +----------------------------------------------------------------------------- +-- 网络相关方法 +----------------------------------------------------------------------------- +-- 刷新socket +-- @return true/false 刷新成功/失败 +function this.reGetSock() + if server then return true end + + if sock ~= nil then + pcall(function() sock:close() end); + end + + --call slua-unreal luasocket + sock = lua_extension and lua_extension.luasocket and lua_extension.luasocket().tcp(); + if sock == nil then + --call normal luasocket + if pcall(function() sock = require("socket_core").tcp(); end) then + this.printToConsole("reGetSock success"); + else + --call custom function to get socket + if customGetSocketInstance and pcall( function() sock = customGetSocketInstance(); end ) then + this.printToConsole("reGetSock custom success"); + else + this.printToConsole("[Error] reGetSock fail", 2); + return false; + end + end + else + --set ue4 luasocket + this.printToConsole("reGetSock ue4 success"); + end + return true; +end + +-- 定时(以函数return为时机) 进行attach连接 +-- 返回值 hook 可以继续往下走时返回1 ,无需继续时返回0 +function this.reConnect() + if currentHookState == hookState.DISCONNECT_HOOK then + if os.time() - stopConnectTime < attachInterval then + -- 未到重连时间 + -- this.printToConsole("Reconnect time less than 1s"); + -- this.printToConsole("os.time:".. os.time() .. " | stopConnectTime:" ..stopConnectTime); + return 0; + end + this.printToConsole("Reconnect !"); + if sock == nil then + this.reGetSock(); + end + + local connectSuccess; + if luaProcessAsServer == true and currentRunState == runState.DISCONNECT then + -- 在 Server 模式下,以及当前处于未连接状态下,才尝试accept新链接。如果不判断可能会出现多次连接,导致sock被覆盖 + if server == nil then + this.bindServer(recordHost, recordPort); + end + + sock = server:accept(); + connectSuccess = sock; + else + sock:settimeout(connectTimeoutSec); + connectSuccess = this.sockConnect(sock); + end + + if connectSuccess then + this.printToConsole("reconnect success"); + this.connectSuccess(); + return 1; + else + this.printToConsole("reconnect failed" ); + stopConnectTime = os.time(); + return 0; + end + end + -- 不必重连,正常继续运行 + return 1; +end + +-- 向adapter发消息 +-- @sendTab 消息体table +function this.sendMsg( sendTab ) + if isNeedB64EncodeStr and sendTab["info"] ~= nil then + for _, v in ipairs(sendTab["info"]) do + if v["type"] == "string" then + v["value"] = tools.base64encode(v["value"]) + end + end + end + + local sendStr = json.encode(sendTab); + if currentRunState == runState.DISCONNECT then + this.printToConsole("[debugger error] disconnect but want sendMsg:" .. sendStr, 2); + this.disconnect(); + return; + end + + local succ,err; + if pcall(function() succ,err = sock:send(sendStr..TCPSplitChar.."\n"); end) then + if succ == nil then + if err == "closed" then + this.disconnect(); + end + end + end +end + +-- 处理 收到的消息 +-- @dataStr 接收的消息json +function this.dataProcess( dataStr ) + this.printToVSCode("debugger get:"..dataStr); + local dataTable = json.decode(dataStr); + if dataTable == nil then + this.printToVSCode("[error] Json is error", 2); + return; + end + + if dataTable.callbackId ~= "0" then + this.setCallbackId(dataTable.callbackId); + end + + if dataTable.cmd == "continue" then + local info = dataTable.info; + if info.isFakeHit == "true" and info.fakeBKPath and info.fakeBKLine then + -- 设置校验结果标志位,以便hook流程知道结果 + hitBpTwiceCheck = false; + if hookLib ~= nil and hookLib.set_bp_twice_check_res then + -- 把结果同步给C + hookLib.set_bp_twice_check_res(0); + end + -- 把假断点的信息加入cache + if nil == fakeBreakPointCache[info.fakeBKPath] then + fakeBreakPointCache[info.fakeBKPath] = {}; + end + table.insert(fakeBreakPointCache[info.fakeBKPath] ,info.fakeBKLine); + else + this.changeRunState(runState.RUN); + end + local msgTab = this.getMsgTable("continue", this.getCallbackId()); + this.sendMsg(msgTab); + + elseif dataTable.cmd == "stopOnStep" then + this.changeRunState(runState.STEPOVER); + local msgTab = this.getMsgTable("stopOnStep", this.getCallbackId()); + this.sendMsg(msgTab); + this.changeHookState(hookState.ALL_HOOK); + + elseif dataTable.cmd == "stopOnStepIn" then + this.changeRunState(runState.STEPIN); + local msgTab = this.getMsgTable("stopOnStepIn", this.getCallbackId()); + this.sendMsg(msgTab); + this.changeHookState(hookState.ALL_HOOK); + + elseif dataTable.cmd == "stopOnStepOut" then + this.changeRunState(runState.STEPOUT); + local msgTab = this.getMsgTable("stopOnStepOut", this.getCallbackId()); + this.sendMsg(msgTab); + this.changeHookState(hookState.ALL_HOOK); + + elseif dataTable.cmd == "setBreakPoint" then + this.printToVSCode("dataTable.cmd == setBreakPoint"); + -- 设置断点时,把 fakeBreakPointCache 清空。这是一个简单的做法,也可以清除具体的条目 + fakeBreakPointCache = {} + local bkPath = dataTable.info.path; + bkPath = this.genUnifiedPath(bkPath); + if testBreakpointFlag then + recordBreakPointPath = bkPath; + end + if autoPathMode then + -- 自动路径模式下,仅保留文件名 + -- table[文件名.后缀] -- [fullpath] -- [line , type] + -- | - [fullpath] -- [line , type] + + local bkShortPath = this.getFilenameFromPath(bkPath); + if breaks[bkShortPath] == nil then + breaks[bkShortPath] = {}; + end + breaks[bkShortPath][bkPath] = dataTable.info.bks; + -- 当v为空时,从断点列表中去除文件 + for k, v in pairs(breaks[bkShortPath]) do + if next(v) == nil then + breaks[bkShortPath][k] = nil; + end + end + else + if breaks[bkPath] == nil then + breaks[bkPath] = {}; + end + -- 两级 bk path 是为了和自动路径模式结构保持一致 + breaks[bkPath][bkPath] = dataTable.info.bks; + -- 当v为空时,从断点列表中去除文件 + for k, v in pairs(breaks[bkPath]) do + if next(v) == nil then + breaks[bkPath][k] = nil; + end + end + end + + -- 当v为空时,从断点列表中去除文件 + for k, v in pairs(breaks) do + if next(v) == nil then + breaks[k] = nil; + end + end + + --sync breaks to c + if hookLib ~= nil then + hookLib.sync_breakpoints(); + end + + if currentRunState ~= runState.WAIT_CMD then + if hookLib == nil then + local fileBP, G_BP =this.checkHasBreakpoint(lastRunFilePath); + if fileBP == false then + if G_BP == true then + this.changeHookState(hookState.MID_HOOK); + else + this.changeHookState(hookState.LITE_HOOK); + end + else + this.changeHookState(hookState.ALL_HOOK); + end + end + else + local msgTab = this.getMsgTable("setBreakPoint", this.getCallbackId()); + this.sendMsg(msgTab); + return; + end + --其他时机收到breaks消息 + local msgTab = this.getMsgTable("setBreakPoint", this.getCallbackId()); + this.sendMsg(msgTab); + -- 打印调试信息 + this.printToVSCode("LuaPanda.getInfo()\n" .. this.getInfo()) + this.debugger_wait_msg(); + elseif dataTable.cmd == "setVariable" then + if currentRunState == runState.STOP_ON_ENTRY or + currentRunState == runState.HIT_BREAKPOINT or + currentRunState == runState.STEPOVER_STOP or + currentRunState == runState.STEPIN_STOP or + currentRunState == runState.STEPOUT_STOP then + local msgTab = this.getMsgTable("setVariable", this.getCallbackId()); + local varRefNum = tonumber(dataTable.info.varRef); + local newValue = tostring(dataTable.info.newValue); + local needFindVariable = true; --如果变量是基础类型,直接赋值,needFindVariable = false; 如果变量是引用类型,needFindVariable = true + local varName = tostring(dataTable.info.varName); + -- 根据首末含有" ' 判断 newValue 是否是字符串 + local first_chr = string.sub(newValue, 1, 1); + local end_chr = string.sub(newValue, -1, -1); + if first_chr == end_chr then + if first_chr == "'" or first_chr == '"' then + newValue = string.sub(newValue, 2, -2); + needFindVariable = false; + end + end + --数字,nil,false,true的处理 + if newValue == "nil" and needFindVariable == true then newValue = nil; needFindVariable = false; + elseif newValue == "true" and needFindVariable == true then newValue = true; needFindVariable = false; + elseif newValue == "false" and needFindVariable == true then newValue = false; needFindVariable = false; + elseif tonumber(newValue) and needFindVariable == true then newValue = tonumber(newValue); needFindVariable = false; + end + + -- 如果新值是基础类型,则不需遍历 + if dataTable.info.stackId ~= nil and tonumber(dataTable.info.stackId) ~= nil and tonumber(dataTable.info.stackId) > 1 then + this.curStackId = tonumber(dataTable.info.stackId); + else + this.printToVSCode("未能获取到堆栈层级,默认使用 this.curStackId;") + end + + if varRefNum < 10000 then + -- 如果修改的是一个 引用变量,那么可直接赋值。但还是要走变量查询过程。查找和赋值过程都需要steakId。 目前给引用变量赋值Object,steak可能有问题 + msgTab.info = this.createSetValueRetTable(varName, newValue, needFindVariable, this.curStackId, variableRefTab[varRefNum]); + else + -- 如果修改的是一个基础类型 + local setLimit; --设置检索变量的限定区域 + if varRefNum >= 10000 and varRefNum < 20000 then setLimit = "local"; + elseif varRefNum >= 20000 and varRefNum < 30000 then setLimit = "global"; + elseif varRefNum >= 30000 then setLimit = "upvalue"; + end + msgTab.info = this.createSetValueRetTable(varName, newValue, needFindVariable, this.curStackId, nil, setLimit); + end + + this.sendMsg(msgTab); + this.debugger_wait_msg(); + end + + elseif dataTable.cmd == "getVariable" then + --仅在停止时处理消息,其他时刻收到此消息,丢弃 + if currentRunState == runState.STOP_ON_ENTRY or + currentRunState == runState.HIT_BREAKPOINT or + currentRunState == runState.STEPOVER_STOP or + currentRunState == runState.STEPIN_STOP or + currentRunState == runState.STEPOUT_STOP then + --发送变量给游戏,并保持之前的状态,等待再次接收数据 + --dataTable.info.varRef 10000~20000局部变量 + -- 20000~30000全局变量 + -- 30000~ upvalue + -- 1000~2000局部变量的查询,2000~3000全局,3000~4000upvalue + local msgTab = this.getMsgTable("getVariable", this.getCallbackId()); + local varRefNum = tonumber(dataTable.info.varRef); + if varRefNum < 10000 then + --查询变量, 此时忽略 stackId + local varTable = this.getVariableRef(dataTable.info.varRef, true); + msgTab.info = varTable; + elseif varRefNum >= 10000 and varRefNum < 20000 then + --局部变量 + if dataTable.info.stackId ~= nil and tonumber(dataTable.info.stackId) > 1 then + this.curStackId = tonumber(dataTable.info.stackId); + if type(currentCallStack[this.curStackId - 1]) ~= "table" or type(currentCallStack[this.curStackId - 1].func) ~= "function" then + local str = "getVariable getLocal currentCallStack " .. this.curStackId - 1 .. " Error\n" .. this.serializeTable(currentCallStack, "currentCallStack"); + this.printToVSCode(str, 2); + msgTab.info = {}; + else + local stackId = this.getSpecificFunctionStackLevel(currentCallStack[this.curStackId - 1].func); --去除偏移量 + local varTable = this.getVariable(stackId, true); + msgTab.info = varTable; + end + end + + elseif varRefNum >= 20000 and varRefNum < 30000 then + --全局变量 + local varTable = this.getGlobalVariable(); + msgTab.info = varTable; + elseif varRefNum >= 30000 then + --upValue + if dataTable.info.stackId ~= nil and tonumber(dataTable.info.stackId) > 1 then + this.curStackId = tonumber(dataTable.info.stackId); + if type(currentCallStack[this.curStackId - 1]) ~= "table" or type(currentCallStack[this.curStackId - 1].func) ~= "function" then + local str = "getVariable getUpvalue currentCallStack " .. this.curStackId - 1 .. " Error\n" .. this.serializeTable(currentCallStack, "currentCallStack"); + this.printToVSCode(str, 2); + msgTab.info = {}; + else + local varTable = this.getUpValueVariable(currentCallStack[this.curStackId - 1 ].func, true); + msgTab.info = varTable; + end + end + end + this.sendMsg(msgTab); + this.debugger_wait_msg(); + end + elseif dataTable.cmd == "initSuccess" then + --初始化会传过来一些变量,这里记录这些变量 + --Base64 + if dataTable.info.isNeedB64EncodeStr == "true" then + isNeedB64EncodeStr = true; + else + isNeedB64EncodeStr = false; + end + --path + luaFileExtension = dataTable.info.luaFileExtension; + local TempFilePath = dataTable.info.TempFilePath; + if TempFilePath:sub(-1, -1) == [[\]] or TempFilePath:sub(-1, -1) == [[/]] then + TempFilePath = TempFilePath:sub(1, -2); + end + TempFilePath_luaString = TempFilePath; + cwd = this.genUnifiedPath(dataTable.info.cwd); + --logLevel + logLevel = tonumber(dataTable.info.logLevel) or 1; + --autoPathMode + if dataTable.info.autoPathMode == "true" then + autoPathMode = true; + else + autoPathMode = false; + end + + if dataTable.info.pathCaseSensitivity == "true" then + pathCaseSensitivity = true; + truncatedOPath = dataTable.info.truncatedOPath or ""; + else + pathCaseSensitivity = false; + truncatedOPath = string.lower(dataTable.info.truncatedOPath or ""); + end + + if dataTable.info.distinguishSameNameFile == "true" then + distinguishSameNameFile = true; + else + distinguishSameNameFile = false; + end + + --OS type + if nil == OSType then + --用户未主动设置OSType, 接收VSCode传来的数据 + if type(dataTable.info.OSType) == "string" then + OSType = dataTable.info.OSType; + else + OSType = "Windows_NT"; + OSTypeErrTip = "未能检测出OSType, 可能是node os库未能加载,系统使用默认设置Windows_NT" + end + else + --用户自设OSType, 使用用户的设置 + end + + --检测用户是否自设了clib路径 + isUserSetClibPath = false; + if nil == clibPath then + --用户未设置clibPath, 接收VSCode传来的数据 + if type(dataTable.info.clibPath) == "string" then + clibPath = dataTable.info.clibPath; + else + clibPath = ""; + pathErrTip = "未能正确获取libpdebug库所在位置, 可能无法加载libpdebug库。"; + end + else + --用户自设clibPath + isUserSetClibPath = true; + end + + --查找c++的hook库是否存在. 当lua5.4时默认不使用c库 + if tostring(dataTable.info.useCHook) == "true" and "Lua 5.4" ~= _VERSION then + userSetUseClib = true; --用户确定使用clib + if isUserSetClibPath == true then --如果用户自设了clib路径 + if luapanda_chook ~= nil then + hookLib = luapanda_chook; + else + if not(this.tryRequireClib("libpdebug", clibPath)) then + this.printToVSCode("Require clib failed, use Lua to continue debug, use LuaPanda.doctor() for more information.", 1); + end + end + else + local clibExt, platform; + if OSType == "Darwin" then clibExt = "/?.so;"; platform = "mac"; + elseif OSType == "Linux" then clibExt = "/?.so;"; platform = "linux"; + else clibExt = "/?.dll;"; platform = "win"; end + + local lua_ver; + if _VERSION == "Lua 5.1" then + lua_ver = "501"; + else + lua_ver = "503"; + end + + local x86Path = clibPath.. platform .."/x86/".. lua_ver .. clibExt; + local x64Path = clibPath.. platform .."/x86_64/".. lua_ver .. clibExt; + + if luapanda_chook ~= nil then + hookLib = luapanda_chook; + else + if not(this.tryRequireClib("libpdebug", x64Path) or this.tryRequireClib("libpdebug", x86Path)) then + this.printToVSCode("Require clib failed, use Lua to continue debug, use LuaPanda.doctor() for more information.", 1); + end + end + end + else + userSetUseClib = false; + end + + --adapter版本信息 + adapterVer = tostring(dataTable.info.adapterVersion); + local msgTab = this.getMsgTable("initSuccess", this.getCallbackId()); + --回传是否使用了lib,是否有loadstring函数 + local isUseHookLib = 0; + if hookLib ~= nil then + isUseHookLib = 1; + --同步数据给c hook + local luaVerTable = this.stringSplit(debuggerVer , '%.'); + local luaVerNum = luaVerTable[1] * 10000 + luaVerTable[2] * 100 + luaVerTable[3]; + if hookLib.sync_lua_debugger_ver then + hookLib.sync_lua_debugger_ver(luaVerNum); + end + -- hookLib.sync_config(logLevel, pathCaseSensitivity and 1 or 0, autoPathMode and 1 or 0); + hookLib.sync_config(logLevel, pathCaseSensitivity and 1 or 0); + hookLib.sync_tempfile_path(TempFilePath_luaString); + hookLib.sync_cwd(cwd); + hookLib.sync_file_ext(luaFileExtension); + end + --detect LoadString + isUseLoadstring = 0; + if debugger_loadString ~= nil and type(debugger_loadString) == "function" then + if(pcall(debugger_loadString("return 0"))) then + isUseLoadstring = 1; + end + end + local tab = { debuggerVer = tostring(debuggerVer) , UseHookLib = tostring(isUseHookLib) , UseLoadstring = tostring(isUseLoadstring), isNeedB64EncodeStr = tostring(isNeedB64EncodeStr) }; + msgTab.info = tab; + this.sendMsg(msgTab); + --上面getBK中会判断当前状态是否WAIT_CMD, 所以最后再切换状态。 + stopOnEntry = dataTable.info.stopOnEntry; + if dataTable.info.stopOnEntry == "true" then + this.changeRunState(runState.STOP_ON_ENTRY); --停止在STOP_ON_ENTRY再接收breaks消息 + else + this.debugger_wait_msg(1); --等待1s bk消息 如果收到或超时(没有断点)就开始运行 + this.changeRunState(runState.RUN); + end + + elseif dataTable.cmd == "getWatchedVariable" then + local msgTab = this.getMsgTable("getWatchedVariable", this.getCallbackId()); + local stackId = tonumber(dataTable.info.stackId); + --loadstring系统函数, watch插件加载 + if isUseLoadstring == 1 then + --使用loadstring + this.curStackId = stackId; + local retValue = this.processWatchedExp(dataTable.info); + msgTab.info = retValue + this.sendMsg(msgTab); + this.debugger_wait_msg(); + return; + else + --旧的查找方式 + local wv = this.getWatchedVariable(dataTable.info.varName, stackId, true); + if wv ~= nil then + msgTab.info = wv; + end + this.sendMsg(msgTab); + this.debugger_wait_msg(); + end + elseif dataTable.cmd == "stopRun" then + --停止hook,已不在处理任何断点信息,也就不会产生日志等。发送消息后等待前端主动断开连接 + local msgTab = this.getMsgTable("stopRun", this.getCallbackId()); + this.sendMsg(msgTab); + if not luaProcessAsServer then + this.disconnect(); + end + elseif "LuaGarbageCollect" == dataTable.cmd then + this.printToVSCode("collect garbage!"); + collectgarbage("collect"); + --回收后刷一下内存 + this.sendLuaMemory(); + this.debugger_wait_msg(); + elseif "runREPLExpression" == dataTable.cmd then + this.curStackId = tonumber(dataTable.info.stackId); + local retValue = this.processExp(dataTable.info); + local msgTab = this.getMsgTable("runREPLExpression", this.getCallbackId()); + msgTab.info = retValue + this.sendMsg(msgTab); + this.debugger_wait_msg(); + else + end +end + +-- 变量赋值的处理函数。基本逻辑是先从当前栈帧(curStackId)中取 newValue 代表的变量,找到之后再把找到的值通过setVariableValue写回。 +-- @varName 被设置值的变量名 +-- @newValue 新值的名字,它是一个string +-- @needFindVariable 是否需要查找引用变量。(用户输入的是否是一个Object) +-- @curStackId 当前栈帧(查找和变量赋值用) +-- @assigndVar 被直接赋值(省去查找过程) +-- @setLimit 赋值时的限制范围(local upvalue global) +function this.createSetValueRetTable(varName, newValue, needFindVariable, curStackId, assigndVar , setLimit) + local info; + local getVarRet; + -- needFindVariable == true,则使用getWatchedVariable处理(可选, 用来支持 a = b (b为变量的情况))。 + if needFindVariable == false then + getVarRet = {}; + getVarRet[1] = {variablesReference = 0, value = newValue, name = varName, type = type(newValue)}; + else + getVarRet = this.getWatchedVariable( tostring(newValue), curStackId, true); + end + if getVarRet ~= nil then + -- newValue赋变量真实值 + local realVarValue; + local displayVarValue = getVarRet[1].value; + if needFindVariable == true then + if tonumber(getVarRet[1].variablesReference) > 0 then + realVarValue = variableRefTab[tonumber(getVarRet[1].variablesReference)]; + else + if getVarRet[1].type == 'number' then realVarValue = tonumber(getVarRet[1].value) end + if getVarRet[1].type == 'string' then + realVarValue = tostring(getVarRet[1].value); + local first_chr = string.sub(realVarValue, 1, 1); + local end_chr = string.sub(realVarValue, -1, -1); + if first_chr == end_chr then + if first_chr == "'" or first_chr == '"' then + realVarValue = string.sub(realVarValue, 2, -2); + displayVarValue = realVarValue; + end + end + end + if getVarRet[1].type == 'boolean' then + if getVarRet[1].value == "true" then + realVarValue = true; + else + realVarValue = false; + end + end + if getVarRet[1].type == 'nil' then realVarValue = nil end + end + else + realVarValue = getVarRet[1].value; + end + + local setVarRet; + if type(assigndVar) ~= table then + setVarRet = this.setVariableValue( varName, curStackId, realVarValue, setLimit ); + else + assigndVar[varName] = realVarValue; + setVarRet = true; + end + + if getVarRet[1].type == "string" then + displayVarValue = '"' .. displayVarValue .. '"'; + end + + if setVarRet ~= false and setVarRet ~= nil then + local retTip = "变量 ".. varName .." 赋值成功"; + info = { success = "true", name = getVarRet[1].name , type = getVarRet[1].type , value = displayVarValue, variablesReference = tostring(getVarRet[1].variablesReference), tip = retTip}; + else + info = { success = "false", type = type(realVarValue), value = displayVarValue, tip = "找不到要设置的变量"}; + end + + else + info = { success = "false", type = nil, value = nil, tip = "输入的值无意义"}; + end + return info +end + +--接收消息 +--这里维护一个接收消息队列,因为Lua端未做隔断符保护,变量赋值时请注意其中不要包含隔断符 |*| +-- @timeoutSec 超时时间 +-- @return boolean 成功/失败 +function this.receiveMessage( timeoutSec ) + timeoutSec = timeoutSec or MAX_TIMEOUT_SEC; + sock:settimeout(timeoutSec); + --如果队列中还有消息,直接取出来交给dataProcess处理 + if #recvMsgQueue > 0 then + local saved_cmd = recvMsgQueue[1]; + table.remove(recvMsgQueue, 1); + this.dataProcess(saved_cmd); + return true; + end + + if currentRunState == runState.DISCONNECT then + this.disconnect(); + return false; + end + + if sock == nil then + this.printToConsole("[debugger error]接收信息失败 | reason: socket == nil", 2); + return; + end + local response, err = sock:receive("*l"); + if response == nil then + if err == "closed" then + this.printToConsole("[debugger error]接收信息失败 | reason:"..err, 2); + this.disconnect(); + end + return false; + else + + --判断是否是一条消息,分拆 + local proc_response = string.sub(response, 1, -1 * (TCPSplitChar:len() + 1 )); + local match_res = string.find(proc_response, TCPSplitChar, 1, true); + if match_res == nil then + --单条 + this.dataProcess(proc_response); + else + --有粘包 + repeat + --待处理命令 + local str1 = string.sub(proc_response, 1, match_res - 1); + table.insert(recvMsgQueue, str1); + --剩余匹配 + local str2 = string.sub(proc_response, match_res + TCPSplitChar:len() , -1); + match_res = string.find(str2, TCPSplitChar, 1, true); + until not match_res + this.receiveMessage(); + end + return true; + end +end + +--这里不用循环,在外面处理完消息会在调用回来 +-- @timeoutSec 等待时间s +-- @entryFlag 入口标记,用来标识是从哪里调入的 +function this.debugger_wait_msg(timeoutSec) + timeoutSec = timeoutSec or MAX_TIMEOUT_SEC; + + if currentRunState == runState.WAIT_CMD then + local ret = this.receiveMessage(timeoutSec); + return ret; + end + + if currentRunState == runState.STEPOVER or + currentRunState == runState.STEPIN or + currentRunState == runState.STEPOUT or + currentRunState == runState.RUN then + this.receiveMessage(0); + return + end + + if currentRunState == runState.STEPOVER_STOP or + currentRunState == runState.STEPIN_STOP or + currentRunState == runState.STEPOUT_STOP or + currentRunState == runState.HIT_BREAKPOINT or + currentRunState == runState.STOP_ON_ENTRY + then + this.sendLuaMemory(); + this.receiveMessage(MAX_TIMEOUT_SEC); + return + end +end + +----------------------------------------------------------------------------- +-- 调试器核心方法 +----------------------------------------------------------------------------- + +------------------------堆栈管理------------------------- + + +--getStackTable需要建立stackTable,保存每层的lua函数实例(用来取upvalue),保存函数展示层级和ly的关系(便于根据前端传来的stackId查局部变量) +-- @level 要获取的层级 +function this.getStackTable( level ) + local functionLevel = 0 + if hookLib ~= nil then + functionLevel = level or HOOK_LEVEL; + else + functionLevel = level or this.getSpecificFunctionStackLevel(lastRunFunction.func); + end + local stackTab = {}; + local userFuncSteakLevel = 0; --用户函数的steaklevel + local clevel = 0 + repeat + local info = debug.getinfo(functionLevel, "SlLnf") + if info == nil then + break; + end + if info.source ~= "=[C]" then + local ss = {}; + ss.file = this.getPath(info); + local oPathFormated = this.formatOpath(info.source) ; --从lua虚拟机获得的原始路径, 它用于帮助定位VScode端原始lua文件的位置(存在重名文件的情况)。 + ss.oPath = this.truncatedPath(oPathFormated, truncatedOPath); + ss.name = "文件名"; --这里要做截取 + ss.line = tostring(info.currentline); + --使用hookLib时,堆栈有偏移量,这里统一调用栈顶编号2 + local ssindex = functionLevel - 3; + if hookLib ~= nil then + ssindex = ssindex + 2; + end + ss.index = tostring(ssindex); + table.insert(stackTab,ss); + --把数据存入currentCallStack + local callStackInfo = {}; + callStackInfo.name = ss.file; + callStackInfo.line = ss.line; + callStackInfo.func = info.func; --保存的function + callStackInfo.realLy = functionLevel; --真实堆栈层functionLevel(仅debug时用) + table.insert(currentCallStack, callStackInfo); + + --level赋值 + if userFuncSteakLevel == 0 then + userFuncSteakLevel = functionLevel; + end + else + local callStackInfo = {}; + callStackInfo.name = info.source; + callStackInfo.line = info.currentline; --C函数行号 + callStackInfo.func = info.func; --保存的function + callStackInfo.realLy = functionLevel; --真实堆栈层functionLevel(仅debug时用) + table.insert(currentCallStack, callStackInfo); + clevel = clevel + 1 + end + functionLevel = functionLevel + 1; + until info == nil + return stackTab, userFuncSteakLevel; +end + +-- 把路径中去除后缀部分的.变为/, +-- @filePath 被替换的路径 +-- @ext 后缀(后缀前的 . 不会被替换) +function this.changePotToSep(filePath, ext) + local idx = filePath:find(ext, (-1) * ext:len() , true) + if idx then + local tmp = filePath:sub(1, idx - 1):gsub("%.", "/"); + filePath = tmp .. ext; + end + return filePath; +end + +--- this.truncatedPath 从 beTruncatedPath 字符串中去除 rep 匹配到的部分 +function this.truncatedPath(beTruncatedPath, rep) + if beTruncatedPath and beTruncatedPath ~= '' and rep and rep ~= "" then + local _, lastIdx = string.find(beTruncatedPath , rep); + if lastIdx then + beTruncatedPath = string.sub(beTruncatedPath, lastIdx + 1); + end + end + return beTruncatedPath; +end + +--这个方法是根据的cwd和luaFileExtension对getInfo获取到的路径进行标准化 +-- @info getInfo获取的包含调用信息table +function this.getPath( info ) + local filePath = info; + if type(info) == "table" then + filePath = info.source; + end + --尝试从Cache中获取路径 + local cachePath = this.getCacheFormatPath(filePath); + if cachePath~= nil and type(cachePath) == "string" then + return cachePath; + end + + -- originalPath是getInfo的原始路径,后面用来填充路径缓存的key + local originalPath = filePath; + + --如果路径头部有@,去除 + if filePath:sub(1,1) == '@' then + filePath = filePath:sub(2); + end + + --如果路径头部有./,去除 + if filePath:sub(1,2) == './' then + filePath = filePath:sub(3); + end + -- getPath的参数路径可能来自于hook, 也可能是一个已标准的路径 + if userDotInRequire then + if autoExt == nil or autoExt == '' then + -- 在虚拟机返回路径没有后缀的情况下,用户必须自设后缀 + -- 确定filePath中最后一个.xxx 不等于用户配置的后缀, 则把所有的. 转为 / + if not filePath:find(luaFileExtension , (-1) * luaFileExtension:len(), true) then + -- getinfo 路径没有后缀,把 . 全部替换成 / ,我们不允许用户在文件(或文件夹)名称中出现"." , 因为无法区分 + filePath = string.gsub(filePath, "%.", "/"); + else + -- 有后缀,那么把除后缀外的部分中的. 转为 / + filePath = this.changePotToSep(filePath, luaFileExtension); + end + + else + -- 虚拟机路径有后缀 + filePath = this.changePotToSep(filePath, autoExt); + end + end + + --后缀处理 + if luaFileExtension ~= "" then + --判断后缀中是否包含%1等魔法字符.用于从lua虚拟机获取到的路径含.的情况 + if string.find(luaFileExtension, "%%%d") then + filePath = string.gsub(filePath, "%.[%w%.]+$", luaFileExtension); + else + filePath = string.gsub(filePath, "%.[%w%.]+$", ""); + filePath = filePath .. "." .. luaFileExtension; + end + end + + + if not autoPathMode then + --绝对路径和相对路径的处理 | 若在Mac下以/开头,或者在Win下以*:开头,说明是绝对路径,不需要再拼。 + if filePath:sub(1,1) == [[/]] or filePath:sub(1,2):match("^%a:") then + isAbsolutePath = true; + else + isAbsolutePath = false; + if cwd ~= "" then + --查看filePath中是否包含cwd + local matchRes = string.find(filePath, cwd, 1, true); + if matchRes == nil then + filePath = cwd.."/"..filePath; + end + end + end + end + filePath = this.genUnifiedPath(filePath); + + if autoPathMode then + -- 自动路径模式下,只保留文件名 + filePath = this.getFilenameFromPath(filePath) + end + --放入Cache中缓存 + this.setCacheFormatPath(originalPath, filePath); + return filePath; +end + +--从路径中获取[文件名.后缀] +function this.getFilenameFromPath(path) + if path == nil then + return ''; + end + + return string.match(path, "([^/]*)$"); +end + +--获取当前函数的堆栈层级 +--原理是向上查找,遇到DebuggerFileName就调过。但是可能存在代码段和C导致不确定性。目前使用getSpecificFunctionStackLevel代替。 +function this.getCurrentFunctionStackLevel() + -- print(debug.traceback("===getCurrentFunctionStackLevel Stack trace===")) + local funclayer = 2; + repeat + local info = debug.getinfo(funclayer, "S"); --通过name来判断 + if info ~= nil then + local matchRes = ((info.source == DebuggerFileName) or (info.source == DebuggerToolsName)); + if matchRes == false then + return (funclayer - 1); + end + end + funclayer = funclayer + 1; + until not info + return 0; +end + +--获取指定函数的堆栈层级 +--通常用来获取最后一个用户函数的层级,用法是从currentCallStack取用户点击的栈,再使用本函数取对应层级。 +-- @func 被获取层级的function +function this.getSpecificFunctionStackLevel( func ) + local funclayer = 2; + repeat + local info = debug.getinfo(funclayer, "f"); --通过name来判断 + if info ~= nil then + if info.func == func then + return (funclayer - 1); + end + end + funclayer = funclayer + 1; + until not info + return 0; +end + +--检查当前堆栈是否是Lua +-- @checkLayer 指定的栈层 +function this.checkCurrentLayerisLua( checkLayer ) + local info = debug.getinfo(checkLayer, "S"); + if info == nil then + return nil; + end + info.source = this.genUnifiedPath(info.source); + if info ~= nil then + for k,v in pairs(info) do + if k == "what" then + if v == "C" then + return false; + else + return true; + end + end + end + end + return nil; +end + +-- 在 fakeBreakPointCache 中查询此断点是否真实存在 +-- 因为同名文件的影响, 有些断点是命中错误的。经过VScode校验后,这些错误命中的断点信息被存在fakeBreakPointCache中 +function this.checkRealHitBreakpoint( oPath, line ) + -- 在假命中列表中搜索,如果本行有过假命中记录,返回 false + if oPath and fakeBreakPointCache[oPath] then + for _, value in ipairs(fakeBreakPointCache[oPath]) do + if tonumber(value) == tonumber(line) then + this.printToVSCode("cache hit bp in same name file. source:" .. tostring(oPath) .. " line:" .. tostring(line)); + return false; + end + end + end + return true; +end + +------------------------断点处理------------------------- +--- this.isHitBreakpoint 判断断点是否命中。这个方法在c mod以及lua中都有调用 +-- @param breakpointPath 文件名+后缀 +-- @param opath getinfo path +-- @param curLine 当前执行行号 +function this.isHitBreakpoint(breakpointPath, opath, curLine) + if breaks[breakpointPath] then + local oPathFormated; + for fullpath, fullpathNode in pairs(breaks[breakpointPath]) do + recordBreakPointPath = fullpath; --这里是为了兼容用户断点行号没有打对的情况 + local line_hit,cur_node = false,{}; + for _, node in ipairs(fullpathNode) do + if tonumber(node["line"]) == tonumber(curLine) then + line_hit = true; -- fullpath 文件中 有行号命中 + cur_node = node; + recordBreakPointPath = fullpath; --行号命中后,再设置一次,保证路径准确 + break; + end + end + + -- 在lua端不知道是否有同名文件,基本思路是先取文件名,用文件名和breakpointArray 进行匹配。 + -- 当文件名匹配上时,可能存在多个同名文件中存在断点的情况。这时候需要用 oPath 和 fullpath 进行对比,取出正确的。 + -- 当本地文件中有断点,lua做了初步命中后,可能存在 stack , 断点文件有同名的情况。这就需要vscode端也需要checkfullpath函数,使用opath进行文件校验。 + if line_hit then + if oPathFormated == nil then + -- 为了避免性能消耗,仅在行号命中时才处理 opath 到标准化路径 + oPathFormated = this.formatOpath(opath); + -- 截取 + oPathFormated = this.truncatedPath(oPathFormated, truncatedOPath); + end + + if (not distinguishSameNameFile) or (string.match(fullpath, oPathFormated ) and this.checkRealHitBreakpoint(opath, curLine)) then + -- type是TS中的枚举类型,其定义在BreakPoint.tx文件中 + -- enum BreakpointType { + -- conditionBreakpoint = 0, + -- logPoint, + -- lineBreakpoint + -- } + + -- 处理断点 + if cur_node["type"] == "0" then + -- condition breakpoint + -- 注意此处不要使用尾调用,否则会影响调用栈,导致Lua5.3和Lua5.1中调用栈层级不同 + local conditionRet = this.IsMeetCondition(cur_node["condition"]); + -- this.printToVSCode("Condition BK: condition:" .. cur_node["condition"] .. " conditionRet " .. tostring(conditionRet)); + return conditionRet; + elseif cur_node["type"] == "1" then + -- log point + this.printToVSCode("[LogPoint Output]: " .. cur_node["logMessage"], 2, 2); + return false; + else + -- line breakpoint + return true; + end + end + end + end + else + testBreakpointFlag = false; --如果用户打开了测试断点的标志位而未主动关闭,会在lua继续运行时关闭。 + recordBreakPointPath = ''; --当切换文件时置空,避免提示给用户错误信息 + end + return false; +end + +-- 条件断点处理函数 +-- 返回true表示条件成立 +-- @conditionExp 条件表达式 +function this.IsMeetCondition(conditionExp) + -- 判断条件之前更新堆栈信息 + currentCallStack = {}; + variableRefTab = {}; + variableRefIdx = 1; + if hookLib then + this.getStackTable(4); + else + this.getStackTable(); + end + + this.curStackId = 2; --在用户空间最上层执行 + + local conditionExpTable = {["varName"] = conditionExp} + local retTable = this.processWatchedExp(conditionExpTable) + + local isMeetCondition = false; + local function HandleResult() + if retTable[1]["isSuccess"] == "true" then + if retTable[1]["value"] == "nil" or (retTable[1]["value"] == "false" and retTable[1]["type"] == "boolean") then + isMeetCondition = false; + else + isMeetCondition = true; + end + else + isMeetCondition = false; + end + end + + xpcall(HandleResult, function() isMeetCondition = false; end) + return isMeetCondition; +end + +--加入断点函数 +function this.BP() + this.printToConsole("BP()"); + if hookLib == nil then + if currentHookState == hookState.DISCONNECT_HOOK then + this.printToConsole("BP() but NO HOOK"); + return; + end + + local co, isMain = coroutine.running(); + if _VERSION == "Lua 5.1" then + if co == nil then + isMain = true; + else + isMain = false; + end + end + + if isMain == true then + this.printToConsole("BP() in main"); + else + this.printToConsole("BP() in coroutine"); + debug.sethook(co, this.debug_hook, "lrc"); + end + hitBP = true; + else + if hookLib.get_libhook_state() == hookState.DISCONNECT_HOOK then + this.printToConsole("BP() but NO C HOOK"); + return; + end + + --clib, set hitBP + hookLib.sync_bp_hit(1); + end + this.changeHookState(hookState.ALL_HOOK); + return true; +end + +-- 检查当前文件中是否有断点 +-- 如果填写参数fileName 返回fileName中有无断点, 全局有无断点 +-- fileName为空,返回全局是否有断点 +function this.checkHasBreakpoint(fileName) + local hasBk = false; + --有无全局断点 + if next(breaks) == nil then + hasBk = false; + else + hasBk = true; + end + --当前文件中是否有断点 + if fileName ~= nil then + return breaks[fileName] ~= nil, hasBk; + else + return hasBk; + end +end + +function this.checkfuncHasBreakpoint(sLine, eLine, fileName) + if breaks[fileName] == nil then + return false; + end + sLine = tonumber(sLine); + eLine = tonumber(eLine); + + --起始行号>结束行号,或者sLine = eLine = 0 + if sLine >= eLine then + return true; + end + + if this.getTableMemberNum(breaks[fileName]) <= 0 then + return false; + else + for k,v in pairs(breaks[fileName]) do + for _, node in ipairs(v) do + if tonumber(node.line) > sLine and tonumber(node.line) <= eLine then + return true; + end + end + end + end + return false; +end +------------------------HOOK模块------------------------- +-- 钩子函数 +-- @event 执行状态(call,return,line) +-- @line 行号 +function this.debug_hook(event, line) + if this.reConnect() == 0 then return; end + + if logLevel == 0 then + local logTable = {"-----enter debug_hook-----\n", "event:", event, " line:", tostring(line), " currentHookState:",currentHookState," currentRunState:", currentRunState}; + local logString = table.concat(logTable); + this.printToVSCode(logString); + end + + --litehook 仅非阻塞接收断点 + if currentHookState == hookState.LITE_HOOK then + local ti = os.time(); + if ti - receiveMsgTimer > 1 then + this.debugger_wait_msg(0); + receiveMsgTimer = ti; + end + return; + end + + --运行中 + local info; + local co, isMain = coroutine.running(); + if _VERSION == "Lua 5.1" then + if co == nil then + isMain = true; + else + isMain = false; + end + end + isInMainThread = isMain; + if isMain == true then + info = debug.getinfo(2, "Slf") + else + info = debug.getinfo(co, 2, "Slf") + end + info.event = event; + + this.real_hook_process(info); +end + +function this.real_hook_process(info) + local jumpFlag = false; + local event = info.event; + + --如果当前行在Debugger中,不做处理 + local matchRes = ((info.source == DebuggerFileName) or (info.source == DebuggerToolsName)); + if matchRes == true then + return; + end + + --即使MID hook在C中, 或者是Run或者单步时也接收消息 + if currentRunState == runState.RUN or + currentRunState == runState.STEPOVER or + currentRunState == runState.STEPIN or + currentRunState == runState.STEPOUT then + local ti = os.time(); + if ti - receiveMsgTimer > 1 then + this.debugger_wait_msg(0); + receiveMsgTimer = ti; + end + end + + --不处理C函数 + if info.source == "=[C]" then + this.printToVSCode("current method is C"); + return; + end + + --不处理 slua "temp buffer" + if info.source == "temp buffer" then + this.printToVSCode("current method is in temp buffer"); + return; + end + + --不处理 xlua "chunk" + if info.source == "chunk" then + this.printToVSCode("current method is in chunk"); + return; + end + + --lua 代码段的处理,目前暂不调试代码段。 + if info.short_src:match("%[string \"") then + --当shortSrc中出现[string时]。要检查一下source, 区别是路径还是代码段. 方法是看路径中有没有\t \n ; + if info.source:match("[\n;=]") then + --是代码段,调过 + this.printToVSCode("hook jump Code String!"); + jumpFlag = true; + end + end + + --标准路径处理 + if jumpFlag == false then + info.orininal_source = info.source; --使用 info.orininal_source 记录lua虚拟机传来的原始路径 + info.source = this.getPath(info); + end + --本次执行的函数和上次执行的函数作对比,防止在一行停留两次 + if lastRunFunction["currentline"] == info["currentline"] and lastRunFunction["source"] == info["source"] and lastRunFunction["func"] == info["func"] and lastRunFunction["event"] == event then + this.printToVSCode("run twice"); + end + --记录最后一次调用信息 + if jumpFlag == false then + lastRunFunction = info; + lastRunFunction["event"] = event; + lastRunFilePath = info.source; + end + --输出函数信息到前台 + if logLevel == 0 and jumpFlag == false then + local logTable = {"[lua hook] event:", tostring(event), " currentRunState:",tostring(currentRunState)," currentHookState:",tostring(currentHookState)," jumpFlag:", tostring(jumpFlag)}; + for k,v in pairs(info) do + table.insert(logTable, tostring(k)); + table.insert(logTable, ":"); + table.insert(logTable, tostring(v)); + table.insert(logTable, " "); + end + local logString = table.concat(logTable); + this.printToVSCode(logString); + end + + --仅在line时做断点判断。进了断点之后不再进入本次STEP类型的判断,用Aflag做标记 + local isHit = false; + if tostring(event) == "line" and jumpFlag == false then + if currentRunState == runState.RUN or currentRunState == runState.STEPOVER or currentRunState == runState.STEPIN or currentRunState == runState.STEPOUT then + --断点判断 + isHit = this.isHitBreakpoint(info.source, info.orininal_source, info.currentline) or hitBP; + if isHit == true then + this.printToVSCode("HitBreakpoint!"); + --备份信息 + local recordStepOverCounter = stepOverCounter; + local recordStepOutCounter = stepOutCounter; + local recordCurrentRunState = currentRunState; + --计数器清0 + stepOverCounter = 0; + stepOutCounter = 0; + this.changeRunState(runState.HIT_BREAKPOINT); + hitBpTwiceCheck = true; -- 命中标志默认设置为true, 如果校验通过,会保留这个标记,校验失败会修改 + if hitBP then + hitBP = false; --hitBP是断点硬性命中标记 + --发消息并等待 + this.SendMsgWithStack("stopOnCodeBreakpoint"); + else + --发消息并等待 + this.SendMsgWithStack("stopOnBreakpoint"); + --若二次校验未命中,恢复状态 + if hitBpTwiceCheck == false then + isHit = false; + -- 确认未命中,把状态恢复,继续运行 + this.changeRunState(recordCurrentRunState); + stepOverCounter = recordStepOverCounter; + stepOutCounter = recordStepOutCounter; + end + end + end + end + end + + if isHit == true then + return; + end + + if currentRunState == runState.STEPOVER then + -- line stepOverCounter!= 0 不作操作 + -- line stepOverCounter == 0 停止 + if event == "line" and stepOverCounter <= 0 and jumpFlag == false then + stepOverCounter = 0; + this.changeRunState(runState.STEPOVER_STOP) + this.SendMsgWithStack("stopOnStep"); + elseif event == "return" or event == "tail return" then + --5.1中是tail return + if stepOverCounter ~= 0 then + stepOverCounter = stepOverCounter - 1; + end + elseif event == "call" then + stepOverCounter = stepOverCounter + 1; + end + elseif currentRunState == runState.STOP_ON_ENTRY then + --在Lua入口点处直接停住 + if event == "line" and jumpFlag == false then + --初始化内存分析的变量 + -- MemProfiler.getSystemVar(); + --这里要判断一下是Lua的入口点,否则停到 + this.SendMsgWithStack("stopOnEntry"); + end + elseif currentRunState == runState.STEPIN then + if event == "line" and jumpFlag == false then + this.changeRunState(runState.STEPIN_STOP) + this.SendMsgWithStack("stopOnStepIn"); + end + elseif currentRunState == runState.STEPOUT then + --line 不做操作 + --in 计数器+1 + --out 计数器-1 + if jumpFlag == false then + if stepOutCounter <= -1 then + stepOutCounter = 0; + this.changeRunState(runState.STEPOUT_STOP) + this.SendMsgWithStack("stopOnStepOut"); + end + end + + if event == "return" or event == "tail return" then + stepOutCounter = stepOutCounter - 1; + elseif event == "call" then + stepOutCounter = stepOutCounter + 1; + end + end + + --在RUN时检查并改变状态 + if hookLib == nil then + if currentRunState == runState.RUN and jumpFlag == false and currentHookState ~= hookState.DISCONNECT_HOOK then + local fileBP, G_BP = this.checkHasBreakpoint(lastRunFilePath); + if fileBP == false then + --文件无断点 + if G_BP == true then + this.changeHookState(hookState.MID_HOOK); + else + this.changeHookState(hookState.LITE_HOOK); + end + else + --文件有断点, 判断函数内是否有断点 + local funHasBP = this.checkfuncHasBreakpoint(lastRunFunction.linedefined, lastRunFunction.lastlinedefined, lastRunFilePath); + if funHasBP then + --函数定义范围内 + this.changeHookState(hookState.ALL_HOOK); + else + this.changeHookState(hookState.MID_HOOK); + end + end + + --MID_HOOK状态下,return需要在下一次hook检查文件(return时,还是当前文件,检查文件时状态无法转换) + if (event == "return" or event == "tail return") and currentHookState == hookState.MID_HOOK then + this.changeHookState(hookState.ALL_HOOK); + end + end + end +end + +-- 向Vscode发送标准通知消息,cmdStr是消息类型 +-- @cmdStr 命令字 +function this.SendMsgWithStack(cmdStr) + local msgTab = this.getMsgTable(cmdStr); + local userFuncLevel = 0; + msgTab["stack"] , userFuncLevel= this.getStackTable(); + if userFuncLevel ~= 0 then + lastRunFunction["func"] = debug.getinfo( (userFuncLevel - 1) , 'f').func; + end + this.sendMsg(msgTab); + this.debugger_wait_msg(); +end + +-- hook状态改变 +-- @s 目标状态 +function this.changeHookState( s ) + if hookLib == nil and currentHookState == s then + return; + end + + this.printToConsole("change hook state :"..s) + if s ~= hookState.DISCONNECT_HOOK then + this.printToVSCode("change hook state : "..s) + end + + currentHookState = s; + if s == hookState.DISCONNECT_HOOK then + --为了实现通用attach模式,require即开始hook,利用r作为时机发起连接 + if openAttachMode == true then + if hookLib then hookLib.lua_set_hookstate(hookState.DISCONNECT_HOOK); else debug.sethook(this.debug_hook, "r", 1000000); end + else + if hookLib then hookLib.endHook(); else debug.sethook(); end + end + elseif s == hookState.LITE_HOOK then + if hookLib then hookLib.lua_set_hookstate(hookState.LITE_HOOK); else debug.sethook(this.debug_hook, "r"); end + elseif s == hookState.MID_HOOK then + if hookLib then hookLib.lua_set_hookstate(hookState.MID_HOOK); else debug.sethook(this.debug_hook, "rc"); end + elseif s == hookState.ALL_HOOK then + if hookLib then hookLib.lua_set_hookstate(hookState.ALL_HOOK); else debug.sethook(this.debug_hook, "lrc");end + end + --coroutine + if hookLib == nil then + this.changeCoroutinesHookState(); + end +end + +-- 运行状态机,状态变更 +-- @s 目标状态 +-- @isFromHooklib 1:从libc库中发来的状态改变 | 0:lua发来的状态改变 +function this.changeRunState(s , isFromHooklib) + local msgFrom; + if isFromHooklib == 1 then + msgFrom = "libc"; + else + msgFrom = "lua"; + end + + --WAIT_CMD状态会等待接收消息,以下两个状态下不能发消息 + this.printToConsole("changeRunState :"..s.. " | from:"..msgFrom); + if s ~= runState.DISCONNECT and s ~= runState.WAIT_CMD then + this.printToVSCode("changeRunState :"..s.." | from:"..msgFrom); + end + + if hookLib ~= nil and isFromHooklib ~= 1 then + hookLib.lua_set_runstate(s); + end + currentRunState = s; + --状态切换时,清除记录栈信息的状态 + currentCallStack = {}; + variableRefTab = {}; + variableRefIdx = 1; +end + +-- 修改协程状态 +-- @s hook标志位 +function this.changeCoroutinesHookState(s) + s = s or currentHookState; + this.printToConsole("change [Coroutine] HookState: "..tostring(s)); + for k ,co in pairs(coroutinePool) do + if coroutine.status(co) == "dead" then + coroutinePool[k] = nil + else + this.changeCoroutineHookState(co, s) + end + end +end + +function this.changeCoroutineHookState(co, s) + if s == hookState.DISCONNECT_HOOK then + if openAttachMode == true then + debug.sethook(co, this.debug_hook, "r", 1000000); + else + debug.sethook(co, this.debug_hook, ""); + end + elseif s == hookState.LITE_HOOK then + debug.sethook(co , this.debug_hook, "r"); + elseif s == hookState.MID_HOOK then + debug.sethook(co , this.debug_hook, "rc"); + elseif s == hookState.ALL_HOOK then + debug.sethook(co , this.debug_hook, "lrc"); + end +end +-------------------------变量处理相关----------------------------- + +--清空REPL的env环境 +function this.clearEnv() + if this.getTableMemberNum(env) > 0 then + --清空env table + env = setmetatable({}, getmetatable(env)); + end +end + +--返回REPL的env环境 +function this.showEnv() + return env; +end + +-- 用户观察table的查找函数。用tableVarName作为key去查逐层级查找realVar是否匹配 +-- @tableVarName 是用户观察的变量名,已经按层级被解析成table。比如用户输出a.b.c,tableVarName是 a = { b = { c } } +-- @realVar 是待查询 table +-- @return 返回查到的table。没查到返回nil +function this.findTableVar( tableVarName, realVar) + if type(tableVarName) ~= "table" or type(realVar) ~= "table" then + return nil; + end + + local layer = 2; + local curVar = realVar; + local jumpOutFlag = false; + repeat + if tableVarName[layer] ~= nil then + --这里优先展示数字key,比如a{"1" = "aa", [1] = "bb"} 会展示[1]的值 + local tmpCurVar = nil; + xpcall(function() tmpCurVar = curVar[tonumber(tableVarName[layer])]; end , function() tmpCurVar = nil end ); + if tmpCurVar == nil then + xpcall(function() curVar = curVar[tostring(tableVarName[layer])]; end , function() curVar = nil end ); + else + curVar = tmpCurVar; + end + layer = layer + 1; + if curVar == nil then + return nil; + end + else + --找到 + jumpOutFlag = true; + end + until(jumpOutFlag == true) + return curVar; +end + +-- 根据传入信息生成返回的变量信息 +-- @variableName 变量名 +-- @variableIns 变量实例 +-- @return 包含变量信息的格式化table +function this.createWatchedVariableInfo(variableName, variableIns) + local var = {}; + var.name = variableName; + var.type = tostring(type(variableIns)); + xpcall(function() var.value = tostring(variableIns) end , function() var.value = tostring(type(variableIns)) .. " [value can't trans to string]" end ); + var.variablesReference = "0"; --这个地方必须用“0”, 以免variableRefTab[0]出错 + + if var.type == "table" or var.type == "function" or var.type == "userdata" then + var.variablesReference = variableRefIdx; + variableRefTab[variableRefIdx] = variableIns; + variableRefIdx = variableRefIdx + 1; + if var.type == "table" then + local memberNum = this.getTableMemberNum(variableIns); + var.value = memberNum .." Members ".. var.value; + end + elseif var.type == "string" then + var.value = '"' ..variableIns.. '"'; + end + return var; +end + +-- 设置 global 变量 +-- @varName 被修改的变量名 +-- @newValue 新的值 +function this.setGlobal(varName, newValue) + _G[varName] = newValue; + this.printToVSCode("[setVariable success] 已设置 _G.".. varName .. " = " .. tostring(newValue) ); + return true; +end + +-- 设置 upvalue 变量 +-- @varName 被修改的变量名 +-- @newValue 新的值 +-- @stackId 变量所在stack栈层 +-- @tableVarName 变量名拆分成的数组 +function this.setUpvalue(varName, newValue, stackId, tableVarName) + local ret = false; + local upTable = this.getUpValueVariable(currentCallStack[stackId - 1 ].func, true); + for i, realVar in ipairs(upTable) do + if realVar.name == varName then + if #tableVarName > 0 and type(realVar) == "table" then + --处理a.b.c的table类型 + local findRes = this.findTableVar(tableVarName, variableRefTab[realVar.variablesReference]); + if findRes ~= nil then + --命中 + local setVarRet = debug.setupvalue (currentCallStack[stackId - 1 ].func, i, newValue); + if setVarRet == varName then + this.printToConsole("[setVariable success1] 已设置 upvalue ".. varName .. " = " .. tostring(newValue) ); + ret = true; + else + this.printToConsole("[setVariable error1] 未能设置 upvalue ".. varName .. " = " .. tostring(newValue).." , 返回结果: ".. tostring(setVarRet)); + end + return ret; + end + else + --命中 + local setVarRet = debug.setupvalue (currentCallStack[stackId - 1 ].func, i, newValue); + if setVarRet == varName then + this.printToConsole("[setVariable success] 已设置 upvalue ".. varName .. " = " .. tostring(newValue) ); + ret = true; + else + this.printToConsole("[setVariable error] 未能设置 upvalue ".. varName .. " = " .. tostring(newValue).." , 返回结果: ".. tostring(setVarRet)); + end + return ret; + end + end + end + return ret; +end + +-- 设置local 变量 +-- @varName 被修改的变量名 +-- @newValue 新的值 +-- @tableVarName 变量名拆分成的数组 +function this.setLocal( varName, newValue, tableVarName, stackId) + local istackId = tonumber(stackId); + local offset = (istackId and istackId - 2) or 0; + local layerVarTab, ly = this.getVariable(nil , true, offset); + local ret = false; + for i, realVar in ipairs(layerVarTab) do + if realVar.name == varName then + if #tableVarName > 0 and type(realVar) == "table" then + --处理a.b.c的table类型 + local findRes = this.findTableVar(tableVarName, variableRefTab[realVar.variablesReference]); + if findRes ~= nil then + --命中 + local setVarRet = debug.setlocal(ly , layerVarTab[i].index, newValue); + if setVarRet == varName then + this.printToConsole("[setVariable success1] 已设置 local ".. varName .. " = " .. tostring(newValue) ); + ret = true; + else + this.printToConsole("[setVariable error1] 未能设置 local ".. varName .. " = " .. tostring(newValue).." , 返回结果: ".. tostring(setVarRet)); + end + return ret; + end + else + + local setVarRet = debug.setlocal(ly , layerVarTab[i].index, newValue); + + if setVarRet == varName then + this.printToConsole("[setVariable success] 已设置 local ".. varName .. " = " .. tostring(newValue) ); + ret = true; + else + this.printToConsole("[setVariable error] 未能设置 local ".. varName .. " = " .. tostring(newValue) .." , 返回结果: ".. tostring(setVarRet)); + end + return ret; + end + end + end + return ret; +end + + +-- 设置变量的值 +-- @varName 被修改的变量名 +-- @curStackId 调用栈层级(仅在固定栈层查找) +-- @newValue 新的值 +-- @limit 限制符, 10000表示仅在局部变量查找 ,20000 global, 30000 upvalue +function this.setVariableValue (varName, stackId, newValue , limit) + this.printToConsole("setVariableValue | varName:" .. tostring(varName) .. " stackId:".. tostring(stackId) .." newValue:" .. tostring(newValue) .." limit:"..tostring(limit) ) + if tostring(varName) == nil or tostring(varName) == "" then + --赋值错误 + this.printToConsole("[setVariable Error] 被赋值的变量名为空", 2 ); + this.printToVSCode("[setVariable Error] 被赋值的变量名为空", 2 ); + return false; + end + + --支持a.b.c形式。切割varName + local tableVarName = {}; + if varName:match('%.') then + tableVarName = this.stringSplit(varName , '%.'); + if type(tableVarName) ~= "table" or #tableVarName < 1 then + return false; + end + varName = tableVarName[1]; + end + + if limit == "local" then + local ret = this.setLocal( varName, newValue, tableVarName, stackId); + return ret; + elseif limit == "upvalue" then + local ret = this.setUpvalue(varName, newValue, stackId, tableVarName); + return ret + elseif limit == "global" then + local ret = this.setGlobal(varName, newValue); + return ret; + else + local ret = this.setLocal( varName, newValue, tableVarName, stackId) or this.setUpvalue(varName, newValue, stackId, tableVarName) or this.setGlobal(varName, newValue); + this.printToConsole("set Value res :".. tostring(ret)); + return ret; + end +end + +-- 按照local -> upvalue -> _G 顺序查找观察变量 +-- @varName 用户输入的变量名 +-- @stackId 调用栈层级(仅在固定栈层查找) +-- @isFormatVariable 是否把变量格式化为VSCode接收的形式 +-- @return 查到返回信息,查不到返回nil +function this.getWatchedVariable( varName , stackId , isFormatVariable ) + this.printToConsole("getWatchedVariable | varName:" .. tostring(varName) .. " stackId:".. tostring(stackId) .." isFormatVariable:" .. tostring(isFormatVariable) ) + if tostring(varName) == nil or tostring(varName) == "" then + return nil; + end + + if type(currentCallStack[stackId - 1]) ~= "table" or type(currentCallStack[stackId - 1].func) ~= "function" then + local str = "getWatchedVariable currentCallStack " .. stackId - 1 .. " Error\n" .. this.serializeTable(currentCallStack, "currentCallStack"); + this.printToVSCode(str, 2); + return nil; + end + + --orgname 记录原名字. 用来处理a.b.c的形式 + local orgname = varName; + --支持a.b.c形式。切割varName + local tableVarName = {}; + if varName:match('%.') then + tableVarName = this.stringSplit(varName , '%.'); + if type(tableVarName) ~= "table" or #tableVarName < 1 then + return nil; + end + varName = tableVarName[1]; + end + --用来返回,带有查到变量的table + local varTab = {}; + local ly = this.getSpecificFunctionStackLevel(currentCallStack[stackId - 1].func); + + local layerVarTab = this.getVariable(ly, isFormatVariable); + local upTable = this.getUpValueVariable(currentCallStack[stackId - 1 ].func, isFormatVariable); + local travelTab = {}; + table.insert(travelTab, layerVarTab); + table.insert(travelTab, upTable); + for _, layerVarTab in ipairs(travelTab) do + for i,realVar in ipairs(layerVarTab) do + if realVar.name == varName then + if #tableVarName > 0 and type(realVar) == "table" then + --处理a.b.c的table类型 + local findRes = this.findTableVar(tableVarName, variableRefTab[realVar.variablesReference]); + if findRes ~= nil then + --命中 + if isFormatVariable then + local var = this.createWatchedVariableInfo( orgname , findRes ); + table.insert(varTab, var); + return varTab; + else + return findRes.value; + end + end + else + --命中 + if isFormatVariable then + table.insert(varTab, realVar); + return varTab; + else + return realVar.value; + end + end + end + end + end + + --在全局变量_G中查找 + if _G[varName] ~= nil then + --命中 + if #tableVarName > 0 and type(_G[varName]) == "table" then + local findRes = this.findTableVar(tableVarName, _G[varName]); + if findRes ~= nil then + if isFormatVariable then + local var = this.createWatchedVariableInfo( orgname , findRes ); + table.insert(varTab, var); + return varTab; + else + return findRes; + end + end + else + if isFormatVariable then + local var = this.createWatchedVariableInfo( varName , _G[varName] ); + table.insert(varTab, var); + return varTab; + else + return _G[varName]; + end + end + end + this.printToConsole("getWatchedVariable not find variable"); + return nil; +end + +-- 查询引用变量 +-- @refStr 变量记录id(variableRefTab索引) +-- @return 格式化的变量信息table +function this.getVariableRef( refStr ) + local varRef = tonumber(refStr); + local varTab = {}; + + if tostring(type(variableRefTab[varRef])) == "table" then + for n,v in pairs(variableRefTab[varRef]) do + local var = {}; + if type(n) == "string" then + var.name = '"' .. tostring(n) .. '"'; + else + var.name = tostring(n); + end + var.type = tostring(type(v)); + xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .. " [value can't trans to string]" end ); + var.variablesReference = "0"; + if var.type == "table" or var.type == "function" or var.type == "userdata" then + var.variablesReference = variableRefIdx; + variableRefTab[variableRefIdx] = v; + variableRefIdx = variableRefIdx + 1; + if var.type == "table" then + local memberNum = this.getTableMemberNum(v); + var.value = memberNum .." Members ".. ( var.value or '' ); + end + elseif var.type == "string" then + var.value = '"' ..v.. '"'; + end + table.insert(varTab, var); + end + --获取一下mtTable + local mtTab = getmetatable(variableRefTab[varRef]); + if mtTab ~= nil and type(mtTab) == "table" then + local var = {}; + var.name = "_Metatable_"; + var.type = tostring(type(mtTab)); + xpcall(function() var.value = "元表 "..tostring(mtTab); end , function() var.value = "元表 [value can't trans to string]" end ); + var.variablesReference = variableRefIdx; + variableRefTab[variableRefIdx] = mtTab; + variableRefIdx = variableRefIdx + 1; + table.insert(varTab, var); + end + elseif tostring(type(variableRefTab[varRef])) == "function" then + --取upvalue + varTab = this.getUpValueVariable(variableRefTab[varRef], true); + elseif tostring(type(variableRefTab[varRef])) == "userdata" then + --取mt table + local udMtTable = getmetatable(variableRefTab[varRef]); + if udMtTable ~= nil and type(udMtTable) == "table" then + local var = {}; + var.name = "_Metatable_"; + var.type = tostring(type(udMtTable)); + xpcall(function() var.value = "元表 "..tostring(udMtTable); end , function() var.value = "元表 [value can't trans to string]" end ); + var.variablesReference = variableRefIdx; + variableRefTab[variableRefIdx] = udMtTable; + variableRefIdx = variableRefIdx + 1; + table.insert(varTab, var); + + if traversalUserData and udMtTable.__pairs ~= nil and type(udMtTable.__pairs) == "function" then + for n,v in pairs(variableRefTab[varRef]) do + local var = {}; + var.name = tostring(n); + var.type = tostring(type(v)); + xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .. " [value can't trans to string]" end ); + var.variablesReference = "0"; + if var.type == "table" or var.type == "function" or var.type == "userdata" then + var.variablesReference = variableRefIdx; + variableRefTab[variableRefIdx] = v; + variableRefIdx = variableRefIdx + 1; + if var.type == "table" then + local memberNum = this.getTableMemberNum(v); + var.value = memberNum .." Members ".. ( var.value or '' ); + end + elseif var.type == "string" then + var.value = '"' ..v.. '"'; + end + table.insert(varTab, var); + end + end + end + end + return varTab; +end + +-- 获取全局变量。方法和内存管理中获取全局变量的方法一样 +-- @return 格式化的信息, 若未找到返回空table +function this.getGlobalVariable( ... ) + --成本比较高,这里只能遍历_G中的所有变量,并去除系统变量,再返回给客户端 + local varTab = {}; + for k,v in pairs(_G) do + local var = {}; + var.name = tostring(k); + var.type = tostring(type(v)); + xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .." [value can't trans to string]" end ); + var.variablesReference = "0"; + if var.type == "table" or var.type == "function" or var.type == "userdata" then + var.variablesReference = variableRefIdx; + variableRefTab[variableRefIdx] = v; + variableRefIdx = variableRefIdx + 1; + if var.type == "table" then + local memberNum = this.getTableMemberNum(v); + var.value = memberNum .." Members ".. ( var.value or '' ); + end + elseif var.type == "string" then + var.value = '"' ..v.. '"'; + end + table.insert(varTab, var); + end + return varTab; +end + +-- 获取upValues +-- @isFormatVariable true返回[值] true返回[格式化的数据] +function this.getUpValueVariable( checkFunc , isFormatVariable) + local isGetValue = true; + if isFormatVariable == true then + isGetValue = false; + end + + --通过Debug获取当前函数的Func + checkFunc = checkFunc or lastRunFunction.func; + + local varTab = {}; + if checkFunc == nil then + return varTab; + end + local i = 1 + repeat + local n, v = debug.getupvalue(checkFunc, i) + if n then + + local var = {}; + var.name = n; + var.type = tostring(type(v)); + var.variablesReference = "0"; + + if isGetValue == false then + xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .. " [value can't trans to string]" end ); + if var.type == "table" or var.type == "function" or var.type == "userdata" then + var.variablesReference = variableRefIdx; + variableRefTab[variableRefIdx] = v; + variableRefIdx = variableRefIdx + 1; + if var.type == "table" then + local memberNum = this.getTableMemberNum(v); + var.value = memberNum .." Members ".. ( var.value or '' ); + end + elseif var.type == "string" then + var.value = '"' ..v.. '"'; + end + else + var.value = v; + end + + table.insert(varTab, var); + i = i + 1 + end + until not n + return varTab; +end + +-- 获取局部变量 checkLayer是要查询的层级,如果不设置则查询当前层级 +-- @isFormatVariable 是否取值,true:取值的tostring +function this.getVariable( checkLayer, isFormatVariable , offset) + local isGetValue = true; + if isFormatVariable == true then + isGetValue = false; + end + + local ly = 0; + if checkLayer ~= nil and type(checkLayer) == "number" then ly = checkLayer + 1; + else ly = this.getSpecificFunctionStackLevel(lastRunFunction.func); end + + if ly == 0 then + this.printToVSCode("[error]获取层次失败!", 2); + return; + end + local varTab = {}; + local stacklayer = ly; + local k = 1; + + if type(offset) == 'number' then + stacklayer = stacklayer + offset; + end + + repeat + local n, v = debug.getlocal(stacklayer, k) + if n == nil then + break; + end + + --(*temporary)是系统变量,过滤掉。这里假设(*temporary)仅出现在最后 + if "(*temporary)" ~= tostring(n) then + local var = {}; + var.name = n; + var.type = tostring(type(v)); + var.variablesReference = "0"; + var.index = k; + + if isGetValue == false then + xpcall(function() var.value = tostring(v) end , function() var.value = tostring(type(v)) .. " [value can't trans to string]" end ); + if var.type == "table" or var.type == "function" or var.type == "userdata" then + var.variablesReference = variableRefIdx; + variableRefTab[variableRefIdx] = v; + variableRefIdx = variableRefIdx + 1; + if var.type == "table" then + local memberNum = this.getTableMemberNum(v); + var.value = memberNum .." Members ".. ( var.value or '' ); + end + elseif var.type == "string" then + var.value = '"' ..v.. '"'; + end + else + var.value = v; + end + + local sameIdx = this.checkSameNameVar(varTab, var); + if sameIdx ~= 0 then + varTab[sameIdx] = var; + else + table.insert(varTab, var); + end + end + k = k + 1 + until n == nil + return varTab, stacklayer - 1; +end + +--检查变量列表中的同名变量 +function this.checkSameNameVar(varTab, var) + for k , v in pairs(varTab) do + if v.name == var.name then + return k; + end + end + return 0; +end + +-- 执行表达式 +function this.processExp(msgTable) + local retString; + local var = {}; + var.isSuccess = "true"; + if msgTable ~= nil then + local expression = this.trim(tostring(msgTable.Expression)); + local isCmd = false; + if isCmd == false then + --兼容旧版p 命令 + if expression:find("p ", 1, true) == 1 then + expression = expression:sub(3); + end + + local expressionWithReturn = "return " .. expression; + local f = debugger_loadString(expressionWithReturn) or debugger_loadString(expression); + --判断结果,如果表达式错误会返回nil + if type(f) == "function" then + if _VERSION == "Lua 5.1" then + setfenv(f , env); + else + debug.setupvalue(f, 1, env); + end + --表达式要有错误处理 + xpcall(function() retString = f() end , function() retString = "输入错误指令。\n + 请检查指令是否正确\n + 指令仅能在[暂停在断点时]输入, 请不要在程序持续运行时输入"; var.isSuccess = false; end) + else + retString = "指令执行错误。\n + 请检查指令是否正确\n + 可以直接输入表达式,执行函数或变量名,并观察执行结果"; + var.isSuccess = false; + end + end + end + + var.name = "Exp"; + var.type = tostring(type(retString)); + xpcall(function() var.value = tostring(retString) end , function(e) var.value = tostring(type(retString)) .. " [value can't trans to string] ".. e; var.isSuccess = false; end); + var.variablesReference = "0"; + if var.type == "table" or var.type == "function" or var.type == "userdata" then + variableRefTab[variableRefIdx] = retString; + var.variablesReference = variableRefIdx; + variableRefIdx = variableRefIdx + 1; + if var.type == "table" then + local memberNum = this.getTableMemberNum(retString); + var.value = memberNum .." Members ".. var.value; + end + elseif var.type == "string" then + var.value = '"' ..retString.. '"'; + end + --string执行完毕后清空env环境 + this.clearEnv(); + local retTab = {} + table.insert(retTab ,var); + return retTab; +end + +--执行变量观察表达式 +function this.processWatchedExp(msgTable) + local retString; + local expression = "return ".. tostring(msgTable.varName) + this.printToConsole("processWatchedExp | expression: " .. expression); + local f = debugger_loadString(expression); + local var = {}; + var.isSuccess = "true"; + --判断结果,如果表达式错误会返回nil + if type(f) == "function" then + --表达式正确 + if _VERSION == "Lua 5.1" then + setfenv(f , env); + else + debug.setupvalue(f, 1, env); + end + xpcall(function() retString = f() end , function() retString = "输入了错误的变量信息"; var.isSuccess = "false"; end) + else + retString = "未能找到变量的值"; + var.isSuccess = "false"; + end + + var.name = msgTable.varName; + var.type = tostring(type(retString)); + xpcall(function() var.value = tostring(retString) end , function() var.value = tostring(type(retString)) .. " [value can't trans to string]"; var.isSuccess = "false"; end ); + var.variablesReference = "0"; + + if var.type == "table" or var.type == "function" or var.type == "userdata" then + variableRefTab[variableRefIdx] = retString; + var.variablesReference = variableRefIdx; + variableRefIdx = variableRefIdx + 1; + if var.type == "table" then + local memberNum = this.getTableMemberNum(retString); + var.value = memberNum .." Members ".. var.value; + end + elseif var.type == "string" then + var.value = '"' ..retString.. '"'; + end + + local retTab = {} + table.insert(retTab ,var); + return retTab; +end + + +function tools.getFileSource() + local info = debug.getinfo(1, "S") + for k,v in pairs(info) do + if k == "source" then + return v; + end + end +end + +--序列化并打印table +function tools.printTable(t, name ,indent) + local str = (tools.show(t, name, indent)); + print(str); +end + +--序列化并返回table +function tools.serializeTable(t, name, indent) + local str = (tools.show(t, name, indent)) + return str +end + +--[[ +Author: Julio Manuel Fernandez-Diaz +Date: January 12, 2007 +Modified slightly by RiciLake to avoid the unnecessary table traversal in tablecount() +Formats tables with cycles recursively to any depth. +The output is returned as a string. +References to other tables are shown as values. +Self references are indicated. +The string returned is "Lua code", which can be procesed +(in the case in which indent is composed by spaces or "--"). +Userdata and function keys and values are shown as strings, +which logically are exactly not equivalent to the original code. +This routine can serve for pretty formating tables with +proper indentations, apart from printing them: +print(table.show(t, "t")) -- a typical use +Heavily based on "Saving tables with cycles", PIL2, p. 113. +Arguments: +t is the table. +name is the name of the table (optional) +indent is a first indentation (optional). +--]] +function tools.show(t, name, indent) + local cart -- a container + local autoref -- for self references + + local function isemptytable(t) return next(t) == nil end + + local function basicSerialize (o) + local so = tostring(o) + if type(o) == "function" then + local info = debug.getinfo(o, "S") + -- info.name is nil because o is not a calling level + if info.what == "C" then + return string.format("%q", so .. ", C function") + else + -- the information is defined through lines + return string.format("%q", so .. ", defined in (" .. + info.linedefined .. "-" .. info.lastlinedefined .. + ")" .. info.source) + end + elseif type(o) == "number" or type(o) == "boolean" then + return so + else + return string.format("%q", so) + end + end + + local function addtocart (value, name, indent, saved, field) + indent = indent or "" + saved = saved or {} + field = field or name + + cart = cart .. indent .. field + + if type(value) ~= "table" then + cart = cart .. " = " .. basicSerialize(value) .. ";\n" + else + if saved[value] then + cart = cart .. " = {}; -- " .. saved[value] + .. " (self reference)\n" + autoref = autoref .. name .. " = " .. saved[value] .. ";\n" + else + saved[value] = name + --if tablecount(value) == 0 then + if isemptytable(value) then + cart = cart .. " = {};\n" + else + cart = cart .. " = {\n" + for k, v in pairs(value) do + k = basicSerialize(k) + local fname = string.format("%s[%s]", name, k) + field = string.format("[%s]", k) + -- three spaces between levels + addtocart(v, fname, indent .. " ", saved, field) + end + cart = cart .. indent .. "};\n" + end + end + end + end + + name = name or "PRINT_Table" + if type(t) ~= "table" then + return name .. " = " .. basicSerialize(t) + end + cart, autoref = "", "" + addtocart(t, name, indent) + return cart .. autoref +end + +----------------------------------------------------------------------------- +-- JSON4Lua: JSON encoding / decoding support for the Lua language. +-- json Module. +-- Author: Craig Mason-Jones +-- Homepage: http://github.com/craigmj/json4lua/ +-- Version: 1.0.0 +-- This module is released under the MIT License (MIT). +-- Please see LICENCE.txt for details. +-- +-- USAGE: +-- This module exposes two functions: +-- json.encode(o) +-- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string. +-- json.decode(json_string) +-- Returns a Lua object populated with the data encoded in the JSON string json_string. +-- +-- REQUIREMENTS: +-- compat-5.1 if using Lua 5.0 +-- +-- CHANGELOG +-- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix). +-- Fixed Lua 5.1 compatibility issues. +-- Introduced json.null to have null values in associative arrays. +-- json.encode() performance improvement (more than 50%) through table.concat rather than .. +-- Introduced decode ability to ignore /**/ comments in the JSON string. +-- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays. +----------------------------------------------------------------------------- + +function tools.createJson() + ----------------------------------------------------------------------------- + -- Imports and dependencies + ----------------------------------------------------------------------------- + local math = require('math') + local string = require("string") + local table = require("table") + + ----------------------------------------------------------------------------- + -- Module declaration + ----------------------------------------------------------------------------- + local json = {} -- Public namespace + local json_private = {} -- Private namespace + + -- Public constants + json.EMPTY_ARRAY={} + json.EMPTY_OBJECT={} + + -- Public functions + + -- Private functions + local decode_scanArray + local decode_scanComment + local decode_scanConstant + local decode_scanNumber + local decode_scanObject + local decode_scanString + local decode_scanWhitespace + local encodeString + local isArray + local isEncodable + + ----------------------------------------------------------------------------- + -- PUBLIC FUNCTIONS + ----------------------------------------------------------------------------- + --- Encodes an arbitrary Lua object / variable. + -- @param v The Lua object / variable to be JSON encoded. + -- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode) + function json.encode (v) + -- Handle nil values + if v==nil then + return "null" + end + + local vtype = type(v) + + -- Handle strings + if vtype=='string' then + return '"' .. json_private.encodeString(v) .. '"' -- Need to handle encoding in string + end + + -- Handle booleans + if vtype=='number' or vtype=='boolean' then + return tostring(v) + end + + -- Handle tables + if vtype=='table' then + local rval = {} + -- Consider arrays separately + local bArray, maxCount = isArray(v) + if bArray then + for i = 1,maxCount do + table.insert(rval, json.encode(v[i])) + end + else -- An object, not an array + for i,j in pairs(v) do + if isEncodable(i) and isEncodable(j) then + table.insert(rval, '"' .. json_private.encodeString(i) .. '":' .. json.encode(j)) + end + end + end + if bArray then + return '[' .. table.concat(rval,',') ..']' + else + return '{' .. table.concat(rval,',') .. '}' + end + end + + -- Handle null values + if vtype=='function' and v==json.null then + return 'null' + end + + assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. tostring(v)) + end + + + --- Decodes a JSON string and returns the decoded value as a Lua data structure / value. + -- @param s The string to scan. + -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1. + -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil, + -- and the position of the first character after + -- the scanned JSON object. + function json.decode(s, startPos) + startPos = startPos and startPos or 1 + startPos = decode_scanWhitespace(s,startPos) + assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']') + local curChar = string.sub(s,startPos,startPos) + -- Object + if curChar=='{' then + return decode_scanObject(s,startPos) + end + -- Array + if curChar=='[' then + return decode_scanArray(s,startPos) + end + -- Number + if string.find("+-0123456789.e", curChar, 1, true) then + return decode_scanNumber(s,startPos) + end + -- String + if curChar==[["]] or curChar==[[']] then + return decode_scanString(s,startPos) + end + if string.sub(s,startPos,startPos+1)=='/*' then + return json.decode(s, decode_scanComment(s,startPos)) + end + -- Otherwise, it must be a constant + return decode_scanConstant(s,startPos) + end + + --- The null function allows one to specify a null value in an associative array (which is otherwise + -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null } + function json.null() + return json.null -- so json.null() will also return null ;-) + end + ----------------------------------------------------------------------------- + -- Internal, PRIVATE functions. + -- Following a Python-like convention, I have prefixed all these 'PRIVATE' + -- functions with an underscore. + ----------------------------------------------------------------------------- + + --- Scans an array from JSON into a Lua object + -- startPos begins at the start of the array. + -- Returns the array and the next starting position + -- @param s The string being scanned. + -- @param startPos The starting position for the scan. + -- @return table, int The scanned array as a table, and the position of the next character to scan. + function decode_scanArray(s,startPos) + local array = {} -- The return value + local stringLen = string.len(s) + assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s ) + startPos = startPos + 1 + -- Infinite loop for array elements + local index = 1 + repeat + startPos = decode_scanWhitespace(s,startPos) + assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.') + local curChar = string.sub(s,startPos,startPos) + if (curChar==']') then + return array, startPos+1 + end + if (curChar==',') then + startPos = decode_scanWhitespace(s,startPos+1) + end + assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.') + local object + object, startPos = json.decode(s,startPos) + array[index] = object + index = index + 1 + until false + end + + --- Scans a comment and discards the comment. + -- Returns the position of the next character following the comment. + -- @param string s The JSON string to scan. + -- @param int startPos The starting position of the comment + function decode_scanComment(s, startPos) + assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos) + local endPos = string.find(s,'*/',startPos+2) + assert(endPos~=nil, "Unterminated comment in string at " .. startPos) + return endPos+2 + end + + --- Scans for given constants: true, false or null + -- Returns the appropriate Lua type, and the position of the next character to read. + -- @param s The string being scanned. + -- @param startPos The position in the string at which to start scanning. + -- @return object, int The object (true, false or nil) and the position at which the next character should be + -- scanned. + function decode_scanConstant(s, startPos) + local consts = { ["true"] = true, ["false"] = false, ["null"] = nil } + local constNames = {"true","false","null"} + + for i,k in pairs(constNames) do + if string.sub(s,startPos, startPos + string.len(k) -1 )==k then + return consts[k], startPos + string.len(k) + end + end + assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos) + end + + --- Scans a number from the JSON encoded string. + -- (in fact, also is able to scan numeric +- eqns, which is not + -- in the JSON spec.) + -- Returns the number, and the position of the next character + -- after the number. + -- @param s The string being scanned. + -- @param startPos The position at which to start scanning. + -- @return number, int The extracted number and the position of the next character to scan. + function decode_scanNumber(s,startPos) + local endPos = startPos+1 + local stringLen = string.len(s) + local acceptableChars = "+-0123456789.e" + while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true) + and endPos<=stringLen + ) do + endPos = endPos + 1 + end + -- local stringValue = 'return ' .. string.sub(s, startPos, endPos - 1) + -- local stringEval = loadstring(stringValue) + -- assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos) + local numberValue = string.sub(s, startPos, endPos - 1) + return numberValue, endPos + end + + --- Scans a JSON object into a Lua object. + -- startPos begins at the start of the object. + -- Returns the object and the next starting position. + -- @param s The string being scanned. + -- @param startPos The starting position of the scan. + -- @return table, int The scanned object as a table and the position of the next character to scan. + function decode_scanObject(s,startPos) + local object = {} + local stringLen = string.len(s) + local key, value + assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s) + startPos = startPos + 1 + repeat + startPos = decode_scanWhitespace(s,startPos) + assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.') + local curChar = string.sub(s,startPos,startPos) + if (curChar=='}') then + return object,startPos+1 + end + if (curChar==',') then + startPos = decode_scanWhitespace(s,startPos+1) + end + assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.') + -- Scan the key + key, startPos = json.decode(s,startPos) + assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) + startPos = decode_scanWhitespace(s,startPos) + assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) + assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos) + startPos = decode_scanWhitespace(s,startPos+1) + assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) + value, startPos = json.decode(s,startPos) + object[key]=value + until false -- infinite loop while key-value pairs are found + end + + -- START SoniEx2 + -- Initialize some things used by decode_scanString + -- You know, for efficiency + local escapeSequences = { + ["\\t"] = "\t", + ["\\f"] = "\f", + ["\\r"] = "\r", + ["\\n"] = "\n", + ["\\b"] = "\b" + } + setmetatable(escapeSequences, {__index = function(t,k) + -- skip "\" aka strip escape + return string.sub(k,2) + end}) + -- END SoniEx2 + + --- Scans a JSON string from the opening inverted comma or single quote to the + -- end of the string. + -- Returns the string extracted as a Lua string, + -- and the position of the next non-string character + -- (after the closing inverted comma or single quote). + -- @param s The string being scanned. + -- @param startPos The starting position of the scan. + -- @return string, int The extracted string as a Lua string, and the next character to parse. + function decode_scanString(s,startPos) + assert(startPos, 'decode_scanString(..) called without start position') + local startChar = string.sub(s,startPos,startPos) + -- START SoniEx2 + -- PS: I don't think single quotes are valid JSON + assert(startChar == [["]] or startChar == [[']],'decode_scanString called for a non-string') + --assert(startPos, "String decoding failed: missing closing " .. startChar .. " for string at position " .. oldStart) + local t = {} + local i,j = startPos,startPos + while string.find(s, startChar, j+1) ~= j+1 do + local oldj = j + i,j = string.find(s, "\\.", j+1) + local x,y = string.find(s, startChar, oldj+1) + if not i or x < i then + i,j = x,y-1 + end + table.insert(t, string.sub(s, oldj+1, i-1)) + if string.sub(s, i, j) == "\\u" then + local a = string.sub(s,j+1,j+4) + j = j + 4 + local n = tonumber(a, 16) + assert(n, "String decoding failed: bad Unicode escape " .. a .. " at position " .. i .. " : " .. j) + -- math.floor(x/2^y) == lazy right shift + -- a % 2^b == bitwise_and(a, (2^b)-1) + -- 64 = 2^6 + -- 4096 = 2^12 (or 2^6 * 2^6) + local x + if n < 0x80 then + x = string.char(n % 0x80) + elseif n < 0x800 then + -- [110x xxxx] [10xx xxxx] + x = string.char(0xC0 + (math.floor(n/64) % 0x20), 0x80 + (n % 0x40)) + else + -- [1110 xxxx] [10xx xxxx] [10xx xxxx] + x = string.char(0xE0 + (math.floor(n/4096) % 0x10), 0x80 + (math.floor(n/64) % 0x40), 0x80 + (n % 0x40)) + end + table.insert(t, x) + else + table.insert(t, escapeSequences[string.sub(s, i, j)]) + end + end + table.insert(t,string.sub(j, j+1)) + assert(string.find(s, startChar, j+1), "String decoding failed: missing closing " .. startChar .. " at position " .. j .. "(for string at position " .. startPos .. ")") + return table.concat(t,""), j+2 + -- END SoniEx2 + end + + --- Scans a JSON string skipping all whitespace from the current start position. + -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached. + -- @param s The string being scanned + -- @param startPos The starting position where we should begin removing whitespace. + -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string + -- was reached. + function decode_scanWhitespace(s,startPos) + local whitespace=" \n\r\t" + local stringLen = string.len(s) + while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do + startPos = startPos + 1 + end + return startPos + end + + --- Encodes a string to be JSON-compatible. + -- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-) + -- @param s The string to return as a JSON encoded (i.e. backquoted string) + -- @return The string appropriately escaped. + + local escapeList = { + ['"'] = '\\"', + ['\\'] = '\\\\', + ['/'] = '\\/', + ['\b'] = '\\b', + ['\f'] = '\\f', + ['\n'] = '\\n', + ['\r'] = '\\r', + ['\t'] = '\\t' + } + + function json_private.encodeString(s) + local s = tostring(s) + return s:gsub(".", function(c) return escapeList[c] end) -- SoniEx2: 5.0 compat + end + + -- Determines whether the given Lua type is an array or a table / dictionary. + -- We consider any table an array if it has indexes 1..n for its n items, and no + -- other data in the table. + -- I think this method is currently a little 'flaky', but can't think of a good way around it yet... + -- @param t The table to evaluate as an array + -- @return boolean, number True if the table can be represented as an array, false otherwise. If true, + -- the second returned value is the maximum + -- number of indexed elements in the array. + function isArray(t) + -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable + -- (with the possible exception of 'n') + if (t == json.EMPTY_ARRAY) then return true, 0 end + if (t == json.EMPTY_OBJECT) then return false end + + local maxIndex = 0 + for k,v in pairs(t) do + if (type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair + if (not isEncodable(v)) then return false end -- All array elements must be encodable + maxIndex = math.max(maxIndex,k) + else + if (k=='n') then + if v ~= (t.n or #t) then return false end -- False if n does not hold the number of elements + else -- Else of (k=='n') + if isEncodable(v) then return false end + end -- End of (k~='n') + end -- End of k,v not an indexed pair + end -- End of loop across all pairs + return true, maxIndex + end + + --- Determines whether the given Lua object / table / variable can be JSON encoded. The only + -- types that are JSON encodable are: string, boolean, number, nil, table and json.null. + -- In this implementation, all other types are ignored. + -- @param o The object to examine. + -- @return boolean True if the object should be JSON encoded, false if it should be ignored. + function isEncodable(o) + local t = type(o) + return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or + (t=='function' and o==json.null) + end + return json +end + +-- Sourced from http://lua-users.org/wiki/BaseSixtyFour + +-- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss +-- licensed under the terms of the LGPL2 + +-- character table string +local base64CharTable='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + +-- encoding +function tools.base64encode(data) + return ((data:gsub('.', function(x) + local r,b='',x:byte() + for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end + return r; + end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) + if (#x < 6) then return '' end + local c=0 + for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end + return base64CharTable:sub(c+1,c+1) + end)..({ '', '==', '=' })[#data%3+1]) +end + +-- decoding +function tools.base64decode(data) + data = string.gsub(data, '[^'..base64CharTable..'=]', '') + return (data:gsub('.', function(x) + if (x == '=') then return '' end + local r,f='',(base64CharTable:find(x)-1) + for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end + return r; + end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) + if (#x ~= 8) then return '' end + local c=0 + for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end + return string.char(c) + end)) +end + +-- tools变量 +json = tools.createJson(); --json处理 +this.printToConsole("load LuaPanda success", 1); +this.replaceCoroutineFuncs() +return this; diff --git a/engine/EngineResources/scripts/3rdparty/ftp.lua b/engine/EngineResources/scripts/3rdparty/ftp.lua new file mode 100644 index 00000000..0ebc5086 --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/ftp.lua @@ -0,0 +1,329 @@ +----------------------------------------------------------------------------- +-- FTP support for the Lua language +-- LuaSocket toolkit. +-- Author: Diego Nehab +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local table = require("table") +local string = require("string") +local math = require("math") +local socket = require("socket") +local url = require("socket.url") +local tp = require("socket.tp") +local ltn12 = require("ltn12") +socket.ftp = {} +local _M = socket.ftp +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +-- timeout in seconds before the program gives up on a connection +_M.TIMEOUT = 60 +-- default port for ftp service +local PORT = 21 +-- this is the default anonymous password. used when no password is +-- provided in url. should be changed to your e-mail. +_M.USER = "ftp" +_M.PASSWORD = "anonymous@anonymous.org" + +----------------------------------------------------------------------------- +-- Low level FTP API +----------------------------------------------------------------------------- +local metat = { __index = {} } + +function _M.open(server, port, create) + local tp = socket.try(tp.connect(server, port or PORT, _M.TIMEOUT, create)) + local f = base.setmetatable({ tp = tp }, metat) + -- make sure everything gets closed in an exception + f.try = socket.newtry(function() f:close() end) + return f +end + +function metat.__index:portconnect() + self.try(self.server:settimeout(_M.TIMEOUT)) + self.data = self.try(self.server:accept()) + self.try(self.data:settimeout(_M.TIMEOUT)) +end + +function metat.__index:pasvconnect() + self.data = self.try(socket.tcp()) + self.try(self.data:settimeout(_M.TIMEOUT)) + self.try(self.data:connect(self.pasvt.address, self.pasvt.port)) +end + +function metat.__index:login(user, password) + self.try(self.tp:command("user", user or _M.USER)) + local code, _ = self.try(self.tp:check{"2..", 331}) + if code == 331 then + self.try(self.tp:command("pass", password or _M.PASSWORD)) + self.try(self.tp:check("2..")) + end + return 1 +end + +function metat.__index:pasv() + self.try(self.tp:command("pasv")) + local _, reply = self.try(self.tp:check("2..")) + local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)" + local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern)) + self.try(a and b and c and d and p1 and p2, reply) + self.pasvt = { + address = string.format("%d.%d.%d.%d", a, b, c, d), + port = p1*256 + p2 + } + if self.server then + self.server:close() + self.server = nil + end + return self.pasvt.address, self.pasvt.port +end + +function metat.__index:epsv() + self.try(self.tp:command("epsv")) + local _, reply = self.try(self.tp:check("229")) + local pattern = "%((.)(.-)%1(.-)%1(.-)%1%)" + local _, _, _, port = string.match(reply, pattern) + self.try(port, "invalid epsv response") + self.pasvt = { + address = self.tp:getpeername(), + port = port + } + if self.server then + self.server:close() + self.server = nil + end + return self.pasvt.address, self.pasvt.port +end + + +function metat.__index:port(address, port) + self.pasvt = nil + if not address then + address = self.try(self.tp:getsockname()) + self.server = self.try(socket.bind(address, 0)) + address, port = self.try(self.server:getsockname()) + self.try(self.server:settimeout(_M.TIMEOUT)) + end + local pl = math.mod(port, 256) + local ph = (port - pl)/256 + local arg = string.gsub(string.format("%s,%d,%d", address, ph, pl), "%.", ",") + self.try(self.tp:command("port", arg)) + self.try(self.tp:check("2..")) + return 1 +end + +function metat.__index:eprt(family, address, port) + self.pasvt = nil + if not address then + address = self.try(self.tp:getsockname()) + self.server = self.try(socket.bind(address, 0)) + address, port = self.try(self.server:getsockname()) + self.try(self.server:settimeout(_M.TIMEOUT)) + end + local arg = string.format("|%s|%s|%d|", family, address, port) + self.try(self.tp:command("eprt", arg)) + self.try(self.tp:check("2..")) + return 1 +end + + +function metat.__index:send(sendt) + self.try(self.pasvt or self.server, "need port or pasv first") + -- if there is a pasvt table, we already sent a PASV command + -- we just get the data connection into self.data + if self.pasvt then self:pasvconnect() end + -- get the transfer argument and command + local argument = sendt.argument or + url.unescape(string.gsub(sendt.path or "", "^[/\\]", "")) + if argument == "" then argument = nil end + local command = sendt.command or "stor" + -- send the transfer command and check the reply + self.try(self.tp:command(command, argument)) + local code, _ = self.try(self.tp:check{"2..", "1.."}) + -- if there is not a pasvt table, then there is a server + -- and we already sent a PORT command + if not self.pasvt then self:portconnect() end + -- get the sink, source and step for the transfer + local step = sendt.step or ltn12.pump.step + local readt = { self.tp } + local checkstep = function(src, snk) + -- check status in control connection while downloading + local readyt = socket.select(readt, nil, 0) + if readyt[tp] then code = self.try(self.tp:check("2..")) end + return step(src, snk) + end + local sink = socket.sink("close-when-done", self.data) + -- transfer all data and check error + self.try(ltn12.pump.all(sendt.source, sink, checkstep)) + if string.find(code, "1..") then self.try(self.tp:check("2..")) end + -- done with data connection + self.data:close() + -- find out how many bytes were sent + local sent = socket.skip(1, self.data:getstats()) + self.data = nil + return sent +end + +function metat.__index:receive(recvt) + self.try(self.pasvt or self.server, "need port or pasv first") + if self.pasvt then self:pasvconnect() end + local argument = recvt.argument or + url.unescape(string.gsub(recvt.path or "", "^[/\\]", "")) + if argument == "" then argument = nil end + local command = recvt.command or "retr" + self.try(self.tp:command(command, argument)) + local code,reply = self.try(self.tp:check{"1..", "2.."}) + if (code >= 200) and (code <= 299) then + recvt.sink(reply) + return 1 + end + if not self.pasvt then self:portconnect() end + local source = socket.source("until-closed", self.data) + local step = recvt.step or ltn12.pump.step + self.try(ltn12.pump.all(source, recvt.sink, step)) + if string.find(code, "1..") then self.try(self.tp:check("2..")) end + self.data:close() + self.data = nil + return 1 +end + +function metat.__index:cwd(dir) + self.try(self.tp:command("cwd", dir)) + self.try(self.tp:check(250)) + return 1 +end + +function metat.__index:type(type) + self.try(self.tp:command("type", type)) + self.try(self.tp:check(200)) + return 1 +end + +function metat.__index:greet() + local code = self.try(self.tp:check{"1..", "2.."}) + if string.find(code, "1..") then self.try(self.tp:check("2..")) end + return 1 +end + +function metat.__index:quit() + self.try(self.tp:command("quit")) + self.try(self.tp:check("2..")) + return 1 +end + +function metat.__index:close() + if self.data then self.data:close() end + if self.server then self.server:close() end + return self.tp:close() +end + +----------------------------------------------------------------------------- +-- High level FTP API +----------------------------------------------------------------------------- +local function override(t) + if t.url then + local u = url.parse(t.url) + for i,v in base.pairs(t) do + u[i] = v + end + return u + else return t end +end + +local function tput(putt) + putt = override(putt) + socket.try(putt.host, "missing hostname") + local f = _M.open(putt.host, putt.port, putt.create) + f:greet() + f:login(putt.user, putt.password) + if putt.type then f:type(putt.type) end + f:epsv() + local sent = f:send(putt) + f:quit() + f:close() + return sent +end + +local default = { + path = "/", + scheme = "ftp" +} + +local function genericform(u) + local t = socket.try(url.parse(u, default)) + socket.try(t.scheme == "ftp", "wrong scheme '" .. t.scheme .. "'") + socket.try(t.host, "missing hostname") + local pat = "^type=(.)$" + if t.params then + t.type = socket.skip(2, string.find(t.params, pat)) + socket.try(t.type == "a" or t.type == "i", + "invalid type '" .. t.type .. "'") + end + return t +end + +_M.genericform = genericform + +local function sput(u, body) + local putt = genericform(u) + putt.source = ltn12.source.string(body) + return tput(putt) +end + +_M.put = socket.protect(function(putt, body) + if base.type(putt) == "string" then return sput(putt, body) + else return tput(putt) end +end) + +local function tget(gett) + gett = override(gett) + socket.try(gett.host, "missing hostname") + local f = _M.open(gett.host, gett.port, gett.create) + f:greet() + f:login(gett.user, gett.password) + if gett.type then f:type(gett.type) end + f:epsv() + f:receive(gett) + f:quit() + return f:close() +end + +local function sget(u) + local gett = genericform(u) + local t = {} + gett.sink = ltn12.sink.table(t) + tget(gett) + return table.concat(t) +end + +_M.command = socket.protect(function(cmdt) + cmdt = override(cmdt) + socket.try(cmdt.host, "missing hostname") + socket.try(cmdt.command, "missing command") + local f = _M.open(cmdt.host, cmdt.port, cmdt.create) + f:greet() + f:login(cmdt.user, cmdt.password) + if type(cmdt.command) == "table" then + local argument = cmdt.argument or {} + local check = cmdt.check or {} + for i,cmd in ipairs(cmdt.command) do + f.try(f.tp:command(cmd, argument[i])) + if check[i] then f.try(f.tp:check(check[i])) end + end + else + f.try(f.tp:command(cmdt.command, cmdt.argument)) + if cmdt.check then f.try(f.tp:check(cmdt.check)) end + end + f:quit() + return f:close() +end) + +_M.get = socket.protect(function(gett) + if base.type(gett) == "string" then return sget(gett) + else return tget(gett) end +end) + +return _M diff --git a/engine/EngineResources/scripts/3rdparty/headers.lua b/engine/EngineResources/scripts/3rdparty/headers.lua new file mode 100644 index 00000000..1eb8223b --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/headers.lua @@ -0,0 +1,104 @@ +----------------------------------------------------------------------------- +-- Canonic header field capitalization +-- LuaSocket toolkit. +-- Author: Diego Nehab +----------------------------------------------------------------------------- +local socket = require("socket") +socket.headers = {} +local _M = socket.headers + +_M.canonic = { + ["accept"] = "Accept", + ["accept-charset"] = "Accept-Charset", + ["accept-encoding"] = "Accept-Encoding", + ["accept-language"] = "Accept-Language", + ["accept-ranges"] = "Accept-Ranges", + ["action"] = "Action", + ["alternate-recipient"] = "Alternate-Recipient", + ["age"] = "Age", + ["allow"] = "Allow", + ["arrival-date"] = "Arrival-Date", + ["authorization"] = "Authorization", + ["bcc"] = "Bcc", + ["cache-control"] = "Cache-Control", + ["cc"] = "Cc", + ["comments"] = "Comments", + ["connection"] = "Connection", + ["content-description"] = "Content-Description", + ["content-disposition"] = "Content-Disposition", + ["content-encoding"] = "Content-Encoding", + ["content-id"] = "Content-ID", + ["content-language"] = "Content-Language", + ["content-length"] = "Content-Length", + ["content-location"] = "Content-Location", + ["content-md5"] = "Content-MD5", + ["content-range"] = "Content-Range", + ["content-transfer-encoding"] = "Content-Transfer-Encoding", + ["content-type"] = "Content-Type", + ["cookie"] = "Cookie", + ["date"] = "Date", + ["diagnostic-code"] = "Diagnostic-Code", + ["dsn-gateway"] = "DSN-Gateway", + ["etag"] = "ETag", + ["expect"] = "Expect", + ["expires"] = "Expires", + ["final-log-id"] = "Final-Log-ID", + ["final-recipient"] = "Final-Recipient", + ["from"] = "From", + ["host"] = "Host", + ["if-match"] = "If-Match", + ["if-modified-since"] = "If-Modified-Since", + ["if-none-match"] = "If-None-Match", + ["if-range"] = "If-Range", + ["if-unmodified-since"] = "If-Unmodified-Since", + ["in-reply-to"] = "In-Reply-To", + ["keywords"] = "Keywords", + ["last-attempt-date"] = "Last-Attempt-Date", + ["last-modified"] = "Last-Modified", + ["location"] = "Location", + ["max-forwards"] = "Max-Forwards", + ["message-id"] = "Message-ID", + ["mime-version"] = "MIME-Version", + ["original-envelope-id"] = "Original-Envelope-ID", + ["original-recipient"] = "Original-Recipient", + ["pragma"] = "Pragma", + ["proxy-authenticate"] = "Proxy-Authenticate", + ["proxy-authorization"] = "Proxy-Authorization", + ["range"] = "Range", + ["received"] = "Received", + ["received-from-mta"] = "Received-From-MTA", + ["references"] = "References", + ["referer"] = "Referer", + ["remote-mta"] = "Remote-MTA", + ["reply-to"] = "Reply-To", + ["reporting-mta"] = "Reporting-MTA", + ["resent-bcc"] = "Resent-Bcc", + ["resent-cc"] = "Resent-Cc", + ["resent-date"] = "Resent-Date", + ["resent-from"] = "Resent-From", + ["resent-message-id"] = "Resent-Message-ID", + ["resent-reply-to"] = "Resent-Reply-To", + ["resent-sender"] = "Resent-Sender", + ["resent-to"] = "Resent-To", + ["retry-after"] = "Retry-After", + ["return-path"] = "Return-Path", + ["sender"] = "Sender", + ["server"] = "Server", + ["smtp-remote-recipient"] = "SMTP-Remote-Recipient", + ["status"] = "Status", + ["subject"] = "Subject", + ["te"] = "TE", + ["to"] = "To", + ["trailer"] = "Trailer", + ["transfer-encoding"] = "Transfer-Encoding", + ["upgrade"] = "Upgrade", + ["user-agent"] = "User-Agent", + ["vary"] = "Vary", + ["via"] = "Via", + ["warning"] = "Warning", + ["will-retry-until"] = "Will-Retry-Until", + ["www-authenticate"] = "WWW-Authenticate", + ["x-mailer"] = "X-Mailer", +} + +return _M \ No newline at end of file diff --git a/engine/EngineResources/scripts/3rdparty/http.lua b/engine/EngineResources/scripts/3rdparty/http.lua new file mode 100644 index 00000000..259eb2b5 --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/http.lua @@ -0,0 +1,430 @@ +----------------------------------------------------------------------------- +-- HTTP/1.1 client support for the Lua language. +-- LuaSocket toolkit. +-- Author: Diego Nehab +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +------------------------------------------------------------------------------- +local socket = require("socket") +local url = require("socket.url") +local ltn12 = require("ltn12") +local mime = require("mime") +local string = require("string") +local headers = require("socket.headers") +local base = _G +local table = require("table") +socket.http = {} +local _M = socket.http + +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +-- connection timeout in seconds +_M.TIMEOUT = 60 +-- user agent field sent in request +_M.USERAGENT = socket._VERSION + +-- supported schemes and their particulars +local SCHEMES = { + http = { + port = 80 + , create = function(t) + return socket.tcp end } + , https = { + port = 443 + , create = function(t) + local https = assert( + require("ssl.https"), 'LuaSocket: LuaSec not found') + local tcp = assert( + https.tcp, 'LuaSocket: Function tcp() not available from LuaSec') + return tcp(t) end }} + +----------------------------------------------------------------------------- +-- Reads MIME headers from a connection, unfolding where needed +----------------------------------------------------------------------------- +local function receiveheaders(sock, headers) + local line, name, value, err + headers = headers or {} + -- get first line + line, err = sock:receive() + if err then return nil, err end + -- headers go until a blank line is found + while line ~= "" do + -- get field-name and value + name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)")) + if not (name and value) then return nil, "malformed response headers" end + name = string.lower(name) + -- get next line (value might be folded) + line, err = sock:receive() + if err then return nil, err end + -- unfold any folded values + while string.find(line, "^%s") do + value = value .. line + line, err = sock:receive() + if err then return nil, err end + end + -- save pair in table + if headers[name] then headers[name] = headers[name] .. ", " .. value + else headers[name] = value end + end + return headers +end + +----------------------------------------------------------------------------- +-- Extra sources and sinks +----------------------------------------------------------------------------- +socket.sourcet["http-chunked"] = function(sock, headers) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function() + -- get chunk size, skip extension + local line, err = sock:receive() + if err then return nil, err end + local size = base.tonumber(string.gsub(line, ";.*", ""), 16) + if not size then return nil, "invalid chunk size" end + -- was it the last chunk? + if size > 0 then + -- if not, get chunk and skip terminating CRLF + local chunk, err, _ = sock:receive(size) + if chunk then sock:receive() end + return chunk, err + else + -- if it was, read trailers into headers table + headers, err = receiveheaders(sock, headers) + if not headers then return nil, err end + end + end + }) +end + +socket.sinkt["http-chunked"] = function(sock) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function(self, chunk, err) + if not chunk then return sock:send("0\r\n\r\n") end + local size = string.format("%X\r\n", string.len(chunk)) + return sock:send(size .. chunk .. "\r\n") + end + }) +end + +----------------------------------------------------------------------------- +-- Low level HTTP API +----------------------------------------------------------------------------- +local metat = { __index = {} } + +function _M.open(host, port, create) + -- create socket with user connect function, or with default + local c = socket.try(create()) + local h = base.setmetatable({ c = c }, metat) + -- create finalized try + h.try = socket.newtry(function() h:close() end) + -- set timeout before connecting + h.try(c:settimeout(_M.TIMEOUT)) + h.try(c:connect(host, port)) + -- here everything worked + return h +end + +function metat.__index:sendrequestline(method, uri) + local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri) + return self.try(self.c:send(reqline)) +end + +function metat.__index:sendheaders(tosend) + local canonic = headers.canonic + local h = "\r\n" + for f, v in base.pairs(tosend) do + h = (canonic[f] or f) .. ": " .. v .. "\r\n" .. h + end + self.try(self.c:send(h)) + return 1 +end + +function metat.__index:sendbody(headers, source, step) + source = source or ltn12.source.empty() + step = step or ltn12.pump.step + -- if we don't know the size in advance, send chunked and hope for the best + local mode = "http-chunked" + if headers["content-length"] then mode = "keep-open" end + return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step)) +end + +function metat.__index:receivestatusline() + local status,ec = self.try(self.c:receive(5)) + -- identify HTTP/0.9 responses, which do not contain a status line + -- this is just a heuristic, but is what the RFC recommends + if status ~= "HTTP/" then + if ec == "timeout" then + return 408 + end + return nil, status + end + -- otherwise proceed reading a status line + status = self.try(self.c:receive("*l", status)) + local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)")) + return self.try(base.tonumber(code), status) +end + +function metat.__index:receiveheaders() + return self.try(receiveheaders(self.c)) +end + +function metat.__index:receivebody(headers, sink, step) + sink = sink or ltn12.sink.null() + step = step or ltn12.pump.step + local length = base.tonumber(headers["content-length"]) + local t = headers["transfer-encoding"] -- shortcut + local mode = "default" -- connection close + if t and t ~= "identity" then mode = "http-chunked" + elseif base.tonumber(headers["content-length"]) then mode = "by-length" end + return self.try(ltn12.pump.all(socket.source(mode, self.c, length), + sink, step)) +end + +function metat.__index:receive09body(status, sink, step) + local source = ltn12.source.rewind(socket.source("until-closed", self.c)) + source(status) + return self.try(ltn12.pump.all(source, sink, step)) +end + +function metat.__index:close() + return self.c:close() +end + +----------------------------------------------------------------------------- +-- High level HTTP API +----------------------------------------------------------------------------- +local function adjusturi(reqt) + local u = reqt + -- if there is a proxy, we need the full url. otherwise, just a part. + if not reqt.proxy and not _M.PROXY then + u = { + path = socket.try(reqt.path, "invalid path 'nil'"), + params = reqt.params, + query = reqt.query, + fragment = reqt.fragment + } + end + return url.build(u) +end + +local function adjustproxy(reqt) + local proxy = reqt.proxy or _M.PROXY + if proxy then + proxy = url.parse(proxy) + proxy.port = proxy.port or 3128 + proxy.create = SCHEMES[proxy.scheme].create(reqt) + return proxy.host, proxy.port, proxy.create + else + return reqt.host, reqt.port, reqt.create + end +end + +local function adjustheaders(reqt) + -- default headers + local host = reqt.host + local port = tostring(reqt.port) + if port ~= tostring(SCHEMES[reqt.scheme].port) then + host = host .. ':' .. port end + local lower = { + ["user-agent"] = _M.USERAGENT, + ["host"] = host, + ["connection"] = "close, TE", + ["te"] = "trailers" + } + -- if we have authentication information, pass it along + if reqt.user and reqt.password then + lower["authorization"] = + "Basic " .. (mime.b64(reqt.user .. ":" .. + url.unescape(reqt.password))) + end + -- if we have proxy authentication information, pass it along + local proxy = reqt.proxy or _M.PROXY + if proxy then + proxy = url.parse(proxy) + if proxy.user and proxy.password then + lower["proxy-authorization"] = + "Basic " .. (mime.b64(proxy.user .. ":" .. proxy.password)) + end + end + -- override with user headers + for i,v in base.pairs(reqt.headers or lower) do + lower[string.lower(i)] = v + end + return lower +end + +-- default url parts +local default = { + path ="/" + , scheme = "http" +} + +local function adjustrequest(reqt) + -- parse url if provided + local nreqt = reqt.url and url.parse(reqt.url, default) or {} + -- explicit components override url + for i,v in base.pairs(reqt) do nreqt[i] = v end + -- default to scheme particulars + local schemedefs, host, port, method + = SCHEMES[nreqt.scheme], nreqt.host, nreqt.port, nreqt.method + if not nreqt.create then nreqt.create = schemedefs.create(nreqt) end + if not (port and port ~= '') then nreqt.port = schemedefs.port end + if not (method and method ~= '') then nreqt.method = 'GET' end + if not (host and host ~= "") then + socket.try(nil, "invalid host '" .. base.tostring(nreqt.host) .. "'") + end + -- compute uri if user hasn't overridden + nreqt.uri = reqt.uri or adjusturi(nreqt) + -- adjust headers in request + nreqt.headers = adjustheaders(nreqt) + if nreqt.source + and not nreqt.headers["content-length"] + and not nreqt.headers["transfer-encoding"] + then + nreqt.headers["transfer-encoding"] = "chunked" + end + + -- ajust host and port if there is a proxy + local proxy_create + nreqt.host, nreqt.port, proxy_create = adjustproxy(nreqt) + if not reqt.create then nreqt.create = proxy_create end + + return nreqt +end + +local function shouldredirect(reqt, code, headers) + local location = headers.location + if not location then return false end + location = string.gsub(location, "%s", "") + if location == "" then return false end + -- the RFC says the redirect URL may be relative + location = url.absolute(reqt.url, location) + local scheme = url.parse(location).scheme + if scheme and (not SCHEMES[scheme]) then return false end + -- avoid https downgrades + if ('https' == reqt.scheme) and ('https' ~= scheme) then return false end + return (reqt.redirect ~= false) and + (code == 301 or code == 302 or code == 303 or code == 307) and + (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD") + and ((false == reqt.maxredirects) + or ((reqt.nredirects or 0) + < (reqt.maxredirects or 5))) +end + +local function shouldreceivebody(reqt, code) + if reqt.method == "HEAD" then return nil end + if code == 204 or code == 304 then return nil end + if code >= 100 and code < 200 then return nil end + return 1 +end + +-- forward declarations +local trequest, tredirect + +--[[local]] function tredirect(reqt, location) + -- the RFC says the redirect URL may be relative + local newurl = url.absolute(reqt.url, location) + -- if switching schemes, reset port and create function + if url.parse(newurl).scheme ~= reqt.scheme then + reqt.port = nil + reqt.create = nil end + -- make new request + local result, code, headers, status = trequest { + url = newurl, + source = reqt.source, + sink = reqt.sink, + headers = reqt.headers, + proxy = reqt.proxy, + maxredirects = reqt.maxredirects, + nredirects = (reqt.nredirects or 0) + 1, + create = reqt.create + } + -- pass location header back as a hint we redirected + headers = headers or {} + headers.location = headers.location or location + return result, code, headers, status +end + +--[[local]] function trequest(reqt) + -- we loop until we get what we want, or + -- until we are sure there is no way to get it + local nreqt = adjustrequest(reqt) + local h = _M.open(nreqt.host, nreqt.port, nreqt.create) + -- send request line and headers + h:sendrequestline(nreqt.method, nreqt.uri) + h:sendheaders(nreqt.headers) + -- if there is a body, send it + if nreqt.source then + h:sendbody(nreqt.headers, nreqt.source, nreqt.step) + end + local code, status = h:receivestatusline() + -- if it is an HTTP/0.9 server, simply get the body and we are done + if not code then + h:receive09body(status, nreqt.sink, nreqt.step) + return 1, 200 + elseif code == 408 then + return 1, code + end + local headers + -- ignore any 100-continue messages + while code == 100 do + h:receiveheaders() + code, status = h:receivestatusline() + end + headers = h:receiveheaders() + -- at this point we should have a honest reply from the server + -- we can't redirect if we already used the source, so we report the error + if shouldredirect(nreqt, code, headers) and not nreqt.source then + h:close() + return tredirect(reqt, headers.location) + end + -- here we are finally done + if shouldreceivebody(nreqt, code) then + h:receivebody(headers, nreqt.sink, nreqt.step) + end + h:close() + return 1, code, headers, status +end + +-- turns an url and a body into a generic request +local function genericform(u, b) + local t = {} + local reqt = { + url = u, + sink = ltn12.sink.table(t), + target = t + } + if b then + reqt.source = ltn12.source.string(b) + reqt.headers = { + ["content-length"] = string.len(b), + ["content-type"] = "application/x-www-form-urlencoded" + } + reqt.method = "POST" + end + return reqt +end + +_M.genericform = genericform + +local function srequest(u, b) + local reqt = genericform(u, b) + local _, code, headers, status = trequest(reqt) + return table.concat(reqt.target), code, headers, status +end + +_M.request = socket.protect(function(reqt, body) + if base.type(reqt) == "string" then return srequest(reqt, body) + else return trequest(reqt) end +end) + +_M.schemes = SCHEMES +return _M diff --git a/engine/EngineResources/scripts/3rdparty/ltn12.lua b/engine/EngineResources/scripts/3rdparty/ltn12.lua new file mode 100644 index 00000000..4cb17f53 --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/ltn12.lua @@ -0,0 +1,318 @@ +----------------------------------------------------------------------------- +-- LTN12 - Filters, sources, sinks and pumps. +-- LuaSocket toolkit. +-- Author: Diego Nehab +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module +----------------------------------------------------------------------------- +local string = require("string") +local table = require("table") +local unpack = unpack or table.unpack +local base = _G +local select = select + +local _M = {} +if module then -- heuristic for exporting a global package table + ltn12 = _M -- luacheck: ignore +end +local filter,source,sink,pump = {},{},{},{} + +_M.filter = filter +_M.source = source +_M.sink = sink +_M.pump = pump + +-- 2048 seems to be better in windows... +_M.BLOCKSIZE = 2048 +_M._VERSION = "LTN12 1.0.3" + +----------------------------------------------------------------------------- +-- Filter stuff +----------------------------------------------------------------------------- +-- returns a high level filter that cycles a low-level filter +function filter.cycle(low, ctx, extra) + base.assert(low) + return function(chunk) + local ret + ret, ctx = low(ctx, chunk, extra) + return ret + end +end + +-- chains a bunch of filters together +-- (thanks to Wim Couwenberg) +function filter.chain(...) + local arg = {...} + local n = select('#',...) + local top, index = 1, 1 + local retry = "" + return function(chunk) + retry = chunk and retry + while true do + if index == top then + chunk = arg[index](chunk) + if chunk == "" or top == n then return chunk + elseif chunk then index = index + 1 + else + top = top+1 + index = top + end + else + chunk = arg[index](chunk or "") + if chunk == "" then + index = index - 1 + chunk = retry + elseif chunk then + if index == n then return chunk + else index = index + 1 end + else base.error("filter returned inappropriate nil") end + end + end + end +end + +----------------------------------------------------------------------------- +-- Source stuff +----------------------------------------------------------------------------- +-- create an empty source +local function empty() + return nil +end + +function source.empty() + return empty +end + +-- returns a source that just outputs an error +function source.error(err) + return function() + return nil, err + end +end + +-- creates a file source +function source.file(handle, io_err) + if handle then + return function() + local chunk = handle:read(_M.BLOCKSIZE) + if not chunk then handle:close() end + return chunk + end + else return source.error(io_err or "unable to open file") end +end + +-- turns a fancy source into a simple source +function source.simplify(src) + base.assert(src) + return function() + local chunk, err_or_new = src() + src = err_or_new or src + if not chunk then return nil, err_or_new + else return chunk end + end +end + +-- creates string source +function source.string(s) + if s then + local i = 1 + return function() + local chunk = string.sub(s, i, i+_M.BLOCKSIZE-1) + i = i + _M.BLOCKSIZE + if chunk ~= "" then return chunk + else return nil end + end + else return source.empty() end +end + +-- creates table source +function source.table(t) + base.assert('table' == type(t)) + local i = 0 + return function() + i = i + 1 + return t[i] + end +end + +-- creates rewindable source +function source.rewind(src) + base.assert(src) + local t = {} + return function(chunk) + if not chunk then + chunk = table.remove(t) + if not chunk then return src() + else return chunk end + else + table.insert(t, chunk) + end + end +end + +-- chains a source with one or several filter(s) +function source.chain(src, f, ...) + if ... then f=filter.chain(f, ...) end + base.assert(src and f) + local last_in, last_out = "", "" + local state = "feeding" + local err + return function() + if not last_out then + base.error('source is empty!', 2) + end + while true do + if state == "feeding" then + last_in, err = src() + if err then return nil, err end + last_out = f(last_in) + if not last_out then + if last_in then + base.error('filter returned inappropriate nil') + else + return nil + end + elseif last_out ~= "" then + state = "eating" + if last_in then last_in = "" end + return last_out + end + else + last_out = f(last_in) + if last_out == "" then + if last_in == "" then + state = "feeding" + else + base.error('filter returned ""') + end + elseif not last_out then + if last_in then + base.error('filter returned inappropriate nil') + else + return nil + end + else + return last_out + end + end + end + end +end + +-- creates a source that produces contents of several sources, one after the +-- other, as if they were concatenated +-- (thanks to Wim Couwenberg) +function source.cat(...) + local arg = {...} + local src = table.remove(arg, 1) + return function() + while src do + local chunk, err = src() + if chunk then return chunk end + if err then return nil, err end + src = table.remove(arg, 1) + end + end +end + +----------------------------------------------------------------------------- +-- Sink stuff +----------------------------------------------------------------------------- +-- creates a sink that stores into a table +function sink.table(t) + t = t or {} + local f = function(chunk, err) + if chunk then table.insert(t, chunk) end + return 1 + end + return f, t +end + +-- turns a fancy sink into a simple sink +function sink.simplify(snk) + base.assert(snk) + return function(chunk, err) + local ret, err_or_new = snk(chunk, err) + if not ret then return nil, err_or_new end + snk = err_or_new or snk + return 1 + end +end + +-- creates a file sink +function sink.file(handle, io_err) + if handle then + return function(chunk, err) + if not chunk then + handle:close() + return 1 + else return handle:write(chunk) end + end + else return sink.error(io_err or "unable to open file") end +end + +-- creates a sink that discards data +local function null() + return 1 +end + +function sink.null() + return null +end + +-- creates a sink that just returns an error +function sink.error(err) + return function() + return nil, err + end +end + +-- chains a sink with one or several filter(s) +function sink.chain(f, snk, ...) + if ... then + local args = { f, snk, ... } + snk = table.remove(args, #args) + f = filter.chain(unpack(args)) + end + base.assert(f and snk) + return function(chunk, err) + if chunk ~= "" then + local filtered = f(chunk) + local done = chunk and "" + while true do + local ret, snkerr = snk(filtered, err) + if not ret then return nil, snkerr end + if filtered == done then return 1 end + filtered = f(done) + end + else return 1 end + end +end + +----------------------------------------------------------------------------- +-- Pump stuff +----------------------------------------------------------------------------- +-- pumps one chunk from the source to the sink +function pump.step(src, snk) + local chunk, src_err = src() + local ret, snk_err = snk(chunk, src_err) + if chunk and ret then return 1 + else return nil, src_err or snk_err end +end + +-- pumps all data from a source to a sink, using a step function +function pump.all(src, snk, step) + base.assert(src and snk) + step = step or pump.step + while true do + local ret, err = step(src, snk) + if not ret then + if err then return nil, err + else return 1 end + end + end +end + +return _M diff --git a/engine/EngineResources/scripts/3rdparty/mbox.lua b/engine/EngineResources/scripts/3rdparty/mbox.lua new file mode 100644 index 00000000..12823b0a --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/mbox.lua @@ -0,0 +1,93 @@ +local _M = {} + +if module then + mbox = _M -- luacheck: ignore +end + +function _M.split_message(message_s) + local message = {} + message_s = string.gsub(message_s, "\r\n", "\n") + string.gsub(message_s, "^(.-\n)\n", function (h) message.headers = h end) + string.gsub(message_s, "^.-\n\n(.*)", function (b) message.body = b end) + if not message.body then + string.gsub(message_s, "^\n(.*)", function (b) message.body = b end) + end + if not message.headers and not message.body then + message.headers = message_s + end + return message.headers or "", message.body or "" +end + +function _M.split_headers(headers_s) + local headers = {} + headers_s = string.gsub(headers_s, "\r\n", "\n") + headers_s = string.gsub(headers_s, "\n[ ]+", " ") + string.gsub("\n" .. headers_s, "\n([^\n]+)", function (h) table.insert(headers, h) end) + return headers +end + +function _M.parse_header(header_s) + header_s = string.gsub(header_s, "\n[ ]+", " ") + header_s = string.gsub(header_s, "\n+", "") + local _, _, name, value = string.find(header_s, "([^%s:]-):%s*(.*)") + return name, value +end + +function _M.parse_headers(headers_s) + local headers_t = _M.split_headers(headers_s) + local headers = {} + for i = 1, #headers_t do + local name, value = _M.parse_header(headers_t[i]) + if name then + name = string.lower(name) + if headers[name] then + headers[name] = headers[name] .. ", " .. value + else headers[name] = value end + end + end + return headers +end + +function _M.parse_from(from) + local _, _, name, address = string.find(from, "^%s*(.-)%s*%<(.-)%>") + if not address then + _, _, address = string.find(from, "%s*(.+)%s*") + end + name = name or "" + address = address or "" + if name == "" then name = address end + name = string.gsub(name, '"', "") + return name, address +end + +function _M.split_mbox(mbox_s) + local mbox = {} + mbox_s = string.gsub(mbox_s, "\r\n", "\n") .."\n\nFrom \n" + local nj, i + local j = 1 + while 1 do + i, nj = string.find(mbox_s, "\n\nFrom .-\n", j) + if not i then break end + local message = string.sub(mbox_s, j, i-1) + table.insert(mbox, message) + j = nj+1 + end + return mbox +end + +function _M.parse(mbox_s) + local mbox = _M.split_mbox(mbox_s) + for i = 1, #mbox do + mbox[i] = _M.parse_message(mbox[i]) + end + return mbox +end + +function _M.parse_message(message_s) + local message = {} + message.headers, message.body = _M.split_message(message_s) + message.headers = _M.parse_headers(message.headers) + return message +end + +return _M diff --git a/engine/EngineResources/scripts/3rdparty/mime.lua b/engine/EngineResources/scripts/3rdparty/mime.lua new file mode 100644 index 00000000..93539de6 --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/mime.lua @@ -0,0 +1,81 @@ +----------------------------------------------------------------------------- +-- MIME support for the Lua language. +-- Author: Diego Nehab +-- Conforming to RFCs 2045-2049 +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local ltn12 = require("ltn12") +local mime = require("mime.core") +local _M = mime + +-- encode, decode and wrap algorithm tables +local encodet, decodet, wrapt = {},{},{} + +_M.encodet = encodet +_M.decodet = decodet +_M.wrapt = wrapt + +-- creates a function that chooses a filter by name from a given table +local function choose(table) + return function(name, opt1, opt2) + if base.type(name) ~= "string" then + name, opt1, opt2 = "default", name, opt1 + end + local f = table[name or "nil"] + if not f then + base.error("unknown key (" .. base.tostring(name) .. ")", 3) + else return f(opt1, opt2) end + end +end + +-- define the encoding filters +encodet['base64'] = function() + return ltn12.filter.cycle(_M.b64, "") +end + +encodet['quoted-printable'] = function(mode) + return ltn12.filter.cycle(_M.qp, "", + (mode == "binary") and "=0D=0A" or "\r\n") +end + +-- define the decoding filters +decodet['base64'] = function() + return ltn12.filter.cycle(_M.unb64, "") +end + +decodet['quoted-printable'] = function() + return ltn12.filter.cycle(_M.unqp, "") +end + +-- define the line-wrap filters +wrapt['text'] = function(length) + length = length or 76 + return ltn12.filter.cycle(_M.wrp, length, length) +end +wrapt['base64'] = wrapt['text'] +wrapt['default'] = wrapt['text'] + +wrapt['quoted-printable'] = function() + return ltn12.filter.cycle(_M.qpwrp, 76, 76) +end + +-- function that choose the encoding, decoding or wrap algorithm +_M.encode = choose(encodet) +_M.decode = choose(decodet) +_M.wrap = choose(wrapt) + +-- define the end-of-line normalization filter +function _M.normalize(marker) + return ltn12.filter.cycle(_M.eol, 0, marker) +end + +-- high level stuffing filter +function _M.stuff() + return ltn12.filter.cycle(_M.dot, 2) +end + +return _M diff --git a/engine/EngineResources/scripts/3rdparty/mobdebug.lua b/engine/EngineResources/scripts/3rdparty/mobdebug.lua new file mode 100644 index 00000000..8b2cc3bf --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/mobdebug.lua @@ -0,0 +1,1670 @@ +-- +-- MobDebug -- Lua remote debugger +-- Copyright 2011-23 Paul Kulchenko +-- Based on RemDebug 1.0 Copyright Kepler Project 2005 +-- + +-- use loaded modules or load explicitly on those systems that require that +local require = require +local io = io or require "io" +local table = table or require "table" +local string = string or require "string" +local coroutine = coroutine or require "coroutine" +local debug = require "debug" +-- protect require "os" as it may fail on embedded systems without os module +local os = os or (function(module) + local ok, res = pcall(require, module) + return ok and res or nil +end)("os") + +local mobdebug = { + _NAME = "mobdebug", + _VERSION = "0.805", + _COPYRIGHT = "Paul Kulchenko", + _DESCRIPTION = "Mobile Remote Debugger for the Lua programming language", + port = os and os.getenv and tonumber((os.getenv("MOBDEBUG_PORT"))) or 8172, + checkcount = 200, + yieldtimeout = 0.02, -- yield timeout (s) + connecttimeout = 2, -- connect timeout (s) +} + +local HOOKMASK = "lcr" +local error = error +local getfenv = getfenv +local setfenv = setfenv +local loadstring = loadstring or load -- "load" replaced "loadstring" in Lua 5.2 +local pairs = pairs +local setmetatable = setmetatable +local tonumber = tonumber +local unpack = table.unpack or unpack +local rawget = rawget +local gsub, sub, find = string.gsub, string.sub, string.find + +-- if strict.lua is used, then need to avoid referencing some global +-- variables, as they can be undefined; +-- use rawget to avoid complaints from strict.lua at run-time. +-- it's safe to do the initialization here as all these variables +-- should get defined values (if any) before the debugging starts. +-- there is also global 'wx' variable, which is checked as part of +-- the debug loop as 'wx' can be loaded at any time during debugging. +local genv = _G or _ENV +local jit = rawget(genv, "jit") +local MOAICoroutine = rawget(genv, "MOAICoroutine") + +-- ngx_lua/Openresty requires special handling as its coroutine.* +-- methods use a different mechanism that doesn't allow resume calls +-- from debug hook handlers. +-- Instead, the "original" coroutine.* methods are used. +-- `rawget` needs to be used to protect against `strict` checks +local ngx = rawget(genv, "ngx") +if not ngx then + -- "older" versions of ngx_lua (0.10.x at least) hide ngx table in metatable, + -- so need to use that + local metagindex = getmetatable(genv) and getmetatable(genv).__index + ngx = type(metagindex) == "table" and metagindex.rawget and metagindex:rawget("ngx") or nil +end +local corocreate = ngx and coroutine._create or coroutine.create +local cororesume = ngx and coroutine._resume or coroutine.resume +local coroyield = ngx and coroutine._yield or coroutine.yield +local corostatus = ngx and coroutine._status or coroutine.status +local corowrap = coroutine.wrap + +if not setfenv then -- Lua 5.2+ + -- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html + -- this assumes f is a function + local function findenv(f) + if not debug.getupvalue then return nil end + local level = 1 + repeat + local name, value = debug.getupvalue(f, level) + if name == '_ENV' then return level, value end + level = level + 1 + until name == nil + return nil end + getfenv = function (f) return(select(2, findenv(f)) or _G) end + setfenv = function (f, t) + local level = findenv(f) + if level then debug.setupvalue(f, level, t) end + return f end +end + +-- check for OS and convert file names to lower case on windows +-- (its file system is case insensitive, but case preserving), as setting a +-- breakpoint on x:\Foo.lua will not work if the file was loaded as X:\foo.lua. +-- OSX and Windows behave the same way (case insensitive, but case preserving). +-- OSX can be configured to be case-sensitive, so check for that. This doesn't +-- handle the case of different partitions having different case-sensitivity. +local win = os and os.getenv and (os.getenv('WINDIR') or (os.getenv('OS') or ''):match('[Ww]indows')) and true or false +local mac = not win and (os and os.getenv and os.getenv('DYLD_LIBRARY_PATH') or not io.open("/proc")) and true or false +local iscasepreserving = win or (mac and io.open('/library') ~= nil) + +-- turn jit off based on Mike Pall's comment in this discussion: +-- http://www.freelists.org/post/luajit/Debug-hooks-and-JIT,2 +-- "You need to turn it off at the start if you plan to receive +-- reliable hook calls at any later point in time." +if jit and jit.off then jit.off() end + +local socket = require "socket" +local coro_debugger +local coro_debugee +local coroutines = {}; setmetatable(coroutines, {__mode = "k"}) -- "weak" keys +local events = { BREAK = 1, WATCH = 2, RESTART = 3, STACK = 4 } +local breakpoints = {} +local watches = {} +local lastsource +local lastfile +local watchescnt = 0 +local abort -- default value is nil; this is used in start/loop distinction +local seen_hook = false +local checkcount = 0 +local step_into = false +local step_over = false +local step_level = 0 +local stack_level = 0 +local SAFEWS = "\012" -- "safe" whitespace value +local server +local buf +local outputs = {} +local iobase = {print = print} +local basedir = "" +local deferror = "execution aborted at default debugee" +local debugee = function () + local a = 1 + for _ = 1, 10 do a = a + 1 end + error(deferror) +end +local function q(s) return string.gsub(s, '([%(%)%.%%%+%-%*%?%[%^%$%]])','%%%1') end + +local serpent = (function() ---- include Serpent module for serialization +local n, v = "serpent", "0.302" -- (C) 2012-18 Paul Kulchenko; MIT License +local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" +local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} +local badtype = {thread = true, userdata = true, cdata = true} +local getmetatable = debug and debug.getmetatable or getmetatable +local pairs = function(t) return next, t end -- avoid using __pairs in Lua 5.2+ +local keyword, globals, G = {}, {}, (_G or _ENV) +for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', + 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', + 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end +for k,v in pairs(G) do globals[v] = k end -- build func to name mapping +for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do + for k,v in pairs(type(G[g]) == 'table' and G[g] or {}) do globals[v] = g..'.'..k end end + +local function s(t, opts) + local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum + local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge + local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) + local maxlen, metatostring = tonumber(opts.maxlength), opts.metatostring + local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) + local numformat = opts.numformat or "%.17g" + local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 + local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", + -- tostring(val) is needed because __tostring may return a non-string value + function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end + local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or numformat:format(s)) + or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 + or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end + local function comment(s,l) return comm and (l or 0) < comm and ' --[['..select(2, pcall(tostring, s))..']]' or '' end + local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal + and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end + local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] + local n = name == nil and '' or name + local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] + local safe = plain and n or '['..safestr(n)..']' + return (path or '')..(plain and path and '.' or '')..safe, safe end + local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding + local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} + local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end + table.sort(k, function(a,b) + -- sort numeric keys first: k[key] is not nil for numerical keys + return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) + < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end + local function val2str(t, name, indent, insref, path, plainindex, level) + local ttype, level, mt = type(t), (level or 0), getmetatable(t) + local spath, sname = safename(path, name) + local tag = plainindex and + ((type(name) == "number") and '' or name..space..'='..space) or + (name ~= nil and sname..space..'='..space or '') + if seen[t] then -- already seen this element + sref[#sref+1] = spath..space..'='..space..seen[t] + return tag..'nil'..comment('ref', level) end + -- protect from those cases where __tostring may fail + if type(mt) == 'table' and metatostring ~= false then + local to, tr = pcall(function() return mt.__tostring(t) end) + local so, sr = pcall(function() return mt.__serialize(t) end) + if (to or so) then -- knows how to serialize itself + seen[t] = insref or spath + t = so and sr or tr + ttype = type(t) + end -- new value falls through to be serialized + end + if ttype == "table" then + if level >= maxl then return tag..'{}'..comment('maxlvl', level) end + seen[t] = insref or spath + if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty + if maxlen and maxlen < 0 then return tag..'{}'..comment('maxlen', level) end + local maxn, o, out = math.min(#t, maxnum or #t), {}, {} + for key = 1, maxn do o[key] = key end + if not maxnum or #o < maxnum then + local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables + for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end + if maxnum and #o > maxnum then o[maxnum+1] = nil end + if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end + local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) + for n, key in ipairs(o) do + local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse + if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing + or opts.keyallow and not opts.keyallow[key] + or opts.keyignore and opts.keyignore[key] + or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types + or sparse and value == nil then -- skipping nils; do nothing + elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then + if not seen[key] and not globals[key] then + sref[#sref+1] = 'placeholder' + local sname = safename(iname, gensym(key)) -- iname is table for local variables + sref[#sref] = val2str(key,sname,indent,sname,iname,true) end + sref[#sref+1] = 'placeholder' + local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' + sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) + else + out[#out+1] = val2str(value,key,indent,nil,seen[t],plainindex,level+1) + if maxlen then + maxlen = maxlen - #out[#out] + if maxlen < 0 then break end + end + end + end + local prefix = string.rep(indent or '', level) + local head = indent and '{\n'..prefix..indent or '{' + local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) + local tail = indent and "\n"..prefix..'}' or '}' + return (custom and custom(tag,head,body,tail,level) or tag..head..body..tail)..comment(t, level) + elseif badtype[ttype] then + seen[t] = insref or spath + return tag..globerr(t, level) + elseif ttype == 'function' then + seen[t] = insref or spath + if opts.nocode then return tag.."function() --[[..skipped..]] end"..comment(t, level) end + local ok, res = pcall(string.dump, t) + local func = ok and "((loadstring or load)("..safestr(res)..",'@serialized'))"..comment(t, level) + return tag..(func or globerr(t, level)) + else return tag..safestr(t) end -- handle all other types + end + local sepr = indent and "\n" or ";"..space + local body = val2str(t, name, indent) -- this call also populates sref + local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' + local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' + return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" +end + +local function deserialize(data, opts) + local env = (opts and opts.safe == false) and G + or setmetatable({}, { + __index = function(t,k) return t end, + __call = function(t,...) error("cannot call functions") end + }) + local f, res = (loadstring or load)('return '..data, nil, nil, env) + if not f then f, res = (loadstring or load)(data, nil, nil, env) end + if not f then return f, res end + if setfenv then setfenv(f, env) end + return pcall(f) +end + +local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end +return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, + load = deserialize, + dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, + line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, + block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end } +end)() ---- end of Serpent module + +mobdebug.line = serpent.line +mobdebug.dump = serpent.dump +mobdebug.linemap = nil +mobdebug.loadstring = loadstring + +local function removebasedir(path, basedir) + if iscasepreserving then + -- check if the lowercased path matches the basedir + -- if so, return substring of the original path (to not lowercase it) + return path:lower():find('^'..q(basedir:lower())) + and path:sub(#basedir+1) or path + else + return string.gsub(path, '^'..q(basedir), '') + end +end + +local function stack(start) + local function vars(f) + local func = debug.getinfo(f, "f").func + local i = 1 + local locals = {} + -- get locals + while true do + local name, value = debug.getlocal(f, i) + if not name then break end + if string.sub(name, 1, 1) ~= '(' then + locals[name] = {value, select(2,pcall(tostring,value))} + end + i = i + 1 + end + -- get varargs (these use negative indices) + i = 1 + while true do + local name, value = debug.getlocal(f, -i) + if not name then break end + locals[name:gsub("%)$"," "..i..")")] = {value, select(2,pcall(tostring,value))} + i = i + 1 + end + -- get upvalues + i = 1 + local ups = {} + while func and debug.getupvalue do -- check for func as it may be nil for tail calls + local name, value = debug.getupvalue(func, i) + if not name then break end + ups[name] = {value, select(2,pcall(tostring,value))} + i = i + 1 + end + return locals, ups + end + + local stack = {} + local linemap = mobdebug.linemap + for i = (start or 0), 100 do + local source = debug.getinfo(i, "Snl") + if not source then break end + + local src = source.source + if src:find("@") == 1 then + src = src:sub(2):gsub("\\", "/") + if src:find("%./") == 1 then src = src:sub(3) end + end + + table.insert(stack, { -- remove basedir from source + {source.name, removebasedir(src, basedir), + linemap and linemap(source.linedefined, source.source) or source.linedefined, + linemap and linemap(source.currentline, source.source) or source.currentline, + source.what, source.namewhat, source.short_src}, + vars(i+1)}) + end + return stack +end + +local function set_breakpoint(file, line) + if file == '-' and lastfile then file = lastfile + elseif iscasepreserving then file = string.lower(file) end + if not breakpoints[line] then breakpoints[line] = {} end + breakpoints[line][file] = true +end + +local function remove_breakpoint(file, line) + if file == '-' and lastfile then file = lastfile + elseif file == '*' and line == 0 then breakpoints = {} + elseif iscasepreserving then file = string.lower(file) end + if breakpoints[line] then breakpoints[line][file] = nil end +end + +local function has_breakpoint(file, line) + return breakpoints[line] + and breakpoints[line][iscasepreserving and string.lower(file) or file] +end + +local function restore_vars(vars) + if type(vars) ~= 'table' then return end + + -- locals need to be processed in the reverse order, starting from + -- the inner block out, to make sure that the localized variables + -- are correctly updated with only the closest variable with + -- the same name being changed + -- first loop find how many local variables there is, while + -- the second loop processes them from i to 1 + local i = 1 + while true do + local name = debug.getlocal(3, i) + if not name then break end + i = i + 1 + end + i = i - 1 + local written_vars = {} + while i > 0 do + local name = debug.getlocal(3, i) + if not written_vars[name] then + if string.sub(name, 1, 1) ~= '(' then + debug.setlocal(3, i, rawget(vars, name)) + end + written_vars[name] = true + end + i = i - 1 + end + + i = 1 + local func = debug.getinfo(3, "f").func + while debug.getupvalue do + local name = debug.getupvalue(func, i) + if not name then break end + if not written_vars[name] then + if string.sub(name, 1, 1) ~= '(' then + debug.setupvalue(func, i, rawget(vars, name)) + end + written_vars[name] = true + end + i = i + 1 + end +end + +local function capture_vars(level, thread) + level = (level or 0)+2 -- add two levels for this and debug calls + local func = (thread and debug.getinfo(thread, level, "f") or debug.getinfo(level, "f") or {}).func + if not func then return {} end + + local vars = {['...'] = {}} + local i = 1 + while debug.getupvalue do + local name, value = debug.getupvalue(func, i) + if not name then break end + if string.sub(name, 1, 1) ~= '(' then vars[name] = value end + i = i + 1 + end + i = 1 + while true do + local name, value + if thread then + name, value = debug.getlocal(thread, level, i) + else + name, value = debug.getlocal(level, i) + end + if not name then break end + if string.sub(name, 1, 1) ~= '(' then vars[name] = value end + i = i + 1 + end + -- get varargs (these use negative indices) + i = 1 + while true do + local name, value + if thread then + name, value = debug.getlocal(thread, level, -i) + else + name, value = debug.getlocal(level, -i) + end + if not name then break end + vars['...'][i] = value + i = i + 1 + end + -- returned 'vars' table plays a dual role: (1) it captures local values + -- and upvalues to be restored later (in case they are modified in "eval"), + -- and (2) it provides an environment for evaluated chunks. + -- getfenv(func) is needed to provide proper environment for functions, + -- including access to globals, but this causes vars[name] to fail in + -- restore_vars on local variables or upvalues with `nil` values when + -- 'strict' is in effect. To avoid this `rawget` is used in restore_vars. + setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func), __mode = "v" }) + return vars +end + +local function stack_depth(start_depth) + for i = start_depth, 0, -1 do + if debug.getinfo(i, "l") then return i+1 end + end + return start_depth +end + +local function is_safe(stack_level) + -- the stack grows up: 0 is getinfo, 1 is is_safe, 2 is debug_hook, 3 is user function + if stack_level == 3 then return true end + for i = 3, stack_level do + -- return if it is not safe to abort + local info = debug.getinfo(i, "S") + if not info then return true end + if info.what == "C" then return false end + end + return true +end + +local function in_debugger() + local this = debug.getinfo(1, "S").source + -- only need to check few frames as mobdebug frames should be close + for i = 3, 7 do + local info = debug.getinfo(i, "S") + if not info then return false end + if info.source == this then return true end + end + return false +end + +local function is_pending(peer) + -- if there is something already in the buffer, skip check + if not buf and checkcount >= mobdebug.checkcount then + peer:settimeout(0) -- non-blocking + buf = peer:receive(1) + peer:settimeout() -- back to blocking + checkcount = 0 + end + return buf +end + +local function readnext(peer, num) + peer:settimeout(0) -- non-blocking + local res, err, partial = peer:receive(num) + peer:settimeout() -- back to blocking + return res or partial or '', err +end + +local function handle_breakpoint(peer) + -- check if the buffer has the beginning of SETB/DELB command; + -- this is to avoid reading the entire line for commands that + -- don't need to be handled here. + if not buf or not (buf:sub(1,1) == 'S' or buf:sub(1,1) == 'D') then return end + + -- check second character to avoid reading STEP or other S* and D* commands + if #buf == 1 then buf = buf .. readnext(peer, 1) end + if buf:sub(2,2) ~= 'E' then return end + + -- need to read few more characters + buf = buf .. readnext(peer, 5-#buf) + if buf ~= 'SETB ' and buf ~= 'DELB ' then return end + + local res, _, partial = peer:receive("*l") -- get the rest of the line; blocking + if not res then + if partial then buf = buf .. partial end + return + end + + local _, _, cmd, file, line = (buf..res):find("^([A-Z]+)%s+(.-)%s+(%d+)%s*$") + if cmd == 'SETB' then set_breakpoint(file, tonumber(line)) + elseif cmd == 'DELB' then remove_breakpoint(file, tonumber(line)) + else + -- this looks like a breakpoint command, but something went wrong; + -- return here to let the "normal" processing to handle, + -- although this is likely to not go well. + return + end + + buf = nil +end + +local function normalize_path(file) + local n + repeat + file, n = file:gsub("/+%.?/+","/") -- remove all `//` and `/./` references + until n == 0 + -- collapse all up-dir references: this will clobber UNC prefix (\\?\) + -- and disk on Windows when there are too many up-dir references: `D:\foo\..\..\bar`; + -- handle the case of multiple up-dir references: `foo/bar/baz/../../../more`; + -- only remove one at a time as otherwise `../../` could be removed; + repeat + file, n = file:gsub("[^/]+/%.%./", "", 1) + until n == 0 + -- there may still be a leading up-dir reference left (as `/../` or `../`); remove it + return (file:gsub("^(/?)%.%./", "%1")) +end + +local function debug_hook(event, line) + -- (1) LuaJIT needs special treatment. Because debug_hook is set for + -- *all* coroutines, and not just the one being debugged as in regular Lua + -- (http://lua-users.org/lists/lua-l/2011-06/msg00513.html), + -- need to avoid debugging mobdebug's own code as LuaJIT doesn't + -- always correctly generate call/return hook events (there are more + -- calls than returns, which breaks stack depth calculation and + -- 'step' and 'step over' commands stop working; possibly because + -- 'tail return' events are not generated by LuaJIT). + -- the next line checks if the debugger is run under LuaJIT and if + -- one of debugger methods is present in the stack, it simply returns. + -- ngx_lua/Openresty requires a slightly different handling, as it + -- creates a coroutine wrapper, so this processing needs to be skipped. + if jit and not (ngx and type(ngx) == "table" and ngx.say) then + -- when luajit is compiled with LUAJIT_ENABLE_LUA52COMPAT, + -- coroutine.running() returns non-nil for the main thread. + local coro, main = coroutine.running() + if not coro or main then coro = 'main' end + local disabled = coroutines[coro] == false + or coroutines[coro] == nil and coro ~= (coro_debugee or 'main') + if coro_debugee and disabled or not coro_debugee and (disabled or in_debugger()) then + return + end + end + + -- (2) check if abort has been requested and it's safe to abort + if abort and is_safe(stack_level) then error(abort) end + + -- (3) also check if this debug hook has not been visited for any reason. + -- this check is needed to avoid stepping in too early + -- (for example, when coroutine.resume() is executed inside start()). + if not seen_hook and in_debugger() then return end + + if event == "call" then + stack_level = stack_level + 1 + elseif event == "return" or event == "tail return" then + stack_level = stack_level - 1 + elseif event == "line" then + if mobdebug.linemap then + local ok, mappedline = pcall(mobdebug.linemap, line, debug.getinfo(2, "S").source) + if ok then line = mappedline end + if not line then return end + end + + -- may need to fall through because of the following: + -- (1) step_into + -- (2) step_over and stack_level <= step_level (need stack_level) + -- (3) breakpoint; check for line first as it's known; then for file + -- (4) socket call (only do every Xth check) + -- (5) at least one watch is registered + if not ( + step_into or step_over or breakpoints[line] or watchescnt > 0 + or is_pending(server) + ) then checkcount = checkcount + 1; return end + + checkcount = mobdebug.checkcount -- force check on the next command + + -- this is needed to check if the stack got shorter or longer. + -- unfortunately counting call/return calls is not reliable. + -- the discrepancy may happen when "pcall(load, '')" call is made + -- or when "error()" is called in a function. + -- in either case there are more "call" than "return" events reported. + -- this validation is done for every "line" event, but should be "cheap" + -- as it checks for the stack to get shorter (or longer by one call). + -- start from one level higher just in case we need to grow the stack. + -- this may happen after coroutine.resume call to a function that doesn't + -- have any other instructions to execute. it triggers three returns: + -- "return, tail return, return", which needs to be accounted for. + stack_level = stack_depth(stack_level+1) + + local caller = debug.getinfo(2, "S") + + -- grab the filename and fix it if needed + local file = lastfile + if (lastsource ~= caller.source) then + file, lastsource = caller.source, caller.source + -- technically, users can supply names that may not use '@', + -- for example when they call loadstring('...', 'filename.lua'). + -- Unfortunately, there is no reliable/quick way to figure out + -- what is the filename and what is the source code. + -- If the name doesn't start with `@`, assume it's a file name if it's all on one line. + if find(file, "^@") or not find(file, "[\r\n]") then + file = gsub(gsub(file, "^@", ""), "\\", "/") + -- normalize paths that may include up-dir or same-dir references + -- if the path starts from the up-dir or reference, + -- prepend `basedir` to generate absolute path to keep breakpoints working. + -- ignore qualified relative path (`D:../`) and UNC paths (`\\?\`) + if find(file, "^%.%./") then file = basedir..file end + if find(file, "/%.%.?/") then file = normalize_path(file) end + -- need this conversion to be applied to relative and absolute + -- file names as you may write "require 'Foo'" to + -- load "foo.lua" (on a case insensitive file system) and breakpoints + -- set on foo.lua will not work if not converted to the same case. + if iscasepreserving then file = string.lower(file) end + if find(file, "^%./") then file = sub(file, 3) end + -- remove basedir, so that breakpoints are checked properly + file = gsub(file, "^"..q(basedir), "") + -- some file systems allow newlines in file names; remove these. + file = gsub(file, "\n", ' ') + else + file = mobdebug.line(file) + end + + -- set to true if we got here; this only needs to be done once per + -- session, so do it here to at least avoid setting it for every line. + seen_hook = true + lastfile = file + end + + if is_pending(server) then handle_breakpoint(server) end + + local vars, status, res + if (watchescnt > 0) then + vars = capture_vars(1) + for index, value in pairs(watches) do + setfenv(value, vars) + local ok, fired = pcall(value) + if ok and fired then + status, res = cororesume(coro_debugger, events.WATCH, vars, file, line, index) + break -- any one watch is enough; don't check multiple times + end + end + end + + -- need to get into the "regular" debug handler, but only if there was + -- no watch that was fired. If there was a watch, handle its result. + local getin = (status == nil) and + (step_into + -- when coroutine.running() return `nil` (main thread in Lua 5.1), + -- step_over will equal 'main', so need to check for that explicitly. + or (step_over and step_over == (coroutine.running() or 'main') and stack_level <= step_level) + or has_breakpoint(file, line) + or is_pending(server)) + + if getin then + vars = vars or capture_vars(1) + step_into = false + step_over = false + status, res = cororesume(coro_debugger, events.BREAK, vars, file, line) + end + + -- handle 'stack' command that provides stack() information to the debugger + while status and res == 'stack' do + -- resume with the stack trace and variables + if vars then restore_vars(vars) end -- restore vars so they are reflected in stack values + status, res = cororesume(coro_debugger, events.STACK, stack(3), file, line) + end + + -- need to recheck once more as resume after 'stack' command may + -- return something else (for example, 'exit'), which needs to be handled + if status and res and res ~= 'stack' then + if not abort and res == "exit" then mobdebug.onexit(1, true); return end + if not abort and res == "done" then mobdebug.done(); return end + abort = res + -- only abort if safe; if not, there is another (earlier) check inside + -- debug_hook, which will abort execution at the first safe opportunity + if is_safe(stack_level) then error(abort) end + elseif not status and res then + error(res, 2) -- report any other (internal) errors back to the application + end + + if vars then restore_vars(vars) end + + -- last command requested Step Over/Out; store the current thread + if step_over == true then step_over = coroutine.running() or 'main' end + end +end + +local function stringify_results(params, status, ...) + if not status then return status, ... end -- on error report as it + + params = params or {} + if params.nocode == nil then params.nocode = true end + if params.comment == nil then params.comment = 1 end + + local t = {} + for i = 1, select('#', ...) do -- stringify each of the returned values + local ok, res = pcall(mobdebug.line, select(i, ...), params) + t[i] = ok and res or ("%q"):format(res):gsub("\010","n"):gsub("\026","\\026") + end + -- stringify table with all returned values + -- this is done to allow each returned value to be used (serialized or not) + -- intependently and to preserve "original" comments + return pcall(mobdebug.dump, t, {sparse = false}) +end + +local function isrunning() + return coro_debugger and (corostatus(coro_debugger) == 'suspended' or corostatus(coro_debugger) == 'running') +end + +-- this is a function that removes all hooks and closes the socket to +-- report back to the controller that the debugging is done. +-- the script that called `done` can still continue. +local function done() + if not (isrunning() and server) then return end + + if not jit then + for co, debugged in pairs(coroutines) do + if debugged then debug.sethook(co) end + end + end + + debug.sethook() + server:close() + + coro_debugger = nil -- to make sure isrunning() returns `false` + seen_hook = nil -- to make sure that the next start() call works + abort = nil -- to make sure that callback calls use proper "abort" value + basedir = "" -- to reset basedir in case the same module/state is reused +end + +local function debugger_loop(sev, svars, sfile, sline) + local command + local eval_env = svars or {} + local function emptyWatch () return false end + local loaded = {} + for k in pairs(package.loaded) do loaded[k] = true end + + while true do + local line, err + if mobdebug.yield and server.settimeout then server:settimeout(mobdebug.yieldtimeout) end + while true do + line, err = server:receive("*l") + if not line then + if err == "timeout" then + if mobdebug.yield then mobdebug.yield() end + elseif err == "closed" then + error("Debugger connection closed", 0) + else + error(("Unexpected socket error: %s"):format(err), 0) + end + else + -- if there is something in the pending buffer, prepend it to the line + if buf then line = buf .. line; buf = nil end + break + end + end + if server.settimeout then server:settimeout() end -- back to blocking + command = string.sub(line, string.find(line, "^[A-Z]+")) + if command == "SETB" then + local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") + if file and line then + set_breakpoint(file, tonumber(line)) + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "DELB" then + local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") + if file and line then + remove_breakpoint(file, tonumber(line)) + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "EXEC" then + -- extract any optional parameters + local params = string.match(line, "--%s*(%b{})%s*$") + local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$") + if chunk then + -- \r is optional, as it may be stripped by some luasocket versions, like the one in LOVE2d + chunk = chunk:gsub("\r?"..SAFEWS, "\n") -- convert safe whitespace back to new line + local func, res = mobdebug.loadstring(chunk) + local status + if func then + local pfunc = params and loadstring("return "..params) -- use internal function + params = pfunc and pfunc() + params = (type(params) == "table" and params or {}) + local stack = tonumber(params.stack) + -- if the requested stack frame is not the current one, then use a new capture + -- with a specific stack frame: `capture_vars(0, coro_debugee)` + local env = stack and coro_debugee and capture_vars(stack-1, coro_debugee) or eval_env + setfenv(func, env) + status, res = stringify_results(params, pcall(func, unpack(rawget(env,'...') or {}))) + end + if status then + if mobdebug.onscratch then mobdebug.onscratch(res) end + server:send("200 OK " .. tostring(#res) .. "\n") + server:send(res) + else + -- fix error if not set (for example, when loadstring is not present) + if not res then res = "Unknown error" end + server:send("401 Error in Expression " .. tostring(#res) .. "\n") + server:send(res) + end + else + server:send("400 Bad Request\n") + end + elseif command == "LOAD" then + local _, _, size, name = string.find(line, "^[A-Z]+%s+(%d+)%s+(%S.-)%s*$") + size = tonumber(size) + + if abort == nil then -- no LOAD/RELOAD allowed inside start() + if size > 0 then server:receive(size) end + if sfile and sline then + server:send("201 Started " .. sfile .. " " .. tostring(sline) .. "\n") + else + server:send("200 OK 0\n") + end + else + -- reset environment to allow required modules to load again + -- remove those packages that weren't loaded when debugger started + for k in pairs(package.loaded) do + if not loaded[k] then package.loaded[k] = nil end + end + + if size == 0 and name == '-' then -- RELOAD the current script being debugged + server:send("200 OK 0\n") + coroyield("load") + else + -- receiving 0 bytes blocks (at least in luasocket 2.0.2), so skip reading + local chunk = size == 0 and "" or server:receive(size) + if chunk then -- LOAD a new script for debugging + local func, res = mobdebug.loadstring(chunk, "@"..name) + if func then + server:send("200 OK 0\n") + debugee = func + coroyield("load") + else + server:send("401 Error in Expression " .. tostring(#res) .. "\n") + server:send(res) + end + else + server:send("400 Bad Request\n") + end + end + end + elseif command == "SETW" then + local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)%s*$") + if exp then + local func, res = mobdebug.loadstring("return(" .. exp .. ")") + if func then + watchescnt = watchescnt + 1 + local newidx = #watches + 1 + watches[newidx] = func + server:send("200 OK " .. tostring(newidx) .. "\n") + else + server:send("401 Error in Expression " .. tostring(#res) .. "\n") + server:send(res) + end + else + server:send("400 Bad Request\n") + end + elseif command == "DELW" then + local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)%s*$") + index = tonumber(index) + if index > 0 and index <= #watches then + watchescnt = watchescnt - (watches[index] ~= emptyWatch and 1 or 0) + watches[index] = emptyWatch + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "RUN" then + server:send("200 OK\n") + + local ev, vars, file, line, idx_watch = coroyield() + eval_env = vars + if ev == events.BREAK then + server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") + elseif ev == events.WATCH then + server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") + elseif ev == events.RESTART then + -- nothing to do + else + server:send("401 Error in Execution " .. tostring(#file) .. "\n") + server:send(file) + end + elseif command == "STEP" then + server:send("200 OK\n") + step_into = true + + local ev, vars, file, line, idx_watch = coroyield() + eval_env = vars + if ev == events.BREAK then + server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") + elseif ev == events.WATCH then + server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") + elseif ev == events.RESTART then + -- nothing to do + else + server:send("401 Error in Execution " .. tostring(#file) .. "\n") + server:send(file) + end + elseif command == "OVER" or command == "OUT" then + server:send("200 OK\n") + step_over = true + + -- OVER and OUT are very similar except for + -- the stack level value at which to stop + if command == "OUT" then step_level = stack_level - 1 + else step_level = stack_level end + + local ev, vars, file, line, idx_watch = coroyield() + eval_env = vars + if ev == events.BREAK then + server:send("202 Paused " .. file .. " " .. tostring(line) .. "\n") + elseif ev == events.WATCH then + server:send("203 Paused " .. file .. " " .. tostring(line) .. " " .. tostring(idx_watch) .. "\n") + elseif ev == events.RESTART then + -- nothing to do + else + server:send("401 Error in Execution " .. tostring(#file) .. "\n") + server:send(file) + end + elseif command == "BASEDIR" then + local _, _, dir = string.find(line, "^[A-Z]+%s+(.+)%s*$") + if dir then + basedir = iscasepreserving and string.lower(dir) or dir + -- reset cached source as it may change with basedir + lastsource = nil + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "SUSPEND" then + -- do nothing; it already fulfilled its role + elseif command == "DONE" then + coroyield("done") + return -- done with all the debugging + elseif command == "STACK" then + -- first check if we can execute the stack command + -- as it requires yielding back to debug_hook it cannot be executed + -- if we have not seen the hook yet as happens after start(). + -- in this case we simply return an empty result + local vars, ev = {} + if seen_hook then + ev, vars = coroyield("stack") + end + if ev and ev ~= events.STACK then + server:send("401 Error in Execution " .. tostring(#vars) .. "\n") + server:send(vars) + else + local params = string.match(line, "--%s*(%b{})%s*$") + local pfunc = params and loadstring("return "..params) -- use internal function + params = pfunc and pfunc() + params = (type(params) == "table" and params or {}) + if params.nocode == nil then params.nocode = true end + if params.sparse == nil then params.sparse = false end + -- take into account additional levels for the stack frames and data management + if tonumber(params.maxlevel) then params.maxlevel = tonumber(params.maxlevel)+4 end + + local ok, res = pcall(mobdebug.dump, vars, params) + if ok then + server:send("200 OK " .. tostring(res) .. "\n") + else + server:send("401 Error in Execution " .. tostring(#res) .. "\n") + server:send(res) + end + end + elseif command == "OUTPUT" then + local _, _, stream, mode = string.find(line, "^[A-Z]+%s+(%w+)%s+([dcr])%s*$") + if stream and mode and stream == "stdout" then + -- assign "print" in the global environment + local default = mode == 'd' + genv.print = default and iobase.print or corowrap(function() + -- wrapping into coroutine.wrap protects this function from + -- being stepped through in the debugger. + -- don't use vararg (...) as it adds a reference for its values, + -- which may affect how they are garbage collected + while true do + local tbl = {coroutine.yield()} + if mode == 'c' then iobase.print(unpack(tbl)) end + for n = 1, #tbl do + tbl[n] = select(2, pcall(mobdebug.line, tbl[n], {nocode = true, comment = false})) end + local file = table.concat(tbl, "\t").."\n" + server:send("204 Output " .. stream .. " " .. tostring(#file) .. "\n" .. file) + end + end) + if not default then genv.print() end -- "fake" print to start printing loop + server:send("200 OK\n") + else + server:send("400 Bad Request\n") + end + elseif command == "EXIT" then + server:send("200 OK\n") + coroyield("exit") + else + server:send("400 Bad Request\n") + end + end +end + +local function output(stream, data) + if server then return server:send("204 Output "..stream.." "..tostring(#data).."\n"..data) end +end + +local function connect(controller_host, controller_port) + local sock, err = socket.tcp() + if not sock then return nil, err end + + if sock.settimeout then sock:settimeout(mobdebug.connecttimeout) end + local res, err = sock:connect(controller_host, tostring(controller_port)) + if sock.settimeout then sock:settimeout() end + + if not res then return nil, err end + return sock +end + +local lasthost, lastport + +-- Starts a debug session by connecting to a controller +local function start(controller_host, controller_port) + -- only one debugging session can be run (as there is only one debug hook) + if isrunning() then return end + + lasthost = controller_host or lasthost + lastport = controller_port or lastport + + controller_host = lasthost or "localhost" + controller_port = lastport or mobdebug.port + + local err + server, err = mobdebug.connect(controller_host, controller_port) + if server then + -- correct stack depth which already has some calls on it + -- so it doesn't go into negative when those calls return + -- as this breaks subsequence checks in stack_depth(). + -- start from 16th frame, which is sufficiently large for this check. + stack_level = stack_depth(16) + + coro_debugger = corocreate(debugger_loop) + debug.sethook(debug_hook, HOOKMASK) + seen_hook = nil -- reset in case the last start() call was refused + step_into = true -- start with step command + return true + else + print(("Could not connect to %s:%s: %s") + :format(controller_host, controller_port, err or "unknown error")) + end +end + +local function controller(controller_host, controller_port, scratchpad) + -- only one debugging session can be run (as there is only one debug hook) + if isrunning() then return end + + lasthost = controller_host or lasthost + lastport = controller_port or lastport + + controller_host = lasthost or "localhost" + controller_port = lastport or mobdebug.port + + local exitonerror = not scratchpad + local err + server, err = mobdebug.connect(controller_host, controller_port) + if server then + local function report(trace, err) + local msg = err .. "\n" .. trace + server:send("401 Error in Execution " .. tostring(#msg) .. "\n") + server:send(msg) + return err + end + + seen_hook = true -- allow to accept all commands + coro_debugger = corocreate(debugger_loop) + + while true do + step_into = true -- start with step command + abort = false -- reset abort flag from the previous loop + if scratchpad then checkcount = mobdebug.checkcount end -- force suspend right away + + coro_debugee = corocreate(debugee) + debug.sethook(coro_debugee, debug_hook, HOOKMASK) + local status, err = cororesume(coro_debugee, unpack(arg or {})) + + -- was there an error or is the script done? + -- 'abort' state is allowed here; ignore it + if abort then + if tostring(abort) == 'exit' then break end + else + if status then -- no errors + if corostatus(coro_debugee) == "suspended" then + -- the script called `coroutine.yield` in the "main" thread + error("attempt to yield from the main thread", 3) + end + break -- normal execution is done + elseif err and not string.find(tostring(err), deferror) then + -- report the error back + -- err is not necessarily a string, so convert to string to report + report(debug.traceback(coro_debugee), tostring(err)) + if exitonerror then break end + -- check if the debugging is done (coro_debugger is nil) + if not coro_debugger then break end + -- resume once more to clear the response the debugger wants to send + -- need to use capture_vars(0) to capture only two (default) levels, + -- as even though there is controller() call, because of the tail call, + -- the caller may not exist for it; + -- This is not entirely safe as the user may see the local + -- variable from console, but they will be reset anyway. + -- This functionality is used when scratchpad is paused to + -- gain access to remote console to modify global variables. + local status, err = cororesume(coro_debugger, events.RESTART, capture_vars(0)) + if not status or status and err == "exit" then break end + end + end + end + else + print(("Could not connect to %s:%s: %s") + :format(controller_host, controller_port, err or "unknown error")) + return false + end + return true +end + +local function scratchpad(controller_host, controller_port) + return controller(controller_host, controller_port, true) +end + +local function loop(controller_host, controller_port) + return controller(controller_host, controller_port, false) +end + +local function on() + if not (isrunning() and server) then return end + + -- main is set to true under Lua5.2 for the "main" chunk. + -- Lua5.1 returns co as `nil` in that case. + local co, main = coroutine.running() + if main then co = nil end + if co then + coroutines[co] = true + debug.sethook(co, debug_hook, HOOKMASK) + else + if jit then coroutines.main = true end + debug.sethook(debug_hook, HOOKMASK) + end +end + +local function off() + if not (isrunning() and server) then return end + + -- main is set to true under Lua5.2 for the "main" chunk. + -- Lua5.1 returns co as `nil` in that case. + local co, main = coroutine.running() + if main then co = nil end + + -- don't remove coroutine hook under LuaJIT as there is only one (global) hook + if co then + coroutines[co] = false + if not jit then debug.sethook(co) end + else + if jit then coroutines.main = false end + if not jit then debug.sethook() end + end + + -- check if there is any thread that is still being debugged under LuaJIT; + -- if not, turn the debugging off + if jit then + local remove = true + for _, debugged in pairs(coroutines) do + if debugged then remove = false; break end + end + if remove then debug.sethook() end + end +end + +-- Handles server debugging commands +local function handle(params, client, options) + -- when `options.verbose` is not provided, use normal `print`; verbose output can be + -- disabled (`options.verbose == false`) or redirected (`options.verbose == function()...end`) + local verbose = not options or options.verbose ~= nil and options.verbose + local print = verbose and (type(verbose) == "function" and verbose or print) or function() end + local file, line, watch_idx + local _, _, command = string.find(params, "^([a-z]+)") + if command == "run" or command == "step" or command == "out" + or command == "over" or command == "exit" then + client:send(string.upper(command) .. "\n") + client:receive("*l") -- this should consume the first '200 OK' response + while true do + local done = true + local breakpoint = client:receive("*l") + if not breakpoint then + print("Program finished") + return nil, nil, false + end + local _, _, status = string.find(breakpoint, "^(%d+)") + if status == "200" then + -- don't need to do anything + elseif status == "202" then + _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") + if file and line then + print("Paused at file " .. file .. " line " .. line) + end + elseif status == "203" then + _, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+(.-)%s+(%d+)%s+(%d+)%s*$") + if file and line and watch_idx then + print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])") + end + elseif status == "204" then + local _, _, stream, size = string.find(breakpoint, "^204 Output (%w+) (%d+)$") + if stream and size then + local size = tonumber(size) + local msg = size > 0 and client:receive(size) or "" + print(msg) + if outputs[stream] then outputs[stream](msg) end + -- this was just the output, so go back reading the response + done = false + end + elseif status == "401" then + local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$") + if size then + local msg = client:receive(tonumber(size)) + print("Error in remote application: " .. msg) + return nil, nil, msg + end + else + print("Unknown error") + return nil, nil, "Debugger error: unexpected response '" .. breakpoint .. "'" + end + if done then break end + end + elseif command == "done" then + client:send(string.upper(command) .. "\n") + -- no response is expected + elseif command == "setb" or command == "asetb" then + _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") + if file and line then + -- if this is a file name, and not a file source + if not file:find('^".*"$') then + file = string.gsub(file, "\\", "/") -- convert slash + file = removebasedir(file, basedir) + end + client:send("SETB " .. file .. " " .. line .. "\n") + if command == "asetb" or client:receive("*l") == "200 OK" then + set_breakpoint(file, line) + else + print("Error: breakpoint not inserted") + end + else + print("Invalid command") + end + elseif command == "setw" then + local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") + if exp then + client:send("SETW " .. exp .. "\n") + local answer = client:receive("*l") + local _, _, watch_idx = string.find(answer, "^200 OK (%d+)%s*$") + if watch_idx then + watches[watch_idx] = exp + print("Inserted watch exp no. " .. watch_idx) + else + local _, _, size = string.find(answer, "^401 Error in Expression (%d+)$") + if size then + local err = client:receive(tonumber(size)):gsub(".-:%d+:%s*","") + print("Error: watch expression not set: " .. err) + else + print("Error: watch expression not set") + end + end + else + print("Invalid command") + end + elseif command == "delb" or command == "adelb" then + _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") + if file and line then + -- if this is a file name, and not a file source + if not file:find('^".*"$') then + file = string.gsub(file, "\\", "/") -- convert slash + file = removebasedir(file, basedir) + end + client:send("DELB " .. file .. " " .. line .. "\n") + if command == "adelb" or client:receive("*l") == "200 OK" then + remove_breakpoint(file, line) + else + print("Error: breakpoint not removed") + end + else + print("Invalid command") + end + elseif command == "delallb" then + local file, line = "*", 0 + client:send("DELB " .. file .. " " .. tostring(line) .. "\n") + if client:receive("*l") == "200 OK" then + remove_breakpoint(file, line) + else + print("Error: all breakpoints not removed") + end + elseif command == "delw" then + local _, _, index = string.find(params, "^[a-z]+%s+(%d+)%s*$") + if index then + client:send("DELW " .. index .. "\n") + if client:receive("*l") == "200 OK" then + watches[index] = nil + else + print("Error: watch expression not removed") + end + else + print("Invalid command") + end + elseif command == "delallw" then + for index, exp in pairs(watches) do + client:send("DELW " .. index .. "\n") + if client:receive("*l") == "200 OK" then + watches[index] = nil + else + print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed") + end + end + elseif command == "eval" or command == "exec" + or command == "load" or command == "loadstring" + or command == "reload" then + local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") + if exp or (command == "reload") then + if command == "eval" or command == "exec" then + exp = exp:gsub("\r?\n", "\r"..SAFEWS) -- convert new lines, so the fragment can be passed as one line + if command == "eval" then exp = "return " .. exp end + client:send("EXEC " .. exp .. "\n") + elseif command == "reload" then + client:send("LOAD 0 -\n") + elseif command == "loadstring" then + local _, _, _, file, lines = string.find(exp, "^([\"'])(.-)%1%s(.+)") + if not file then + _, _, file, lines = string.find(exp, "^(%S+)%s(.+)") + end + client:send("LOAD " .. tostring(#lines) .. " " .. file .. "\n") + client:send(lines) + else + local file = io.open(exp, "r") + if not file and pcall(require, "winapi") then + -- if file is not open and winapi is there, try with a short path; + -- this may be needed for unicode paths on windows + winapi.set_encoding(winapi.CP_UTF8) + local shortp = winapi.short_path(exp) + file = shortp and io.open(shortp, "r") + end + if not file then return nil, nil, "Cannot open file " .. exp end + -- read the file and remove the shebang line as it causes a compilation error + local lines = file:read("*all"):gsub("^#!.-\n", "\n") + file:close() + + local fname = string.gsub(exp, "\\", "/") -- convert slash + fname = removebasedir(fname, basedir) + client:send("LOAD " .. tostring(#lines) .. " " .. fname .. "\n") + if #lines > 0 then client:send(lines) end + end + while true do + local params, err = client:receive("*l") + if not params then + return nil, nil, "Debugger connection " .. (err or "error") + end + local done = true + local _, _, status, len = string.find(params, "^(%d+).-%s+(%d+)%s*$") + if status == "200" then + len = tonumber(len) + if len > 0 then + local status, res + local str = client:receive(len) + -- handle serialized table with results + local func, err = loadstring(str) + if func then + status, res = pcall(func) + if not status then err = res + elseif type(res) ~= "table" then + err = "received "..type(res).." instead of expected 'table'" + end + end + if err then + print("Error in processing results: " .. err) + return nil, nil, "Error in processing results: " .. err + end + print(unpack(res)) + return res[1], res + end + elseif status == "201" then + _, _, file, line = string.find(params, "^201 Started%s+(.-)%s+(%d+)%s*$") + elseif status == "202" or params == "200 OK" then + -- do nothing; this only happens when RE/LOAD command gets the response + -- that was for the original command that was aborted + elseif status == "204" then + local _, _, stream, size = string.find(params, "^204 Output (%w+) (%d+)$") + if stream and size then + local size = tonumber(size) + local msg = size > 0 and client:receive(size) or "" + print(msg) + if outputs[stream] then outputs[stream](msg) end + -- this was just the output, so go back reading the response + done = false + end + elseif status == "401" then + len = tonumber(len) + local res = client:receive(len) + print("Error in expression: " .. res) + return nil, nil, res + else + print("Unknown error") + return nil, nil, "Debugger error: unexpected response after EXEC/LOAD '" .. params .. "'" + end + if done then break end + end + else + print("Invalid command") + end + elseif command == "listb" then + for l, v in pairs(breakpoints) do + for f in pairs(v) do + print(f .. ": " .. l) + end + end + elseif command == "listw" then + for i, v in pairs(watches) do + print("Watch exp. " .. i .. ": " .. v) + end + elseif command == "suspend" then + client:send("SUSPEND\n") + elseif command == "stack" then + local opts = string.match(params, "^[a-z]+%s+(.+)$") + client:send("STACK" .. (opts and " "..opts or "") .."\n") + local resp = client:receive("*l") + local _, _, status, res = string.find(resp, "^(%d+)%s+%w+%s+(.+)%s*$") + if status == "200" then + local func, err = loadstring(res) + if func == nil then + print("Error in stack information: " .. err) + return nil, nil, err + end + local ok, stack = pcall(func) + if not ok then + print("Error in stack information: " .. stack) + return nil, nil, stack + end + for _,frame in ipairs(stack) do + print(mobdebug.line(frame[1], {comment = false})) + end + return stack + elseif status == "401" then + local _, _, len = string.find(resp, "%s+(%d+)%s*$") + len = tonumber(len) + local res = len > 0 and client:receive(len) or "Invalid stack information." + print("Error in expression: " .. res) + return nil, nil, res + else + print("Unknown error") + return nil, nil, "Debugger error: unexpected response after STACK" + end + elseif command == "output" then + local _, _, stream, mode = string.find(params, "^[a-z]+%s+(%w+)%s+([dcr])%s*$") + if stream and mode then + client:send("OUTPUT "..stream.." "..mode.."\n") + local resp, err = client:receive("*l") + if not resp then + print("Unknown error: "..err) + return nil, nil, "Debugger connection error: "..err + end + local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") + if status == "200" then + print("Stream "..stream.." redirected") + outputs[stream] = type(options) == 'table' and options.handler or nil + -- the client knows when she is doing, so install the handler + elseif type(options) == 'table' and options.handler then + outputs[stream] = options.handler + else + print("Unknown error") + return nil, nil, "Debugger error: can't redirect "..stream + end + else + print("Invalid command") + end + elseif command == "basedir" then + local _, _, dir = string.find(params, "^[a-z]+%s+(.+)$") + if dir then + dir = string.gsub(dir, "\\", "/") -- convert slash + if not string.find(dir, "/$") then dir = dir .. "/" end + + local remdir = dir:match("\t(.+)") + if remdir then dir = dir:gsub("/?\t.+", "/") end + basedir = dir + + client:send("BASEDIR "..(remdir or dir).."\n") + local resp, err = client:receive("*l") + if not resp then + print("Unknown error: "..err) + return nil, nil, "Debugger connection error: "..err + end + local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") + if status == "200" then + print("New base directory is " .. basedir) + else + print("Unknown error") + return nil, nil, "Debugger error: unexpected response after BASEDIR" + end + else + print(basedir) + end + elseif command == "help" then + print("setb -- sets a breakpoint") + print("delb -- removes a breakpoint") + print("delallb -- removes all breakpoints") + print("setw -- adds a new watch expression") + print("delw -- removes the watch expression at index") + print("delallw -- removes all watch expressions") + print("run -- runs until next breakpoint") + print("step -- runs until next line, stepping into function calls") + print("over -- runs until next line, stepping over function calls") + print("out -- runs until line after returning from current function") + print("listb -- lists breakpoints") + print("listw -- lists watch expressions") + print("eval -- evaluates expression on the current context and returns its value") + print("exec -- executes statement on the current context") + print("load -- loads a local file for debugging") + print("reload -- restarts the current debugging session") + print("stack -- reports stack trace") + print("output stdout -- capture and redirect io stream (default|copy|redirect)") + print("basedir [] -- sets the base path of the remote application, or shows the current one") + print("done -- stops the debugger and continues application execution") + print("exit -- exits debugger and the application") + else + local _, _, spaces = string.find(params, "^(%s*)$") + if spaces then + return nil, nil, "Empty command" + else + print("Invalid command") + return nil, nil, "Invalid command" + end + end + return file, line +end + +-- Starts debugging server +local function listen(host, port) + host = host or "*" + port = port or mobdebug.port + + local socket = require "socket" + + print("Lua Remote Debugger") + print("Run the program you wish to debug") + + local server = socket.bind(host, port) + local client = server:accept() + + client:send("STEP\n") + client:receive("*l") + + local breakpoint = client:receive("*l") + local _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") + if file and line then + print("Paused at file " .. file ) + print("Type 'help' for commands") + else + local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)%s*$") + if size then + print("Error in remote application: ") + print(client:receive(size)) + end + end + + while true do + io.write("> ") + local file, _, err = handle(io.read("*line"), client) + if not file and err == false then break end -- completed debugging + end + + client:close() +end + +local cocreate +local function coro() + if cocreate then return end -- only set once + cocreate = cocreate or coroutine.create + coroutine.create = function(f, ...) + return cocreate(function(...) + mobdebug.on() + return f(...) + end, ...) + end +end + +local moconew +local function moai() + if moconew then return end -- only set once + moconew = moconew or (MOAICoroutine and MOAICoroutine.new) + if not moconew then return end + MOAICoroutine.new = function(...) + local thread = moconew(...) + -- need to support both thread.run and getmetatable(thread).run, which + -- was used in earlier MOAI versions + local mt = thread.run and thread or getmetatable(thread) + local patched = mt.run + mt.run = function(self, f, ...) + return patched(self, function(...) + mobdebug.on() + return f(...) + end, ...) + end + return thread + end +end + +-- make public functions available +mobdebug.setbreakpoint = set_breakpoint +mobdebug.removebreakpoint = remove_breakpoint +mobdebug.listen = listen +mobdebug.loop = loop +mobdebug.scratchpad = scratchpad +mobdebug.handle = handle +mobdebug.connect = connect +mobdebug.start = start +mobdebug.on = on +mobdebug.off = off +mobdebug.moai = moai +mobdebug.coro = coro +mobdebug.done = done +mobdebug.pause = function() step_into = true end +mobdebug.yield = nil -- callback +mobdebug.output = output +mobdebug.onexit = os and os.exit or done +mobdebug.onscratch = nil -- callback +mobdebug.basedir = function(b) if b then basedir = b end return basedir end + +return mobdebug diff --git a/engine/EngineResources/scripts/3rdparty/smtp.lua b/engine/EngineResources/scripts/3rdparty/smtp.lua new file mode 100644 index 00000000..c26ce44f --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/smtp.lua @@ -0,0 +1,256 @@ +----------------------------------------------------------------------------- +-- SMTP client support for the Lua language. +-- LuaSocket toolkit. +-- Author: Diego Nehab +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local coroutine = require("coroutine") +local string = require("string") +local math = require("math") +local os = require("os") +local socket = require("socket") +local tp = require("socket.tp") +local ltn12 = require("ltn12") +local headers = require("socket.headers") +local mime = require("mime") + +socket.smtp = {} +local _M = socket.smtp + +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +-- timeout for connection +_M.TIMEOUT = 60 +-- default server used to send e-mails +_M.SERVER = "localhost" +-- default port +_M.PORT = 25 +-- domain used in HELO command and default sendmail +-- If we are under a CGI, try to get from environment +_M.DOMAIN = os.getenv("SERVER_NAME") or "localhost" +-- default time zone (means we don't know) +_M.ZONE = "-0000" + +--------------------------------------------------------------------------- +-- Low level SMTP API +----------------------------------------------------------------------------- +local metat = { __index = {} } + +function metat.__index:greet(domain) + self.try(self.tp:check("2..")) + self.try(self.tp:command("EHLO", domain or _M.DOMAIN)) + return socket.skip(1, self.try(self.tp:check("2.."))) +end + +function metat.__index:mail(from) + self.try(self.tp:command("MAIL", "FROM:" .. from)) + return self.try(self.tp:check("2..")) +end + +function metat.__index:rcpt(to) + self.try(self.tp:command("RCPT", "TO:" .. to)) + return self.try(self.tp:check("2..")) +end + +function metat.__index:data(src, step) + self.try(self.tp:command("DATA")) + self.try(self.tp:check("3..")) + self.try(self.tp:source(src, step)) + self.try(self.tp:send("\r\n.\r\n")) + return self.try(self.tp:check("2..")) +end + +function metat.__index:quit() + self.try(self.tp:command("QUIT")) + return self.try(self.tp:check("2..")) +end + +function metat.__index:close() + return self.tp:close() +end + +function metat.__index:login(user, password) + self.try(self.tp:command("AUTH", "LOGIN")) + self.try(self.tp:check("3..")) + self.try(self.tp:send(mime.b64(user) .. "\r\n")) + self.try(self.tp:check("3..")) + self.try(self.tp:send(mime.b64(password) .. "\r\n")) + return self.try(self.tp:check("2..")) +end + +function metat.__index:plain(user, password) + local auth = "PLAIN " .. mime.b64("\0" .. user .. "\0" .. password) + self.try(self.tp:command("AUTH", auth)) + return self.try(self.tp:check("2..")) +end + +function metat.__index:auth(user, password, ext) + if not user or not password then return 1 end + if string.find(ext, "AUTH[^\n]+LOGIN") then + return self:login(user, password) + elseif string.find(ext, "AUTH[^\n]+PLAIN") then + return self:plain(user, password) + else + self.try(nil, "authentication not supported") + end +end + +-- send message or throw an exception +function metat.__index:send(mailt) + self:mail(mailt.from) + if base.type(mailt.rcpt) == "table" then + for i,v in base.ipairs(mailt.rcpt) do + self:rcpt(v) + end + else + self:rcpt(mailt.rcpt) + end + self:data(ltn12.source.chain(mailt.source, mime.stuff()), mailt.step) +end + +function _M.open(server, port, create) + local tp = socket.try(tp.connect(server or _M.SERVER, port or _M.PORT, + _M.TIMEOUT, create)) + local s = base.setmetatable({tp = tp}, metat) + -- make sure tp is closed if we get an exception + s.try = socket.newtry(function() + s:close() + end) + return s +end + +-- convert headers to lowercase +local function lower_headers(headers) + local lower = {} + for i,v in base.pairs(headers or lower) do + lower[string.lower(i)] = v + end + return lower +end + +--------------------------------------------------------------------------- +-- Multipart message source +----------------------------------------------------------------------------- +-- returns a hopefully unique mime boundary +local seqno = 0 +local function newboundary() + seqno = seqno + 1 + return string.format('%s%05d==%05u', os.date('%d%m%Y%H%M%S'), + math.random(0, 99999), seqno) +end + +-- send_message forward declaration +local send_message + +-- yield the headers all at once, it's faster +local function send_headers(tosend) + local canonic = headers.canonic + local h = "\r\n" + for f,v in base.pairs(tosend) do + h = (canonic[f] or f) .. ': ' .. v .. "\r\n" .. h + end + coroutine.yield(h) +end + +-- yield multipart message body from a multipart message table +local function send_multipart(mesgt) + -- make sure we have our boundary and send headers + local bd = newboundary() + local headers = lower_headers(mesgt.headers or {}) + headers['content-type'] = headers['content-type'] or 'multipart/mixed' + headers['content-type'] = headers['content-type'] .. + '; boundary="' .. bd .. '"' + send_headers(headers) + -- send preamble + if mesgt.body.preamble then + coroutine.yield(mesgt.body.preamble) + coroutine.yield("\r\n") + end + -- send each part separated by a boundary + for i, m in base.ipairs(mesgt.body) do + coroutine.yield("\r\n--" .. bd .. "\r\n") + send_message(m) + end + -- send last boundary + coroutine.yield("\r\n--" .. bd .. "--\r\n\r\n") + -- send epilogue + if mesgt.body.epilogue then + coroutine.yield(mesgt.body.epilogue) + coroutine.yield("\r\n") + end +end + +-- yield message body from a source +local function send_source(mesgt) + -- make sure we have a content-type + local headers = lower_headers(mesgt.headers or {}) + headers['content-type'] = headers['content-type'] or + 'text/plain; charset="iso-8859-1"' + send_headers(headers) + -- send body from source + while true do + local chunk, err = mesgt.body() + if err then coroutine.yield(nil, err) + elseif chunk then coroutine.yield(chunk) + else break end + end +end + +-- yield message body from a string +local function send_string(mesgt) + -- make sure we have a content-type + local headers = lower_headers(mesgt.headers or {}) + headers['content-type'] = headers['content-type'] or + 'text/plain; charset="iso-8859-1"' + send_headers(headers) + -- send body from string + coroutine.yield(mesgt.body) +end + +-- message source +function send_message(mesgt) + if base.type(mesgt.body) == "table" then send_multipart(mesgt) + elseif base.type(mesgt.body) == "function" then send_source(mesgt) + else send_string(mesgt) end +end + +-- set defaul headers +local function adjust_headers(mesgt) + local lower = lower_headers(mesgt.headers) + lower["date"] = lower["date"] or + os.date("!%a, %d %b %Y %H:%M:%S ") .. (mesgt.zone or _M.ZONE) + lower["x-mailer"] = lower["x-mailer"] or socket._VERSION + -- this can't be overridden + lower["mime-version"] = "1.0" + return lower +end + +function _M.message(mesgt) + mesgt.headers = adjust_headers(mesgt) + -- create and return message source + local co = coroutine.create(function() send_message(mesgt) end) + return function() + local ret, a, b = coroutine.resume(co) + if ret then return a, b + else return nil, a end + end +end + +--------------------------------------------------------------------------- +-- High level SMTP API +----------------------------------------------------------------------------- +_M.send = socket.protect(function(mailt) + local s = _M.open(mailt.server, mailt.port, mailt.create) + local ext = s:greet(mailt.domain) + s:auth(mailt.user, mailt.password, ext) + s:send(mailt) + s:quit() + return s:close() +end) + +return _M diff --git a/engine/EngineResources/scripts/3rdparty/socket.lua b/engine/EngineResources/scripts/3rdparty/socket.lua new file mode 100644 index 00000000..d1c0b164 --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/socket.lua @@ -0,0 +1,149 @@ +----------------------------------------------------------------------------- +-- LuaSocket helper module +-- Author: Diego Nehab +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local string = require("string") +local math = require("math") +local socket = require("socket.core") + +local _M = socket + +----------------------------------------------------------------------------- +-- Exported auxiliar functions +----------------------------------------------------------------------------- +function _M.connect4(address, port, laddress, lport) + return socket.connect(address, port, laddress, lport, "inet") +end + +function _M.connect6(address, port, laddress, lport) + return socket.connect(address, port, laddress, lport, "inet6") +end + +function _M.bind(host, port, backlog) + if host == "*" then host = "0.0.0.0" end + local addrinfo, err = socket.dns.getaddrinfo(host); + if not addrinfo then return nil, err end + local sock, res + err = "no info on address" + for i, alt in base.ipairs(addrinfo) do + if alt.family == "inet" then + sock, err = socket.tcp4() + else + sock, err = socket.tcp6() + end + if not sock then return nil, err end + sock:setoption("reuseaddr", true) + res, err = sock:bind(alt.addr, port) + if not res then + sock:close() + else + res, err = sock:listen(backlog) + if not res then + sock:close() + else + return sock + end + end + end + return nil, err +end + +_M.try = _M.newtry() + +function _M.choose(table) + return function(name, opt1, opt2) + if base.type(name) ~= "string" then + name, opt1, opt2 = "default", name, opt1 + end + local f = table[name or "nil"] + if not f then base.error("unknown key (".. base.tostring(name) ..")", 3) + else return f(opt1, opt2) end + end +end + +----------------------------------------------------------------------------- +-- Socket sources and sinks, conforming to LTN12 +----------------------------------------------------------------------------- +-- create namespaces inside LuaSocket namespace +local sourcet, sinkt = {}, {} +_M.sourcet = sourcet +_M.sinkt = sinkt + +_M.BLOCKSIZE = 2048 + +sinkt["close-when-done"] = function(sock) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function(self, chunk, err) + if not chunk then + sock:close() + return 1 + else return sock:send(chunk) end + end + }) +end + +sinkt["keep-open"] = function(sock) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function(self, chunk, err) + if chunk then return sock:send(chunk) + else return 1 end + end + }) +end + +sinkt["default"] = sinkt["keep-open"] + +_M.sink = _M.choose(sinkt) + +sourcet["by-length"] = function(sock, length) + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function() + if length <= 0 then return nil end + local size = math.min(socket.BLOCKSIZE, length) + local chunk, err = sock:receive(size) + if err then return nil, err end + length = length - string.len(chunk) + return chunk + end + }) +end + +sourcet["until-closed"] = function(sock) + local done + return base.setmetatable({ + getfd = function() return sock:getfd() end, + dirty = function() return sock:dirty() end + }, { + __call = function() + if done then return nil end + local chunk, err, partial = sock:receive(socket.BLOCKSIZE) + if not err then return chunk + elseif err == "closed" then + sock:close() + done = 1 + return partial + else return nil, err end + end + }) +end + + +sourcet["default"] = sourcet["until-closed"] + +_M.source = _M.choose(sourcet) + +return _M diff --git a/engine/EngineResources/scripts/3rdparty/tp.lua b/engine/EngineResources/scripts/3rdparty/tp.lua new file mode 100644 index 00000000..b8ebc56d --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/tp.lua @@ -0,0 +1,134 @@ +----------------------------------------------------------------------------- +-- Unified SMTP/FTP subsystem +-- LuaSocket toolkit. +-- Author: Diego Nehab +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module and import dependencies +----------------------------------------------------------------------------- +local base = _G +local string = require("string") +local socket = require("socket") +local ltn12 = require("ltn12") + +socket.tp = {} +local _M = socket.tp + +----------------------------------------------------------------------------- +-- Program constants +----------------------------------------------------------------------------- +_M.TIMEOUT = 60 + +----------------------------------------------------------------------------- +-- Implementation +----------------------------------------------------------------------------- +-- gets server reply (works for SMTP and FTP) +local function get_reply(c) + local code, current, sep + local line, err = c:receive() + local reply = line + if err then return nil, err end + code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) + if not code then return nil, "invalid server reply" end + if sep == "-" then -- reply is multiline + repeat + line, err = c:receive() + if err then return nil, err end + current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) + reply = reply .. "\n" .. line + -- reply ends with same code + until code == current and sep == " " + end + return code, reply +end + +-- metatable for sock object +local metat = { __index = {} } + +function metat.__index:getpeername() + return self.c:getpeername() +end + +function metat.__index:getsockname() + return self.c:getpeername() +end + +function metat.__index:check(ok) + local code, reply = get_reply(self.c) + if not code then return nil, reply end + if base.type(ok) ~= "function" then + if base.type(ok) == "table" then + for i, v in base.ipairs(ok) do + if string.find(code, v) then + return base.tonumber(code), reply + end + end + return nil, reply + else + if string.find(code, ok) then return base.tonumber(code), reply + else return nil, reply end + end + else return ok(base.tonumber(code), reply) end +end + +function metat.__index:command(cmd, arg) + cmd = string.upper(cmd) + if arg then + return self.c:send(cmd .. " " .. arg.. "\r\n") + else + return self.c:send(cmd .. "\r\n") + end +end + +function metat.__index:sink(snk, pat) + local chunk, err = self.c:receive(pat) + return snk(chunk, err) +end + +function metat.__index:send(data) + return self.c:send(data) +end + +function metat.__index:receive(pat) + return self.c:receive(pat) +end + +function metat.__index:getfd() + return self.c:getfd() +end + +function metat.__index:dirty() + return self.c:dirty() +end + +function metat.__index:getcontrol() + return self.c +end + +function metat.__index:source(source, step) + local sink = socket.sink("keep-open", self.c) + local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) + return ret, err +end + +-- closes the underlying c +function metat.__index:close() + self.c:close() + return 1 +end + +-- connect with server and return c object +function _M.connect(host, port, timeout, create) + local c, e = (create or socket.tcp)() + if not c then return nil, e end + c:settimeout(timeout or _M.TIMEOUT) + local r, e = c:connect(host, port) + if not r then + c:close() + return nil, e + end + return base.setmetatable({c = c}, metat) +end + +return _M diff --git a/engine/EngineResources/scripts/3rdparty/url.lua b/engine/EngineResources/scripts/3rdparty/url.lua new file mode 100644 index 00000000..aef16984 --- /dev/null +++ b/engine/EngineResources/scripts/3rdparty/url.lua @@ -0,0 +1,331 @@ +----------------------------------------------------------------------------- +-- URI parsing, composition and relative URL resolution +-- LuaSocket toolkit. +-- Author: Diego Nehab +----------------------------------------------------------------------------- + +----------------------------------------------------------------------------- +-- Declare module +----------------------------------------------------------------------------- +local string = require("string") +local base = _G +local table = require("table") +local socket = require("socket") + +socket.url = {} +local _M = socket.url + +----------------------------------------------------------------------------- +-- Module version +----------------------------------------------------------------------------- +_M._VERSION = "URL 1.0.3" + +----------------------------------------------------------------------------- +-- Encodes a string into its escaped hexadecimal representation +-- Input +-- s: binary string to be encoded +-- Returns +-- escaped representation of string binary +----------------------------------------------------------------------------- +function _M.escape(s) + return (string.gsub(s, "([^A-Za-z0-9_])", function(c) + return string.format("%%%02x", string.byte(c)) + end)) +end + +----------------------------------------------------------------------------- +-- Protects a path segment, to prevent it from interfering with the +-- url parsing. +-- Input +-- s: binary string to be encoded +-- Returns +-- escaped representation of string binary +----------------------------------------------------------------------------- +local function make_set(t) + local s = {} + for i,v in base.ipairs(t) do + s[t[i]] = 1 + end + return s +end + +-- these are allowed within a path segment, along with alphanum +-- other characters must be escaped +local segment_set = make_set { + "-", "_", ".", "!", "~", "*", "'", "(", + ")", ":", "@", "&", "=", "+", "$", ",", +} + +local function protect_segment(s) + return string.gsub(s, "([^A-Za-z0-9_])", function (c) + if segment_set[c] then return c + else return string.format("%%%02X", string.byte(c)) end + end) +end + +----------------------------------------------------------------------------- +-- Unencodes a escaped hexadecimal string into its binary representation +-- Input +-- s: escaped hexadecimal string to be unencoded +-- Returns +-- unescaped binary representation of escaped hexadecimal binary +----------------------------------------------------------------------------- +function _M.unescape(s) + return (string.gsub(s, "%%(%x%x)", function(hex) + return string.char(base.tonumber(hex, 16)) + end)) +end + +----------------------------------------------------------------------------- +-- Removes '..' and '.' components appropriately from a path. +-- Input +-- path +-- Returns +-- dot-normalized path +local function remove_dot_components(path) + local marker = string.char(1) + repeat + local was = path + path = path:gsub('//', '/'..marker..'/', 1) + until path == was + repeat + local was = path + path = path:gsub('/%./', '/', 1) + until path == was + repeat + local was = path + path = path:gsub('[^/]+/%.%./([^/]+)', '%1', 1) + until path == was + path = path:gsub('[^/]+/%.%./*$', '') + path = path:gsub('/%.%.$', '/') + path = path:gsub('/%.$', '/') + path = path:gsub('^/%.%./', '/') + path = path:gsub(marker, '') + return path +end + +----------------------------------------------------------------------------- +-- Builds a path from a base path and a relative path +-- Input +-- base_path +-- relative_path +-- Returns +-- corresponding absolute path +----------------------------------------------------------------------------- +local function absolute_path(base_path, relative_path) + if string.sub(relative_path, 1, 1) == "/" then + return remove_dot_components(relative_path) end + base_path = base_path:gsub("[^/]*$", "") + if not base_path:find'/$' then base_path = base_path .. '/' end + local path = base_path .. relative_path + path = remove_dot_components(path) + return path +end + +----------------------------------------------------------------------------- +-- Parses a url and returns a table with all its parts according to RFC 2396 +-- The following grammar describes the names given to the URL parts +-- ::= :///;?# +-- ::= @: +-- ::= [:] +-- :: = {/} +-- Input +-- url: uniform resource locator of request +-- default: table with default values for each field +-- Returns +-- table with the following fields, where RFC naming conventions have +-- been preserved: +-- scheme, authority, userinfo, user, password, host, port, +-- path, params, query, fragment +-- Obs: +-- the leading '/' in {/} is considered part of +----------------------------------------------------------------------------- +function _M.parse(url, default) + -- initialize default parameters + local parsed = {} + for i,v in base.pairs(default or parsed) do parsed[i] = v end + -- empty url is parsed to nil + if not url or url == "" then return nil, "invalid url" end + -- remove whitespace + -- url = string.gsub(url, "%s", "") + -- get scheme + url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", + function(s) parsed.scheme = s; return "" end) + -- get authority + url = string.gsub(url, "^//([^/%?#]*)", function(n) + parsed.authority = n + return "" + end) + -- get fragment + url = string.gsub(url, "#(.*)$", function(f) + parsed.fragment = f + return "" + end) + -- get query string + url = string.gsub(url, "%?(.*)", function(q) + parsed.query = q + return "" + end) + -- get params + url = string.gsub(url, "%;(.*)", function(p) + parsed.params = p + return "" + end) + -- path is whatever was left + if url ~= "" then parsed.path = url end + local authority = parsed.authority + if not authority then return parsed end + authority = string.gsub(authority,"^([^@]*)@", + function(u) parsed.userinfo = u; return "" end) + authority = string.gsub(authority, ":([^:%]]*)$", + function(p) parsed.port = p; return "" end) + if authority ~= "" then + -- IPv6? + parsed.host = string.match(authority, "^%[(.+)%]$") or authority + end + local userinfo = parsed.userinfo + if not userinfo then return parsed end + userinfo = string.gsub(userinfo, ":([^:]*)$", + function(p) parsed.password = p; return "" end) + parsed.user = userinfo + return parsed +end + +----------------------------------------------------------------------------- +-- Rebuilds a parsed URL from its components. +-- Components are protected if any reserved or unallowed characters are found +-- Input +-- parsed: parsed URL, as returned by parse +-- Returns +-- a stringing with the corresponding URL +----------------------------------------------------------------------------- +function _M.build(parsed) + --local ppath = _M.parse_path(parsed.path or "") + --local url = _M.build_path(ppath) + local url = parsed.path or "" + if parsed.params then url = url .. ";" .. parsed.params end + if parsed.query then url = url .. "?" .. parsed.query end + local authority = parsed.authority + if parsed.host then + authority = parsed.host + if string.find(authority, ":") then -- IPv6? + authority = "[" .. authority .. "]" + end + if parsed.port then authority = authority .. ":" .. base.tostring(parsed.port) end + local userinfo = parsed.userinfo + if parsed.user then + userinfo = parsed.user + if parsed.password then + userinfo = userinfo .. ":" .. parsed.password + end + end + if userinfo then authority = userinfo .. "@" .. authority end + end + if authority then url = "//" .. authority .. url end + if parsed.scheme then url = parsed.scheme .. ":" .. url end + if parsed.fragment then url = url .. "#" .. parsed.fragment end + -- url = string.gsub(url, "%s", "") + return url +end + +----------------------------------------------------------------------------- +-- Builds a absolute URL from a base and a relative URL according to RFC 2396 +-- Input +-- base_url +-- relative_url +-- Returns +-- corresponding absolute url +----------------------------------------------------------------------------- +function _M.absolute(base_url, relative_url) + local base_parsed + if base.type(base_url) == "table" then + base_parsed = base_url + base_url = _M.build(base_parsed) + else + base_parsed = _M.parse(base_url) + end + local result + local relative_parsed = _M.parse(relative_url) + if not base_parsed then + result = relative_url + elseif not relative_parsed then + result = base_url + elseif relative_parsed.scheme then + result = relative_url + else + relative_parsed.scheme = base_parsed.scheme + if not relative_parsed.authority then + relative_parsed.authority = base_parsed.authority + if not relative_parsed.path then + relative_parsed.path = base_parsed.path + if not relative_parsed.params then + relative_parsed.params = base_parsed.params + if not relative_parsed.query then + relative_parsed.query = base_parsed.query + end + end + else + relative_parsed.path = absolute_path(base_parsed.path or "", + relative_parsed.path) + end + end + result = _M.build(relative_parsed) + end + return remove_dot_components(result) +end + +----------------------------------------------------------------------------- +-- Breaks a path into its segments, unescaping the segments +-- Input +-- path +-- Returns +-- segment: a table with one entry per segment +----------------------------------------------------------------------------- +function _M.parse_path(path) + local parsed = {} + path = path or "" + --path = string.gsub(path, "%s", "") + string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) + for i = 1, #parsed do + parsed[i] = _M.unescape(parsed[i]) + end + if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end + if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end + return parsed +end + +----------------------------------------------------------------------------- +-- Builds a path component from its segments, escaping protected characters. +-- Input +-- parsed: path segments +-- unsafe: if true, segments are not protected before path is built +-- Returns +-- path: corresponding path stringing +----------------------------------------------------------------------------- +function _M.build_path(parsed, unsafe) + local path = "" + local n = #parsed + if unsafe then + for i = 1, n-1 do + path = path .. parsed[i] + path = path .. "/" + end + if n > 0 then + path = path .. parsed[n] + if parsed.is_directory then path = path .. "/" end + end + else + for i = 1, n-1 do + path = path .. protect_segment(parsed[i]) + path = path .. "/" + end + if n > 0 then + path = path .. protect_segment(parsed[n]) + if parsed.is_directory then path = path .. "/" end + end + end + if parsed.is_absolute then path = "/" .. path end + return path +end + +return _M diff --git a/engine/EngineResources/scripts/definitions/ImGui.lua b/engine/EngineResources/scripts/definitions/ImGui.lua new file mode 100644 index 00000000..1d2a0dc9 --- /dev/null +++ b/engine/EngineResources/scripts/definitions/ImGui.lua @@ -0,0 +1,203 @@ +---@meta + +---@class ImGui +ImGui = {} + +---@param label string +---@return boolean +function ImGui.Begin(label) end + +function ImGui.End() end + +---@param text string +function ImGui.Text(text) end + +---@param text string +function ImGui.Button(text) end + +---@param text string +---@return boolean +function ImGui.SmallButton(text) end + +function ImGui.SameLine() end + +---@param value number +function ImGui.SetCursorPosX(value) end + +---@return number +function ImGui.GetCursorPosX() end + +---@param value number +function ImGui.SetCursorPosY(value) end + +---@return number +function ImGui.GetCursorPosY() end + +---@param x number +---@param y number +function ImGui.SetCursorPos(x, y) end + +---@return number, number +function ImGui.GetCursorPos() end + +---@param x number +---@param y number +---@param w number +---@param h number +function ImGui.SetWindowSize(x, y, w, h) end + +---@param x number +---@param y number +---@param w number +---@param h number +function ImGui.SetNextWindowSize(x, y, w, h) end + +---@param x number +---@param y number +function ImGui.SetWindowPos(x, y) end + +---@param x number +---@param y number +function ImGui.SetNextWindowPos(x, y) end + +---@param value number +function ImGui.PushStyleVar(value) end + +function ImGui.PopStyleVar() end + +function ImGui.BeginTabBar() end + +function ImGui.EndTabBar() end + +---@param label string +---@return boolean +function ImGui.BeginTabItem(label) end + +function ImGui.EndTabItem() end + +---@param text string +function ImGui.TextWrapped(text) end + +---@param label string +---@param items table +---@param currentItemIndex number +---@param popupMaxHeightInItems number +function ImGui.Combo(label, items, currentItemIndex, popupMaxHeightInItems) end + +---@param label string +---@param items table +---@param currentItemIndex number +---@return boolean +function ImGui.ListBox(label, items, currentItemIndex) end + +---@param label string +---@param width number +---@param height number +---@param border boolean +function ImGui.BeginChild(label, width, height, border) end + +function ImGui.EndChild() end + +function ImGui.Columns() end + +---@param text string +function ImGui.TextDisabled(text) end + +---@param text string +function ImGui.TextColored(text) end + +function ImGui.Bullet() end + +---@param text string +function ImGui.Selectable(text) end + +---@param label string +---@param value boolean +function ImGui.Checkbox(label, value) end + +---@param label string +---@param value number +---@param min number +---@param max number +function ImGui.SliderFloat(label, value, min, max) end + +---@param label string +---@param value number +---@param min number +---@param max number +function ImGui.SliderInt(label, value, min, max) end + +---@param label string +---@param values table +---@param currentItemIndex number +function ImGui.ListBox(label, values, currentItemIndex) end + +---@param label string +---@param items table +---@param currentItemIndex number +---@return boolean +function ImGui.BeginCombo(label, items, currentItemIndex) end + +function ImGui.EndCombo() end + +---@param label string +function ImGui.InputText(label) end + +function ImGui.TreePop() end + +function ImGui.PushStyleColor() end + +function ImGui.PopStyleColor() end + +---@param text string +function ImGui.SetTooltip(text) end + +function ImGui.BeginTooltip() end + +function ImGui.EndTooltip() end + +---@param text string +function ImGui.PlotLines(text) end + +---@param text string +function ImGui.PlotHistogram(text) end + +---@param label string +---@param defaultValue string +---@param maxLength number +function ImGui.InputText(label, defaultValue, maxLength) end + +---@param label string +---@param value number +function ImGui.DragFloat(label, value) end + +---@param label string +---@param value number +function ImGui.DragInt(label, value) end + +---@param label string +---@param text string +---@return boolean +function ImGui.TreeNode(label, text) end + +function ImGui.TreePush() end + +function ImGui.TreePop() end + +function ImGui.PushItemWidth() end + +function ImGui.PopItemWidth() end + +---@param label string +---@param value number +---@param step number +---@param stepFast number +---@param format string +---@return boolean +function ImGui.InputFloat(label, value, step, stepFast, format) end + +---@param label string +---@param isOpen boolean +---@param text string +---@return boolean +function ImGui.TreeNode(label, isOpen, text) end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/jleObject.lua b/engine/EngineResources/scripts/definitions/jleObject.lua new file mode 100644 index 00000000..4ac8d1ca --- /dev/null +++ b/engine/EngineResources/scripts/definitions/jleObject.lua @@ -0,0 +1,31 @@ +---@meta + +---@class jleObject +jleObject = {} + +---@return string +function jleObject.name() end + +---@return jleTransform +function jleObject.transform() end + +---@param componentName string +---@return boolean +function jleObject.addComponent(componentName) end + +---@return jleObject +function jleObject.duplicate() end + +function jleObject.destroy() end + +---@return boolean +function jleObject.pendingKill() end + +---@return boolean +function jleObject.isStarted() end + +---@return number +function jleObject.instanceID() end + +---@return jleScene +function jleObject.scene() end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/jlePath.lua b/engine/EngineResources/scripts/definitions/jlePath.lua new file mode 100644 index 00000000..a232ecc5 --- /dev/null +++ b/engine/EngineResources/scripts/definitions/jlePath.lua @@ -0,0 +1,37 @@ +---@meta + +---@class jlePath +jlePath = {} + +---@return jlePath +function jlePath.new() end + +---@param path string +---@return jlePath +function jlePath.new(path) end + +---@param path string +---@param isVirtual boolean +---@return jlePath +function jlePath.new(path, isVirtual) end + +---@return string +function jlePath.getPathVirtualDrive() end + +---@return string +function jlePath.getVirtualPathConst() end + +---@return string +function jlePath.getRealPathConst() end + +---@return boolean +function jlePath.isEmpty() end + +---@return string +function jlePath.getFileEnding() end + +---@return string +function jlePath.getFileNameNoEnding() end + +---@return string +function jlePath.__tostring() end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/jleScene.lua b/engine/EngineResources/scripts/definitions/jleScene.lua new file mode 100644 index 00000000..d4366f33 --- /dev/null +++ b/engine/EngineResources/scripts/definitions/jleScene.lua @@ -0,0 +1,15 @@ +---@meta + +---@class jleScene +jleScene = {} + +---@return string +function jleScene.name() end + +---@return jleObject +function jleScene.spawnObjectWithName() end + +function jleScene.destroy() end + +---@return table +function jleScene.objects() end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/jleTransform.lua b/engine/EngineResources/scripts/definitions/jleTransform.lua new file mode 100644 index 00000000..09a5fab7 --- /dev/null +++ b/engine/EngineResources/scripts/definitions/jleTransform.lua @@ -0,0 +1,31 @@ +---@meta + +---@class jleTransform +jleTransform = {} + +---@return jleTransform +function jleTransform.new() end + +---@return vec3 +function jleTransform.getLocalPosition() end + +---@return vec3 +function jleTransform.getWorldPosition() end + +---@param pos vec3 +function jleTransform.setLocalPosition(pos) end + +---@param pos vec3 +function jleTransform.setWorldPosition(pos) end + +---@return mat4 +function jleTransform.getWorldMatrix() end + +---@return mat4 +function jleTransform.getLocalMatrix() end + +---@return vec3 +function jleTransform.getForward() end + +---@param mat mat4 +function jleTransform.setWorldMatrix(mat) end diff --git a/engine/EngineResources/scripts/definitions/mat2.lua b/engine/EngineResources/scripts/definitions/mat2.lua new file mode 100644 index 00000000..b43b62df --- /dev/null +++ b/engine/EngineResources/scripts/definitions/mat2.lua @@ -0,0 +1,44 @@ +---@meta + +---@class mat2 +mat2 = {} + +---@return mat2 +function mat2.new() end + +---@param m1 mat2 +---@param m2 mat2 +---@return mat2 +function mat2.__mul(m1, m2) end + +---@param m1 mat2 +---@param f number +---@return mat2 +function mat2.__mul(m1, f) end + +---@param f number +---@param m1 mat2 +---@return mat2 +function mat2.__mul(f, m1) end + +---@param m1 mat2 +---@param m2 mat2 +---@return mat2 +function mat2.__add(m1, m2) end + +---@param m1 mat2 +---@param m2 mat2 +---@return mat2 +function mat2.__sub(m1, m2) end + +---@param m mat2 +---@return string +function mat2.__tostring(m) end + +---@param m mat2 +---@return mat2 +function mat2.inverse(m) end + +---@param m mat2 +---@return mat2 +function mat2.transpose(m) end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/mat3.lua b/engine/EngineResources/scripts/definitions/mat3.lua new file mode 100644 index 00000000..abdf20ac --- /dev/null +++ b/engine/EngineResources/scripts/definitions/mat3.lua @@ -0,0 +1,44 @@ +---@meta + +---@class mat3 +mat3 = {} + +---@return mat3 +function mat3.new() end + +---@param m1 mat3 +---@param m2 mat3 +---@return mat3 +function mat3.__mul(m1, m2) end + +---@param m1 mat3 +---@param f number +---@return mat3 +function mat3.__mul(m1, f) end + +---@param f number +---@param m1 mat3 +---@return mat3 +function mat3.__mul(f, m1) end + +---@param m1 mat3 +---@param m2 mat3 +---@return mat3 +function mat3.__add(m1, m2) end + +---@param m1 mat3 +---@param m2 mat3 +---@return mat3 +function mat3.__sub(m1, m2) end + +---@param m mat3 +---@return string +function mat3.__tostring(m) end + +---@param m mat3 +---@return mat3 +function mat3.inverse(m) end + +---@param m mat3 +---@return mat3 +function mat3.transpose(m) end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/mat4.lua b/engine/EngineResources/scripts/definitions/mat4.lua new file mode 100644 index 00000000..ad2dbed2 --- /dev/null +++ b/engine/EngineResources/scripts/definitions/mat4.lua @@ -0,0 +1,60 @@ +---@meta + +---@class mat4 +mat4 = {} + +---@return mat4 +function mat4.new() end + +---@param m1 mat4 +---@param m2 mat4 +---@return mat4 +function mat4.__mul(m1, m2) end + +---@param m1 mat4 +---@param f number +---@return mat4 +function mat4.__mul(m1, f) end + +---@param f number +---@param m1 mat4 +---@return mat4 +function mat4.__mul(f, m1) end + +---@param m1 mat4 +---@param m2 mat4 +---@return mat4 +function mat4.__add(m1, m2) end + +---@param m1 mat4 +---@param m2 mat4 +---@return mat4 +function mat4.__sub(m1, m2) end + +---@param m mat4 +---@return string +function mat4.__tostring(m) end + +---@param m mat4 +---@return mat4 +function mat4.inverse(m) end + +---@param m mat4 +---@return mat4 +function mat4.transpose(m) end + +---@param m mat4 +---@param v vec3 +---@return mat4 +function mat4.translate(m, v) end + +---@param m mat4 +---@param v vec3 +---@return mat4 +function mat4.scale(m, v) end + +---@param m mat4 +---@param a number +---@param v vec3 +---@return mat4 +function mat4.rotate(m, a, v) end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/vec2.lua b/engine/EngineResources/scripts/definitions/vec2.lua new file mode 100644 index 00000000..80da457c --- /dev/null +++ b/engine/EngineResources/scripts/definitions/vec2.lua @@ -0,0 +1,60 @@ +---@meta + +---@class vec2 +vec2 = {} + +---@param x number +---@param y number +---@return vec2 +function vec2.new(x, y) end + +---@param v1 vec2 +---@param v2 vec2 +---@return vec2 +function vec2.__mul(v1, v2) end + +---@param v1 vec2 +---@param f number +---@return vec2 +function vec2.__mul(v1, f) end + +---@param f number +---@param v1 vec2 +---@return vec2 +function vec2.__mul(f, v1) end + +---@param v1 vec2 +---@param v2 vec2 +---@return vec2 +function vec2.__div(v1, v2) end + +---@param v1 vec2 +---@param f number +---@return vec2 +function vec2.__div(v1, f) end + +---@param f number +---@param v1 vec2 +---@return vec2 +function vec2.__div(f, v1) end + +---@param v1 vec2 +---@param v2 vec2 +---@return vec2 +function vec2.__add(v1, v2) end + +---@param v1 vec2 +---@param v2 vec2 +---@return vec2 +function vec2.__sub(v1, v2) end + +---@param v1 vec2 +---@param v2 vec2 +---@return string +function vec2.__tostring(v1, v2) end + +---@param v1 vec2 +---@param v2 vec2 +---@param a number +---@return vec2 +function vec2.mix(v1, v2, a) end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/vec3.lua b/engine/EngineResources/scripts/definitions/vec3.lua new file mode 100644 index 00000000..e608122d --- /dev/null +++ b/engine/EngineResources/scripts/definitions/vec3.lua @@ -0,0 +1,61 @@ +---@meta + +---@class vec3 +vec3 = {} + +---@param x number +---@param y number +---@param z number +---@return vec3 +function vec3.new(x, y, z) end + +---@param v1 vec3 +---@param v2 vec3 +---@return vec3 +function vec3.__mul(v1, v2) end + +---@param v1 vec3 +---@param f number +---@return vec3 +function vec3.__mul(v1, f) end + +---@param f number +---@param v1 vec3 +---@return vec3 +function vec3.__mul(f, v1) end + +---@param v1 vec3 +---@param v2 vec3 +---@return vec3 +function vec3.__div(v1, v2) end + +---@param v1 vec3 +---@param f number +---@return vec3 +function vec3.__div(v1, f) end + +---@param f number +---@param v1 vec3 +---@return vec3 +function vec3.__div(f, v1) end + +---@param v1 vec3 +---@param v2 vec3 +---@return vec3 +function vec3.__add(v1, v2) end + +---@param v1 vec3 +---@param v2 vec3 +---@return vec3 +function vec3.__sub(v1, v2) end + +---@param v1 vec3 +---@param v2 vec3 +---@return string +function vec3.__tostring(v1, v2) end + +---@param v1 vec3 +---@param v2 vec3 +---@param a number +---@return vec3 +function vec3.mix(v1, v2, a) end \ No newline at end of file diff --git a/engine/EngineResources/scripts/definitions/vec4.lua b/engine/EngineResources/scripts/definitions/vec4.lua new file mode 100644 index 00000000..5b6da1ee --- /dev/null +++ b/engine/EngineResources/scripts/definitions/vec4.lua @@ -0,0 +1,62 @@ +---@meta + +---@class vec4 +vec4 = {} + +---@param x number +---@param y number +---@param z number +---@param w number +---@return vec4 +function vec4.new(x, y, z, w) end + +---@param v1 vec4 +---@param v2 vec4 +---@return vec4 +function vec4.__mul(v1, v2) end + +---@param v1 vec4 +---@param f number +---@return vec4 +function vec4.__mul(v1, f) end + +---@param f number +---@param v1 vec4 +---@return vec4 +function vec4.__mul(f, v1) end + +---@param v1 vec4 +---@param v2 vec4 +---@return vec4 +function vec4.__div(v1, v2) end + +---@param v1 vec4 +---@param f number +---@return vec4 +function vec4.__div(v1, f) end + +---@param f number +---@param v1 vec4 +---@return vec4 +function vec4.__div(f, v1) end + +---@param v1 vec4 +---@param v2 vec4 +---@return vec4 +function vec4.__add(v1, v2) end + +---@param v1 vec4 +---@param v2 vec4 +---@return vec4 +function vec4.__sub(v1, v2) end + +---@param v1 vec4 +---@param v2 vec4 +---@return string +function vec4.__tostring(v1, v2) end + +---@param v1 vec4 +---@param v2 vec4 +---@param a number +---@return vec4 +function vec4.mix(v1, v2, a) end \ No newline at end of file diff --git a/engine/EngineResources/scripts/engine.lua b/engine/EngineResources/scripts/engine.lua index b92ba270..6d4bb386 100644 --- a/engine/EngineResources/scripts/engine.lua +++ b/engine/EngineResources/scripts/engine.lua @@ -1,3 +1,19 @@ -- Main entry point for engine Lua scripts +local packagePath = package.path +local packageCPath = package.cpath + +-- Appending location to find packages like LuaPanda etc +packagePath = packagePath .. ";C:/dev/rpg/jle/engine/EngineResources/scripts/3rdparty/?.lua" +packageCPath = packageCPath .. ";C:/dev/rpg/jle/engine/EngineResources/scripts/3rdparty/?.dll" + +-- Update the package path +package.path = packagePath +package.cpath = packageCPath + +--require("mobdebug").start() -- not used atm, but works with ZeroBrane IDE + +-- Connect to LuaPanda debugger using LuaHelper extension in VS Code from Tencent +require("LuaPanda").start("127.0.0.1", 8818) + luaEngine = luaEngine or {} \ No newline at end of file diff --git a/engine/jleExternalSerialization.h b/engine/jleExternalSerialization.h index 03e36148..b044a101 100644 --- a/engine/jleExternalSerialization.h +++ b/engine/jleExternalSerialization.h @@ -71,4 +71,56 @@ namespace glm{ } } +// clang-format on + +// Lua / Sol2 + +#include + +namespace sol +{ +template +void +save(Archive &archive, const sol::table &luaTable) +{ + for (auto &pair : luaTable) { + auto keyType = pair.first.get_type(); + auto valueType = pair.second.get_type(); + + std::string key; + if (keyType == sol::type::string) { + key = pair.first.as(); + } else if (keyType == sol::type::number) { + key = std::to_string(pair.first.as()); + } + + switch (valueType) { + case sol::type::table: { + sol::table innerTable = pair.second.as(); + archive(cereal::make_nvp(key, innerTable)); + break; + } + case sol::type::string: { + std::string str = pair.second.as(); + archive(cereal::make_nvp(key, str)); + break; + } + case sol::type::number: { + double number = pair.second.as(); + archive(cereal::make_nvp(key, number)); + break; + } + } + } +} + +template +void +load(Archive &archive, sol::table &luaTable) +{ + // Currently not supporting loading of lua tables from archive +} + +} // namespace sol + #endif // JLE_EXTERNALSERIALIZATION_H diff --git a/engine/jleLuaScript.cpp b/engine/jleLuaScript.cpp index efc8f911..aee295a7 100644 --- a/engine/jleLuaScript.cpp +++ b/engine/jleLuaScript.cpp @@ -41,7 +41,8 @@ void jleLuaScript::loadScript() { try { - _luaEnvironment->getState().script(_sourceCode); + const auto absoluteSrcCodePath = path.getRealPath(); + _luaEnvironment->getState().script(_sourceCode, absoluteSrcCodePath); faultyState = false; } catch (std::exception &e) { LOGE << "Loading script failed: " << e.what(); diff --git a/engine/jleLuaScriptComponent.cpp b/engine/jleLuaScriptComponent.cpp index 09bbdaca..6062d8ab 100644 --- a/engine/jleLuaScriptComponent.cpp +++ b/engine/jleLuaScriptComponent.cpp @@ -87,7 +87,8 @@ jleLuaScriptComponent::loadScript() auto &lua = _luaEnvironment->getState(); try { - lua.script(_sourceCode); + const auto absoluteSrcCodePath = path.getRealPath(); + lua.script(_sourceCode, absoluteSrcCodePath); auto setup = lua[_luaScriptName]["setup"]; auto start = lua[_luaScriptName]["start"]; @@ -95,25 +96,25 @@ jleLuaScriptComponent::loadScript() auto onDestroy = lua[_luaScriptName]["onDestroy"]; if (!setup.valid() || !setup.is()) { - LOGE << "Expected " + _luaScriptName + ".setup function was not found!"; + LOGE << "Expected " + _luaScriptName + ".setup() function was not found!"; faultyState = true; return; } if (!start.valid() || !start.is()) { - LOGE << "Expected " + _luaScriptName + ".start function was not found!"; + LOGE << "Expected " + _luaScriptName + ".start(self) function was not found!"; faultyState = true; return; } if (!update.valid() || !update.is()) { - LOGE << "Expected " + _luaScriptName + ".update function was not found!"; + LOGE << "Expected " + _luaScriptName + ".update(self, dt) function was not found!"; faultyState = true; return; } if (!onDestroy.valid() || !onDestroy.is()) { - LOGE << "Expected " + _luaScriptName + ".onDestroy function was not found!"; + LOGE << "Expected " + _luaScriptName + ".onDestroy(self) function was not found!"; faultyState = true; return; }