1 #include "cmdhelp/lua.hpp"
2 #include "core/command.hpp"
3 #include "core/misc.hpp"
4 #include "library/globalwrap.hpp"
5 #include "library/keyboard.hpp"
6 #include "library/memtracker.hpp"
7 #include "lua/internal.hpp"
9 #include "lua/unsaferewind.hpp"
10 #include "core/instance.hpp"
11 #include "core/mainloop.hpp"
12 #include "core/messages.hpp"
13 #include "core/memorymanip.hpp"
14 #include "core/moviedata.hpp"
15 #include "core/misc.hpp"
25 extern const char* lua_sysrc_script
;
27 lua::function_group lua_func_bit
;
28 lua::function_group lua_func_misc
;
29 lua::function_group lua_func_load
;
30 lua::function_group lua_func_zip
;
32 lua::class_group lua_class_callback
;
33 lua::class_group lua_class_gui
;
34 lua::class_group lua_class_bind
;
35 lua::class_group lua_class_pure
;
36 lua::class_group lua_class_movie
;
37 lua::class_group lua_class_memory
;
38 lua::class_group lua_class_fileio
;
42 const char* lua_vm_id
= "Lua VM";
43 typedef settingvar::model_int
<32,1024> mb_model
;
44 settingvar::supervariable
<mb_model
> SET_lua_maxmem(lsnes_setgrp
, "lua-maxmem",
45 "Lua‣Maximum memory use (MB)", 128);
47 void pushpair(lua::state
& L
, std::string key
, double value
)
49 L
.pushstring(key
.c_str());
54 void pushpair(lua::state
& L
, std::string key
, std::string value
)
56 L
.pushstring(key
.c_str());
57 L
.pushstring(value
.c_str());
61 std::string
get_mode_str(int mode
)
71 void push_keygroup_parameters(lua::state
& L
, keyboard::key
& p
)
73 keyboard::mouse_calibration p2
;
76 switch(p
.get_type()) {
77 case keyboard::KBD_KEYTYPE_KEY
:
78 pushpair(L
, "value", p
.get_state());
79 pushpair(L
, "type", "key");
81 case keyboard::KBD_KEYTYPE_HAT
:
82 pushpair(L
, "value", p
.get_state());
83 pushpair(L
, "type", "hat");
85 case keyboard::KBD_KEYTYPE_MOUSE
:
86 p2
= p
.cast_mouse()->get_calibration();
87 pushpair(L
, "value", p
.get_state());
88 pushpair(L
, "type", "mouse");
90 case keyboard::KBD_KEYTYPE_AXIS
:
91 mode
= p
.cast_axis()->get_mode();
92 pushpair(L
, "value", p
.get_state());
93 pushpair(L
, "type", get_mode_str(mode
));
101 void soft_oom(int status
)
104 messages
<< "Lua: Memory limit exceeded, attempting to free memory..." << std::endl
;
106 messages
<< "Lua: Memory allocation still failed." << std::endl
;
108 messages
<< "Lua: Allocation successful after freeing some memory." << std::endl
;
111 int push_keygroup_parameters2(lua::state
& L
, keyboard::key
* p
)
113 push_keygroup_parameters(L
, *p
);
118 const char* read_lua_fragment(lua_State
* unused
, void* fragment
, size_t* size
)
120 const char*& luareader_fragment
= *reinterpret_cast<const char**>(fragment
);
121 if(luareader_fragment
) {
122 const char* ret
= luareader_fragment
;
123 *size
= strlen(luareader_fragment
);
124 luareader_fragment
= NULL
;
132 #define TEMPORARY "LUAINTERP_INTERNAL_COMMAND_TEMPORARY"
134 const char* CONST_eval_sysrc_lua
= "local fn, err = " LUA_LOAD_CMD
"(" TEMPORARY
", \"<built-in>\"); "
135 "if fn then fn(); else print2(\"Parse error in sysrc.lua script: \"..err); end;";
136 const char* CONST_eval_lua_lua
= "local fn, err = " LUA_LOAD_CMD
"(" TEMPORARY
"); if fn then fn(); else "
137 " print(\"Parse error in Lua statement: \"..err); end;";
138 const char* CONST_run_lua_lua
= "dofile(" TEMPORARY
");";
140 int system_write_error(lua::state
& L
)
142 throw std::runtime_error("_SYSTEM is write-protected");
145 void copy_system_tables(lua::state
& L
)
151 //Stack: _SYSTEM, KEY, VALUE
154 //Stack: _SYSTEM, KEY, VALUE, KEY, VALUE
156 //Stack: _SYSTEM, KEY, VALUE
158 //Stack: _SYSTEM, KEY
161 L
.push_trampoline(system_write_error
, 0);
162 L
.setfield(-2, "__newindex");
164 L
.setglobal("_SYSTEM");
168 void lua_state::_listener::on_setting_change(settingvar::group
& grp
, const settingvar::base
& val
)
170 if(val
.get_iname() == "lua-maxmem")
171 obj
.set_memory_limit(dynamic_cast<const settingvar::variable
<mb_model
>*>(&val
)->get());
174 void lua_state::set_memory_limit(size_t limit_mb
)
176 L
.set_memory_limit(limit_mb
<< 20);
179 lua_state::lua_state(lua::state
& _L
, command::group
& _command
, settingvar::group
& settings
)
180 : L(_L
), command(_command
),
181 resetcmd(command
, CLUA::reset
, [this]() { this->do_reset(); }),
182 evalcmd(command
, CLUA::eval
, [this](const std::string
& a
) { this->do_eval_lua(a
); }),
183 evalcmd2(command
, CLUA::eval2
, [this](const std::string
& a
) { this->do_eval_lua(a
); }),
184 runcmd(command
, CLUA::run
, [this](command::arg_filename a
) { this->do_run_lua(a
); }),
185 listener(settings
, *this)
187 requests_repaint
= false;
188 requests_subframe_paint
= false;
190 input_controllerdata
= NULL
;
191 //We can't read the value of lua maxmem setting here (it crashes), so just set default, it will be changed
193 L
.set_memory_limit(1 << 27);
194 memtracker::singleton()(lua_vm_id
, L
.get_memory_use());
195 L
.set_memory_change_handler([](ssize_t delta
) { memtracker::singleton()(lua_vm_id
, delta
); });
197 idle_hook_time
= 0x7EFFFFFFFFFFFFFFULL
;
198 timer_hook_time
= 0x7EFFFFFFFFFFFFFFULL
;
203 synchronous_paint_ctx
= NULL
;
204 recursive_flag
= false;
205 luareader_fragment
= NULL
;
207 renderq_saved
= NULL
;
209 renderq_redirect
= false;
211 on_paint
= new lua::state::callback_list(L
, "paint", "on_paint");
212 on_video
= new lua::state::callback_list(L
, "video", "on_video");
213 on_reset
= new lua::state::callback_list(L
, "reset", "on_reset");
214 on_frame
= new lua::state::callback_list(L
, "frame", "on_frame");
215 on_rewind
= new lua::state::callback_list(L
, "rewind", "on_rewind");
216 on_idle
= new lua::state::callback_list(L
, "idle", "on_idle");
217 on_timer
= new lua::state::callback_list(L
, "timer", "on_timer");
218 on_frame_emulated
= new lua::state::callback_list(L
, "frame_emulated", "on_frame_emulated");
219 on_readwrite
= new lua::state::callback_list(L
, "readwrite", "on_readwrite");
220 on_startup
= new lua::state::callback_list(L
, "startup", "on_startup");
221 on_pre_load
= new lua::state::callback_list(L
, "pre_load", "on_pre_load");
222 on_post_load
= new lua::state::callback_list(L
, "post_load", "on_post_load");
223 on_err_load
= new lua::state::callback_list(L
, "err_load", "on_err_load");
224 on_pre_save
= new lua::state::callback_list(L
, "pre_save", "on_pre_save");
225 on_post_save
= new lua::state::callback_list(L
, "post_save", "on_post_save");
226 on_err_save
= new lua::state::callback_list(L
, "err_save", "on_err_save");
227 on_input
= new lua::state::callback_list(L
, "input", "on_input");
228 on_snoop
= new lua::state::callback_list(L
, "snoop", "on_snoop");
229 on_snoop2
= new lua::state::callback_list(L
, "snoop2", "on_snoop2");
230 on_button
= new lua::state::callback_list(L
, "button", "on_button");
231 on_quit
= new lua::state::callback_list(L
, "quit", "on_quit");
232 on_keyhook
= new lua::state::callback_list(L
, "keyhook", "on_keyhook");
233 on_movie_lost
= new lua::state::callback_list(L
, "movie_lost", "on_movie_lost");
234 on_pre_rewind
= new lua::state::callback_list(L
, "pre_rewind", "on_pre_rewind");
235 on_post_rewind
= new lua::state::callback_list(L
, "post_rewind", "on_post_rewind");
236 on_set_rewind
= new lua::state::callback_list(L
, "set_rewind", "on_set_rewind");
237 on_latch
= new lua::state::callback_list(L
, "latch", "on_latch");
240 lua_state::~lua_state()
249 delete on_frame_emulated
;
264 delete on_movie_lost
;
265 delete on_pre_rewind
;
266 delete on_post_rewind
;
267 delete on_set_rewind
;
271 void lua_state::callback_do_paint(struct lua::render_context
* ctx
, bool non_synthetic
) throw()
273 run_synchronous_paint(ctx
);
274 run_callback(*on_paint
, lua::state::store_tag(render_ctx
, ctx
), lua::state::boolean_tag(non_synthetic
));
277 void lua_state::callback_do_video(struct lua::render_context
* ctx
, bool& _kill_frame
, uint32_t& _hscl
,
278 uint32_t& _vscl
) throw()
280 run_callback(*on_video
, lua::state::store_tag(render_ctx
, ctx
), lua::state::store_tag(kill_frame
,
281 &_kill_frame
), lua::state::store_tag(hscl
, &_hscl
), lua::state::store_tag(vscl
, &_vscl
));
284 void lua_state::callback_do_reset() throw()
286 run_callback(*on_reset
);
289 void lua_state::callback_do_frame() throw()
291 run_callback(*on_frame
);
294 void lua_state::callback_do_rewind() throw()
296 run_callback(*on_rewind
);
299 void lua_state::callback_do_idle() throw()
301 idle_hook_time
= 0x7EFFFFFFFFFFFFFFULL
;
302 run_callback(*on_idle
);
305 void lua_state::callback_do_timer() throw()
307 timer_hook_time
= 0x7EFFFFFFFFFFFFFFULL
;
308 run_callback(*on_timer
);
311 void lua_state::callback_do_frame_emulated() throw()
313 run_callback(*on_frame_emulated
);
316 void lua_state::callback_do_readwrite() throw()
318 run_callback(*on_readwrite
);
321 void lua_state::callback_pre_load(const std::string
& name
) throw()
323 run_callback(*on_pre_load
, lua::state::string_tag(name
));
326 void lua_state::callback_err_load(const std::string
& name
) throw()
328 run_callback(*on_err_load
, lua::state::string_tag(name
));
331 void lua_state::callback_post_load(const std::string
& name
, bool was_state
) throw()
333 run_callback(*on_post_load
, lua::state::string_tag(name
), lua::state::boolean_tag(was_state
));
336 void lua_state::callback_pre_save(const std::string
& name
, bool is_state
) throw()
338 run_callback(*on_pre_save
, lua::state::string_tag(name
), lua::state::boolean_tag(is_state
));
341 void lua_state::callback_err_save(const std::string
& name
) throw()
343 run_callback(*on_err_save
, lua::state::string_tag(name
));
346 void lua_state::callback_post_save(const std::string
& name
, bool is_state
) throw()
348 run_callback(*on_post_save
, lua::state::string_tag(name
), lua::state::boolean_tag(is_state
));
351 void lua_state::callback_do_input(portctrl::frame
& data
, bool subframe
) throw()
353 run_callback(*on_input
, lua::state::store_tag(input_controllerdata
, &data
),
354 lua::state::boolean_tag(subframe
));
357 void lua_state::callback_snoop_input(uint32_t port
, uint32_t controller
, uint32_t index
, short value
) throw()
359 if(run_callback(*on_snoop2
, lua::state::numeric_tag(port
), lua::state::numeric_tag(controller
),
360 lua::state::numeric_tag(index
), lua::state::numeric_tag(value
)))
362 run_callback(*on_snoop
, lua::state::numeric_tag(port
), lua::state::numeric_tag(controller
),
363 lua::state::numeric_tag(index
), lua::state::numeric_tag(value
));
366 bool lua_state::callback_do_button(uint32_t port
, uint32_t controller
, uint32_t index
, const char* type
)
369 run_callback(*on_button
, lua::state::store_tag(veto_flag
, &flag
), lua::state::numeric_tag(port
),
370 lua::state::numeric_tag(controller
), lua::state::numeric_tag(index
), lua::state::string_tag(type
));
376 lua::_class
<lua_unsaferewind
> LUA_class_unsaferewind(lua_class_movie
, "UNSAFEREWIND", {}, {
377 }, &lua_unsaferewind::print
);
380 void lua_state::do_reset()
383 luaL_openlibs(L
.handle());
386 copy_system_tables(L
);
387 messages
<< "Lua VM reset" << std::endl
;
390 void lua_state::do_evaluate(const std::string
& a
)
393 throw std::runtime_error("Expected expression to evaluate");
397 void lua_state::callback_quit() throw()
399 run_callback(*on_quit
);
402 void lua_state::callback_keyhook(const std::string
& key
, keyboard::key
& p
) throw()
404 run_callback(*on_keyhook
, lua::state::string_tag(key
), lua::state::fnptr_tag(push_keygroup_parameters2
, &p
));
407 void init_lua(emulator_instance
& core
) throw()
409 core
.lua
->set_oom_handler(OOM_panic
);
410 core
.lua
->set_soft_oom_handler(soft_oom
);
413 core
.lua
->add_function_group(lua_func_bit
);
414 core
.lua
->add_function_group(lua_func_load
);
415 core
.lua
->add_function_group(lua_func_misc
);
416 core
.lua
->add_function_group(lua_func_zip
);
417 core
.lua
->add_class_group(lua_class_callback
);
418 core
.lua
->add_class_group(lua_class_gui
);
419 core
.lua
->add_class_group(lua_class_bind
);
420 core
.lua
->add_class_group(lua_class_pure
);
421 core
.lua
->add_class_group(lua_class_movie
);
422 core
.lua
->add_class_group(lua_class_memory
);
423 core
.lua
->add_class_group(lua_class_fileio
);
424 } catch(std::exception
& e
) {
425 messages
<< "Can't initialize Lua." << std::endl
;
428 luaL_openlibs(core
.lua
->handle());
429 core
.lua2
->run_sysrc_lua(false);
430 copy_system_tables(*core
.lua
);
433 void quit_lua(emulator_instance
& core
) throw()
439 #define LUA_TIMED_HOOK_IDLE 0
440 #define LUA_TIMED_HOOK_TIMER 1
442 uint64_t lua_state::timed_hook(int timer
) throw()
445 case LUA_TIMED_HOOK_IDLE
:
446 return idle_hook_time
;
447 case LUA_TIMED_HOOK_TIMER
:
448 return timer_hook_time
;
453 void lua_state::callback_do_unsafe_rewind(movie
& mov
, void* u
)
457 lua_unsaferewind
* u2
= reinterpret_cast<lua::objpin
<lua_unsaferewind
>*>(u
)->object();
460 run_callback(*on_pre_rewind
);
461 run_callback(*on_movie_lost
, "unsaferewind");
462 mainloop_restore_state(u2
->console_state
);
463 mov
.fast_load(u2
->console_state
.save_frame
, u2
->ptr
, u2
->console_state
.lagged_frames
,
464 u2
->console_state
.pollcounters
);
465 core
.mlogic
->get_mfile().dyn
= u2
->console_state
;
466 run_callback(*on_post_rewind
);
467 delete reinterpret_cast<lua::objpin
<lua_unsaferewind
>*>(u
);
468 } catch(std::bad_alloc
& e
) {
475 run_callback(*on_set_rewind
, lua::state::fn_tag([&core
, &mov
](lua::state
& L
) ->
477 lua_unsaferewind
* u2
= lua::_class
<lua_unsaferewind
>::create(*core
.lua
);
478 u2
->console_state
= core
.mlogic
->get_mfile().dyn
;
479 mov
.fast_save(u2
->console_state
.save_frame
, u2
->ptr
, u2
->console_state
.lagged_frames
,
480 u2
->console_state
.pollcounters
);
486 void lua_state::callback_movie_lost(const char* what
)
488 run_callback(*on_movie_lost
, std::string(what
));
491 void lua_state::callback_do_latch(std::list
<std::string
>& args
)
493 run_callback(*on_latch
, lua::state::vararg_tag(args
));
496 lua_unsaferewind::lua_unsaferewind(lua::state
& L
)
500 void lua_state::run_startup_scripts()
502 for(auto i
: startup_scripts
) {
503 messages
<< "Trying to run Lua script: " << i
<< std::endl
;
508 void lua_state::add_startup_script(const std::string
& file
)
510 startup_scripts
.push_back(file
);
513 const std::map
<std::string
, std::u32string
>& lua_state::get_watch_vars()
518 bool lua_state::run_lua_fragment() throw(std::bad_alloc
)
523 int t
= L
.load(read_lua_fragment
, &luareader_fragment
, "run_lua_fragment", "t");
524 if(t
== LUA_ERRSYNTAX
) {
525 messages
<< "Can't run Lua: Internal syntax error: " << L
.tostring(-1)
530 if(t
== LUA_ERRMEM
) {
531 messages
<< "Can't run Lua: Out of memory" << std::endl
;
535 recursive_flag
= true;
536 int r
= L
.pcall(0, 0, 0);
537 recursive_flag
= false;
538 if(r
== LUA_ERRRUN
) {
539 messages
<< "Error running Lua hunk: " << L
.tostring(-1) << std::endl
;
543 if(r
== LUA_ERRMEM
) {
544 messages
<< "Error running Lua hunk: Out of memory" << std::endl
;
548 if(r
== LUA_ERRERR
) {
549 messages
<< "Error running Lua hunk: Double Fault???" << std::endl
;
554 if(r
== LUA_ERRGCMM
) {
555 messages
<< "Error running Lua hunk: Fault in garbage collector" << std::endl
;
561 if(requests_repaint
) {
562 requests_repaint
= false;
563 command
.invoke("repaint");
568 void lua_state::do_eval_lua(const std::string
& c
) throw(std::bad_alloc
)
570 L
.pushlstring(c
.c_str(), c
.length());
571 L
.setglobal(TEMPORARY
);
572 luareader_fragment
= CONST_eval_lua_lua
;
576 void lua_state::do_run_lua(const std::string
& c
) throw(std::bad_alloc
)
578 L
.pushlstring(c
.c_str(), c
.length());
579 L
.setglobal(TEMPORARY
);
580 luareader_fragment
= CONST_run_lua_lua
;
584 template<typename
... T
> bool lua_state::run_callback(lua::state::callback_list
& list
, T
... args
)
588 recursive_flag
= true;
590 if(!list
.callback(args
...)) {
591 recursive_flag
= false;
594 } catch(std::exception
& e
) {
595 messages
<< e
.what() << std::endl
;
597 recursive_flag
= false;
599 if(requests_repaint
) {
600 requests_repaint
= false;
601 command
.invoke("repaint");
606 void lua_state::run_sysrc_lua(bool rerun
)
608 L
.pushstring(lua_sysrc_script
);
609 L
.setglobal(TEMPORARY
);
610 luareader_fragment
= CONST_eval_sysrc_lua
;
611 if(!run_lua_fragment() && !rerun
) {
612 //run_lua_fragment shows error.
613 //messages << "Failed to run sysrc lua script" << std::endl;
618 void lua_state::run_synchronous_paint(struct lua::render_context
* ctx
)
620 if(!synchronous_paint_ctx
)
622 lua_renderq_run(ctx
, synchronous_paint_ctx
);