保护应用程序免受错误 Lua 脚本的影响

Protecting application from erroneous Lua script

我正在微控制器项目中使用 Lua。 我的软件使用 RTOS,除了其他任务外,它还调用用户提供的 Lua 脚本。

脚本必须有两个函数:init函数和run函数。我的应用程序在初始化期间调用了init函数,然后周期性地调用了run函数。

我加载脚本的方式与 dofile().

非常相似

return 需要 run 函数。这样,底层线程为其他优先级较低的线程产生处理器。

所以问题是,在我有机会调用我需要的函数之前,我如何保护系统免受提供 "dangerous" 脚本的用户的影响,即从未完成其初始执行的脚本。 请参阅以下内容:

function init
    --Do some stuff.
end

function run
    --Do some other stuff.
end

while (true) do
    --Do nasty stuff, without ever returning.
end

在上面的示例中,代码在脚本的初始加载期间阻塞,并且从不 returns。我从来没有机会调用 initrun 函数。我如何检测此类情况,以及如何获得保护?

编辑 忘了说了。我正在使用 Lua 5.2.2.

设置线挂钩或计数挂钩,如果超过限制则中止。

解决方案是推迟执行用户脚本,直到您准备好 WD。


假设这是用户脚本:
user_script.lua

function init()
   --Do some stuff.
end

function run()
   --Do some other stuff.
end

while (true) do
   --Do nasty stuff, without ever returning.
end

您现在在宿主应用程序中所做的事情(就像写在Lua上一样)

dofile("user_script.lua")

init_watchdog()

init()

run()
run()

您应该在主机应用程序中做什么

local user_script_as_text = read_content_of_file("user_script.lua")
assert(loadstring(
[[
   function init()  -- this is your wrapper around user script
      init = nil
      do
         ]]..user_script_as_text..
[[  
      end
      init()  -- invoking "init" defined by user
   end
]]
))()

init_watchdog()

init()  -- invoking your wrapper

run()
run()

如果您需要在打开 WD 之前读取某些配置变量的值,那么这些配置变量必须作为易于解析的字符串提供,如下所示 var1=42,var2=on,var3="Hi"。这些配置变量不能在 Lua 脚本中,因为 Lua 脚本可能会永远循环。
换句话说,您需要来自用户的两个文件:user_config_vars.jsonuser_script.lua