Pumpkin-Framework / JNLua

JNLua fork for pumpkin scripting engine
MIT License
1 stars 0 forks source link

Allow limiting the memory usage of individual Lua states #9

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I had the requirement to limit Lua VMs to a maximum memory usage for better 
sandboxing. This is actually pretty easy thanks to Lua offering a way to supply 
a custom allocator. I extended JNLua a bit to offer seamless support for this:
- Added a new constructor that takes the initially allowed maximum memory. If 
this constructor is used instead of the default one, the custom allocator will 
be used. If not, the default allocator will be used, so there's no impact on 
performance in that case.
- Added getter and setter for allowed maximum memory: 
getTotalMemory/setTotalMemory. This value can be changed at any time for an 
existing Lua VM that was created with the new constructor. Due to the allocator 
being decided upon VM creation this cannot be enabled afterwards.
- Added a getter for current memory consumption: getFreeMemory. This is the 
exact remaining number of bytes the allocator may still use.

Keep in mind that the native library compiled with this patch will only work 
with the patched LuaState class, since the native library accesses the new 
fields in the LuaState class: using an older implementation will crash (field 
not found). I quickly scrolled through jni.h but didn't see anything that 
allows checking for the existence of a field without throwing an error.

The attached patch is for release 0.9.6. I'm sure it will be very simple to 
port this to the 1.x branch, but I just don't need it so I won't.

I'm providing this patch no strings attached, use it as you see fit. Ideally 
I'd hope for this to get integrated into the repository, so I don't have to 
patch it whenever there's a new version - I tried to match the existing code 
style as closely as possible.

Final disclaimer: I only tested this on Windows, but I don't see why it 
wouldn't work on other systems (there's no platform specific code in the patch).

Original issue reported on code.google.com by fnuecke on 19 Aug 2013 at 9:15

Attachments:

GoogleCodeExporter commented 9 years ago
Update with bugfix for cases when calling back and forth between Lua and Java.

Original comment by fnuecke on 20 Aug 2013 at 5:17

Attachments:

GoogleCodeExporter commented 9 years ago
Thanks for the patch. I will look into this in the future.

Original comment by an...@naef.com on 24 Aug 2013 at 9:29

GoogleCodeExporter commented 9 years ago
I'd appreciate that :)

Here's another bugfix (stupid derp) and a port for 1.0.4.

Original comment by fnuecke on 31 Aug 2013 at 1:45

Attachments:

GoogleCodeExporter commented 9 years ago
[deleted comment]
GoogleCodeExporter commented 9 years ago
Another small fixed fix.

Original comment by fnuecke on 29 Sep 2013 at 3:47

Attachments: