How to use time-out to protect against JavaScript loops etc. in Duktape 2.5.0

148 Views Asked by At

I am successfully running Duktape JavaScripts using protected calls - actually invoked with duk_peval().

I want to catch indefinite loops etc. I have read the guide and understand I need to set up a function that is called periodically and in which I can check if too much time has elapsed. If so, I return 1 to unwind the duk_peval call. But I do not understand how/where to set up that function - presumably in C(++) before calling duk_peval() and possibly declaring it in a macro.

How must the correct setup look like?

1

There are 1 best solutions below

0
Antipole On

I eventually cracked this for myself.

You need to provide three functions like the examples in examples/cmdline/dduk_cmdline_lowmem.c You need the three that have timeout in their name. In this example, the function that handles the check from the bytecode executor is duk_bool_t lowmem_exec_timeout_check(void *udata)

Then you need to set the macro DUK_USE_EXEC_TIMEOUT_CHECK to this name and declare the function. In my case, I added the following to my duktape.h header file:

#define DUK_USE_EXEC_TIMEOUT_CHECK JSduk_timeout_check // timeout check function
duk_bool_t JSduk_timeout_check(void *udata);

and it works!