Question: Max time for Lua script to complete execution and cancel from other thread.
Closed this issue · 3 comments
Hi,
Thanks for this crate. I'm using it to embed some lua code in a rust project, mostly expression evaluation (running on main thread) or simple scripts to enrich application behaviour (typically ruing in a dedicated thread). I have two questions:
- It is possible to set a max time of execution of a lua expresion or script? This will avoid that any wild lua code will block the main thread.
- It is possible to stop lua code running in another thread?
Thanks,
Hi @ludiazv,
As far as I'm aware, the answer is: kinda.
If you're just looking to prevent accidental runaway loops for a better developer experience you can abuse debug.sethook
to get something that will interrupt your code. Although really you'll probaby want to do this from the Rust side of things. See: https://docs.rs/rlua/0.17.0/rlua/struct.Lua.html#method.set_hook You'd then either set the limit based on total number of instructions or you'd externally track the amount to time/cpu-time that has elapsed since the script started executing.
From what I've read though, this isn't really a robust enough method to prevent malicious code from blocking. For that you'd want an entirely separate OS process using real sandboxing techniques so you have the ability to externally kill runaway processes.
Thanks for the information @azdle . I will give a try to sethook for evaluate expressions with every_nth_instruction with a big value to set a timeout. I think this will work.
On the other hand, spawning new process will be complex for my application as the Lua script will access rust objects.
I'll post the experience with sethook.
Thanks again.
Closing as this has been answered.