Commit Graph

286 Commits

Author SHA1 Message Date
kyren 9c4d451d4c Implement tuple MultiValue tuple conversion up to 16 2018-09-02 02:48:54 -04:00
kyren 1a9c50f228 Solve (maybe) *another* soundness issue with `Lua::scope`
Callbacks should not be able to capture their arguments and hold onto them,
because the `&Lua` used in previous calls will not remain valid across calls.
One could imagine an API where the specific `&Lua` is simply stored inside the
`Scope` itself, but this is harder to do, and would (badly) encourage storing
references inside Lua userdata.

Ideally, the only way it should be possible to store Lua handles inside Lua
itself is through usafety or the `rental` crate or other self-borrowing
techniques to make references into 'static types.  If at all possible this
roadblock should stay, because reference types inside userdata are almost always
going to lead to a a memory leak, and if you accept the risks you should just
use `RegistryKey` with its manual removal.
2018-08-05 20:03:47 -04:00
kyren b35ff5fa12 Remove out of date documentation, simpler scope lifetimes
The documentation describing it being a logic bug to access "outer" callback
handles when inside an "inner" callback is inaccurate, that was only true when
using an older design for handle values.

Also, there is no reason to have a separate 'callback lifetime, because 'scope
is already invariant and just using 'scope seems equivalent.
2018-08-05 19:02:19 -04:00
kyren a2615a8cbb Fix for a soundness bug around scope, don't allow callback parameters to escape
Also includes other fixes for compiletest_rs failures, and a small reorg of tests
2018-08-05 11:54:33 -04:00
kyren 8366960368 Update to failure 0.1.2, rename deprecated methods 2018-08-05 11:48:25 -04:00
kyren 2e1bdb64c0 format with up-to-date rustfmt 2018-08-05 09:51:39 -04:00
kyren e6688e1db2 very small doc fixes 2018-08-05 09:51:32 -04:00
kyren 02bc8da203 Prepare for 0.14.0 release 2018-06-29 01:24:28 -04:00
kyren 71f3dd50a1 New approach for ref types, use an auxillary thread stack
Vastly simpler and less magical than using a fixed size magical section of the
active stack, and seems to be no slower.  The only real downside is that
it *seems* extremely extremely hacky (and to be fair, it is).
2018-03-28 01:09:51 -04:00
kyren 5aa22de68e Use git dependency on failure 1.0 for right now 2018-03-20 14:07:32 -04:00
kyren 8b9ab3d031 Small renames and comments to better communicate the intention of stack checking functions 2018-03-19 17:42:10 -04:00
kyren a05f0d5cd0 Where possible, don't call to_lua / from_lua / to_lua_multi / from_lua_multi callbacks during Lua stack manipulation
This should protect against being able to trigger a stack assert in Lua.  Lua
and associated types shoul be able to assume that LUA_MINSTACK stack slots are
available on any user entry point.  In the future, we could turn check_stack
into something that only checked the Lua stack when debug_assertions is true.
2018-03-19 15:16:40 -04:00
kyren 0d5e45e800 Always ensure LUA_MINSTACK available stack spaces on callback
Otherwise, cleanly error with an appropriate stack error.  Part of an effort to
ensure that it should not be possible to trigger a stack space assert.
2018-03-19 14:36:01 -04:00
kyren 4b6809c766 Clean up some lifetime specification 2018-03-19 14:35:46 -04:00
kyren 985636267c Fix some bad potential unsafety on inner callback calls.
Since we now optionally use stack spaces for handle values, we have to be
mindful of whether our stack handle points to the stack in an outer level of
Lua "stack protection".  We now keep track of the "recursion level" of Lua
instances, and do not allow ref manipulation on "outer" Lua instances until the
inner callback has returned.  Also, update the documentation to reflect the
additional panic behavior.
2018-03-12 22:36:52 -04:00
kyren 1019ab8a3f Use rlua_ asserts instead of unreachable!, changelog updates for 0.14
0.14 will be released alongside `failure` 1.0 with a dependency update.
2018-03-12 20:36:39 -04:00
kyren c6c90f201c Documentation updates for new handle behavior, and some minor cleanup 2018-03-12 17:50:48 -04:00
kyren 4358034bbf Do not crash in release when accessing an AnyUserData
Also, don't bother asserting if the userdata has no metatable, just behave as
though the userdata has no type.  This should be impossible to trigger currently
without the debug library, but it is not really that useful of an assert anyway.
2018-03-12 17:48:05 -04:00
kyren f0775f4a1a Move several asserts to only be active with debug, bump alpha version number 2018-03-12 16:14:52 -04:00
kyren f79d771f1a Documentation improvements, split scope into its own module, improved tests
Also makes `Lua` and associated types !UnwindSafe and !RefUnwindSafe, which they
should be because they are intensely internally mutable.  Lua IS still panic
safe, but that doesn't mean it should be marked as UnwindSafe (as I understand
it).
2018-03-12 16:00:11 -04:00
kyren ee23f199f0 Remove `stack_guard` function and instead just use StackGuard directly 2018-03-12 13:13:44 -04:00
kyren 95633ce915 Merge branch 'bench' 2018-03-12 12:29:27 -04:00
kyren 601e9f4cac A lot of performance changes.
Okay, so this is kind of a mega-commit of a lot of performance related changes
to rlua, some of which are pretty complicated.

There are some small improvements here and there, but most of the benefits of
this change are from a few big changes.  The simplest big change is that there
is now `protect_lua` as well as `protect_lua_call`, which allows skipping a
lightuserdata parameter and some stack manipulation in some cases.  Second
simplest is the change to use Vec instead of VecDeque for MultiValue, and to
have MultiValue be used as a sort of "backwards-only" Vec so that ToLuaMulti /
FromLuaMulti still work correctly.

The most complex change, though, is a change to the way LuaRef works, so that
LuaRef can optionally point into the Lua stack instead of only registry values.
At state creation a set number of stack slots is reserved for the first N LuaRef
types (currently 16), and space for these are also allocated separately
allocated at callback time.  There is a huge breaking change here, which is that
now any LuaRef types MUST only be used with the Lua on which they were created,
and CANNOT be used with any other Lua callback instance.  This mostly will
affect people using LuaRef types from inside a scope callback, but hopefully in
those cases `Function::bind` will be a suitable replacement.  On the plus side,
the rules for LuaRef types are easier to state now.

There is probably more easy-ish perf on the table here, but here's the
preliminary results, based on my very limited benchmarks:

create table            time:   [314.13 ns 315.71 ns 317.44 ns]
                        change: [-36.154% -35.670% -35.205%] (p = 0.00 < 0.05)
create array 10         time:   [2.9731 us 2.9816 us 2.9901 us]
                        change: [-16.996% -16.600% -16.196%] (p = 0.00 < 0.05)
                        Performance has improved.
create string table 10  time:   [5.6904 us 5.7164 us 5.7411 us]
                        change: [-53.536% -53.309% -53.079%] (p = 0.00 < 0.05)
                        Performance has improved.
call add function 3 10  time:   [5.1134 us 5.1222 us 5.1320 us]
                        change: [-4.1095% -3.6910% -3.1781%] (p = 0.00 < 0.05)
                        Performance has improved.
call callback add 2 10  time:   [5.4408 us 5.4480 us 5.4560 us]
                        change: [-6.4203% -5.7780% -5.0013%] (p = 0.00 < 0.05)
                        Performance has improved.
call callback append 10 time:   [9.8243 us 9.8410 us 9.8586 us]
                        change: [-26.937% -26.702% -26.469%] (p = 0.00 < 0.05)
                        Performance has improved.
create registry 10      time:   [3.7005 us 3.7089 us 3.7174 us]
                        change: [-8.4965% -8.1042% -7.6926%] (p = 0.00 < 0.05)
                        Performance has improved.

I think that a lot of these benchmarks are too "easy", and most API usage is
going to be more like the 'create string table 10' benchmark, where there are a
lot of handles and tables and strings, so I think that 25%-50% improvement is a
good guess for most use cases.
2018-03-11 23:20:10 -04:00
kyren 6470b6eefc Improve documentation about __index vs regular methods 2018-03-10 10:30:17 -05:00
kyren 431f84012a Enable stack leak panic universally
This will potentially panic on Drop of a `Lua` instance, which may be an abort
if this is a double panic, but that is more desirable than such a bug being
hidden.
2018-03-08 12:36:03 -05:00
kyren d06890afc6 Simplify stack_guard / stack_err_guard
The expected change is always zero, because stack_guard / stack_err_guard are
always used at `rlua` entry / exit points.
2018-03-08 11:40:24 -05:00
kyren 10802bf70f Whoops, fix an assert that was improperly changed to an internal error 2018-03-08 11:14:02 -05:00
kyren adfeaeab49 Change strategies for handling the Lua stack during panics
Previously, on an internal panic, the Lua stack would be reset before panicking
in an attempt to make sure that such panics would not cause stack leaks or leave
the stack in an unknown state.  Now, such panic handling is done in stack_guard
and stack_err_guard instead, and this is for a few reasons:

1) The previous approach did NOT handle user triggered panics that were outside
   of `rlua`, such as a panic in a ToLua / FromLua implementation.  This is
   especially bad since most other panics would be indicative of an internal bug
   anyway, so the utility of keeping `rlua` types usable after such panics was
   questionable.  It is much more sensible to ensure that `rlua` types are
   usable after *user generated* panics.
2) Every entry point into `rlua` should be guarded by a stack_guard or
   stack_err_guard anyway, so this should restore the Lua stack on exiting back
   to user code in all cases.
3) The method of stack restoration no longer *clears* the stack, only resets it
   to what it previously was.  This allows us, potentially, to keep values at
   the beginning of the Lua stack long term and know that panics will not
   clobber them.  There may be a way of dramatically speeding up ref types by
   using a small static area at the beginning of the stack instead of only the
   registry, so this may be important.
2018-03-08 10:59:50 -05:00
kyren 1e76de1d08 Update docs to include warning about RegistryKey in callbacks 2018-03-06 06:23:04 -05:00
kyren eb154e4a9e Further safety updates of `protect_lua_call`
Only allow Copy result types and Fn parameter functions, do not risk dropping
anything inside function passed to lua_pcall.
2018-03-06 06:22:05 -05:00
kyren 37feaebdce Also describe how protect_lua_call functions should not hold types that Drop 2018-03-01 17:56:19 -05:00
kyren 8ac78c4585 Make some changes whose necessity became recently apparent while reading rustc 1.24.1 change notes.
So, despite staring intently at the params structure magic in protect_lua_call,
there is still a nasty bug.  In the event of an error, the return value of the
parameters structure could be dropped despite being mem::unintialized.  Of
course, the actual return values are incidentally always Copy I think, so this
wasn't an actual bug, but I've proven to myself the danger of such dark majyyks.
Just use Option and be done with it, it doesn't have to be so complicated!

Also document why there are a slew of random functions in the ffi module.
2018-03-01 17:17:18 -05:00
kyren d7995137d7 Add debug API to ffi (not used yet, was using experimentally)
Also fix for cstr! macro
2018-02-28 14:42:05 -05:00
kyren a49ea51b79 Remove terrible awful no-good evil hack
The breakage is being addressed in rust itself.
2018-02-19 18:09:04 -05:00
kyren e19a5b6481 Cleanup max upvalues constant a bit, add some luaconf.h assumptions 2018-02-19 18:03:18 -05:00
kyren d78420b51c Communicate a little bit better about the checkstack constant 2018-02-19 17:57:39 -05:00
kyren ace5cb44f0 Letting scope handles escape the scope was unsafe
This simplifies the Scope lifetimes, and should make it a compile error for
scope created handles to exit the scope.  This should be strictly better, as you
would never WANT to do this, but I hope that I have not caused a subtle lifetime
problem that would prevent passing those created handles back into Lua.  I've
tested every situation I can think of, and it doesn't appear to be an issue, but
I admit that I don't fully understand everything involved and I could be missing
something.

The reason that I needed to do this is that if you can let a scope handle escape
the scope, you have a LuaRef with an unused registry id, and that can lead to
UB.  Since not letting the scope references escape is a strict improvement
ANYWAY (if I haven't caused a lifetime issue), this is the easiest fix.

This is technically a breaking change but I think in most cases if you notice it
you would be invoking UB, or you had a function that accepted a Scope or
something.  I don't know if it's worth a version bump?
2018-02-19 17:40:48 -05:00
kyren 0450c9b597 Make error_traceback never trigger a Lua error
It is called from both Lua and Rust, and any error would hide the error it's
trying to generate a traceback for.
2018-02-18 21:13:35 -05:00
kyren b07557c1c7 more hard to trigger bugs that I noticed doing conversion 2018-02-18 06:09:15 -05:00
kyren bb2a9c5b5d Fix several bugs found while doing C conversion
Fixing these in master in case I need to back out the change I'm making
2018-02-18 05:26:14 -05:00
kyren dec360f78f Can.. can I do this? Is this a thing that actually works?
Drastic times and all that.
2018-02-16 22:01:41 -05:00
kyren 73de52dcce Remove debugging println!s 2018-02-16 21:09:49 -05:00
kyren f0186d1799 Provisional "fix" for #71. Requires nightly :( 2018-02-15 21:39:35 -05:00
kyren fc058eba60 comment fixes 2018-02-12 13:56:23 -05:00
kyren c22aae461b Some changes for panic correctness, stack usage correctness, and speed 2018-02-12 13:54:31 -05:00
kyren c4b3170e2b More documentation fixes 2018-02-11 18:17:15 -05:00
kyren bfe44089ef Documentation fixes / additions 2018-02-11 17:54:17 -05:00
kyren ea834635c1 Add `UserDataMethods::` `add_function_mut` and `add_meta_function_mut` 2018-02-11 17:53:25 -05:00
kyren 7231e95195 It's far too easy to write 'stack_guard' as opposed to 'stack_err_guard'!
And it will work until something fails!  Maybe there should be a test that calls
every possible function that invokes to_lua / from_lua with a type where both
directions fail?
2018-02-11 16:47:39 -05:00
kyren ce7e8e61fd shave this yak some more, make `Callback` type alias have two lifetimes 2018-02-11 08:51:17 -05:00
kyren da1e1625b3 Specify the types exactly in the scary transmute
If I happen to change the definition of the Callback type alias, instead of
creating a potentially arbitrary transmute, it will now instead fail to compile.
2018-02-11 08:30:03 -05:00
kyren a91e3ed411 clarify the scary transmute 2018-02-11 08:22:15 -05:00
kyren fd0e31c6ea Add some extra warnings about the reference cycle dangers of `RegistryKey` 2018-02-11 06:37:51 -05:00
kyren 20480ec88d fix unused process import warnings 2018-02-10 17:55:08 -05:00
kyren 9e3374ff9e lua_abort / lua_internal_abort macros 2018-02-10 17:49:54 -05:00
kyren d4c80d44c8 Attempt to enable compiletest_rs on nightly on travis 2018-02-10 00:27:15 -05:00
kyren 60743d45cd Move all tests into a tests/ subfolder 2018-02-09 23:52:05 -05:00
kyren d331e4b97c Error correctly on too many arguments / returns / binds / recursions
There are also some other drive-by changes to fix panicking in extern "C"
functions and other edge case stack errors
2018-02-09 23:40:23 -05:00
kyren fe6e4bdf35 Explicit error type for destructed callbacks
Also removes some cleverness if debug_assertions was disabled, as it really
doesn't make much of a performance difference.
2018-02-09 21:23:59 -05:00
kyren 514abd5b82 Actually unref scope created types from the registry AS WELL AS destructing them 2018-02-09 07:27:55 -05:00
kyren 84b009da03 A few small performance improvements
When 'debug_assertions' is not enabled, don't bother doing asserts in
stack_guard / stack_err_guard.  Also, add an optional feature not enabled by
default to disable LUA_USE_APICHECK in release mode.  Once the bugs in rlua that
allow you to trigger LUA_USE_APICHECK are fixed, this feature will be the
default behavior.
2018-02-09 01:22:34 -05:00
kyren de4d21f8ea Fix some strange lifetime usage on `Lua::create_function`
I don't think that the lifetime of the &Lua in the callback and the lifetime of
the &Lua from creating the callback need to be related at all.  I'm not sure if
this has any actual effect, but it makes more sense (I think?).
2018-02-08 18:52:29 -05:00
kyren b6bc8d0bed Make the `Scope` lifetimes more sensible
Avoids messy lifetime issues when interacting with other handle types with scope
produced values.

The whole lifetime situation with 'lua on most methods could actually probably
use some looking at, I'm sure it probably has lots of less than optimal
decisions in it.

This also adds a proper comment to the 'scope lifetime to explain that the key
is that 'scope needs to be invariant to make things safe.  Disregard my previous
commit message, the real problem is that I had a poor understanding of lifetime
variance / invaraince.
2018-02-08 18:45:07 -05:00
kyren 7701aeef85 TERRIBLE HACK FIX I DO NOT UNDERSTAND
Okay, so this is the fix for the previously mentioned lifetime problem.  I
mimicked the API for `crossbeam::scope` extremely closely for `Lua::scope`, and
for some reason things that would not compile with `crossbeam::scope` WOULD
compile with `Lua::scope`, and I could not figure it out.

So I took the crossbeam source and made tiny edits until I determined the
crossover point where invalid borrows would compile, and it was.. not what I
expected it to be.  Simply replacing a RefCell<Option<DtorChain<'a>>> with a
PhantomData<&'a ()> would suddenly cause this to compile with crossbeam:

```
struct Test {
    field: i32,
}
crossbeam::scope(|scope| {
    let mut t = Test {
        field: 0,
    };

    scope.spawn(|| t.field = 42);

    drop(t);

    // ...anything
})

```

which is precisely the same problem as `rlua`.

To say I am unsatisfied by this fix is a drastic understatement.  SURELY this
must be a compiler bug?
2018-02-08 05:12:27 -05:00
kyren f05716deb8 This SHOULD fix the lifetime problem with scope... but it doesn't!
The following code should not compile:

```
struct Test {
    field: i32,
}

let lua = Lua::new();
lua.scope(|scope| {
    let mut test = Test { field: 0 };

    let f = scope
        .create_function(|_, ()| {
            test.field = 42;
            Ok(())
        })
        .unwrap();
    lua.globals().set("bad!", f).unwrap();
});
```

yet it does with this commit.  However, I have a fix for this, which I do not in
any way understand.
2018-02-08 05:12:11 -05:00
kyren 7a0c066593 export accidentally hidden `Scope` type 2018-02-08 01:54:30 -05:00
kyren 164250b352 Don't panic with "rlua internal error" message on panics that are not internal
It is part of the contract that only LuaRef types constructed from the same
parent Lua state are passed into Lua, so generating a panic there is not an
internal error.
2018-02-07 17:05:00 -05:00
kyren b9d9bea28a slightly faster, less obnoxious scope drop 2018-02-07 16:51:24 -05:00
kyren 98ee4e9492 More correct scope drop behavior
now no longer aborts if a Drop impl panics
2018-02-07 16:42:03 -05:00
kyren ab9841a02f Don't keep the unref list around forever after Lua is dropped 2018-02-07 11:16:22 -05:00
kyren cb25a99f70 Lots of changes, not sure if actually safe yet.
* Make Lua Send
* Add Send bounds to (nearly) all instances where userdata and functions are
  passed to Lua
* Add a "scope" method which takes a callback that accepts a `Scope`, and give
  `Scope` the ability to create functions and userdata that are !Send, *and also
  functions that are not even 'static!*.
2018-02-06 20:53:25 -05:00
kyren 7780a91e19 fix missing unwrap in tests 2018-02-06 20:29:48 -05:00
kyren b056ed2c4e Don't panic on mismatched `RegistryKey` use, instead return error 2018-02-06 10:51:39 -05:00
kyren 823c2deaca Slightly different strategy with RegistryKey values
Provide a method for automatic cleanup of expired RegistryKey values, so that
manually cleaning up registry values is optional.
2018-02-06 03:33:19 -05:00
kyren 8820e7705c test `owns_registry_value` 2018-02-06 00:54:04 -05:00
kyren 79635f29be Add method to check whether a RegistryKey is owned by a given `Lua` instance 2018-02-06 00:41:51 -05:00
kyren d43f8129f3 experimentally make `RegistryKey` Send 2018-02-06 00:05:35 -05:00
kyren fe35742026 Set the metatable of __gc'ed userdata to something more informative 2018-02-05 14:40:20 -05:00
kyren 6382baa991 Use ptr::write to initialize uninitalized memory, NOT mem::replace 2018-01-27 18:38:00 -05:00
kyren 77eb73a50c Simplify handling of userdata __gc and resurrected userdata.
Now, simply remove the userdata table immediately before dropping the userdata.
This does two things, it prevents __gc from double dropping the userdata, and
after the first call to __gc, it prevents the userdata from being identified as
any particular userdata type, so it cannot be misused after being finalized.

This change thus removes the userdata invalidation error, and simplifies a lot
of userdata handling code.

It also fixes a panic bug.  Because there is no predictable order for
finalizers, it is possible to run a userdata finalizer that does not resurrect
itself before a lua table finalizer that accesses that userdata, and this means
that there were several asserts that were possible to trigger in normal Lua code
in util.rs related to `WrappedError`.

Now, finalized userdata is simply a userdata with no methods, so any use of
finalized userdata becomes a normal script runtime error (though, with a
potentially confusing error message).  As a future improvement, we could set
a metatable on finalized userdata that provides a better error message.
2018-01-27 18:27:01 -05:00
kyren 8527266d3b Add an API that exposes the functionality of `lua_getuservalue` and `lua_setuservalue` 2018-01-26 20:06:18 -05:00
kyren 0801104762 ACTUALLY expose `RegistryKey` API
Also fixes a safety issue with RegistryKey, where you could use RegistryKeys
with mismatching Lua instances.
2018-01-26 19:43:53 -05:00
Jonas Schievink ff847ea438 __gc would be safe now, reword MetaMethod docs accordingly 2018-01-26 21:31:01 +01:00
Jonas Schievink 0a4ae8d859 Additional `MetaMethod` docs 2018-01-26 19:44:35 +01:00
Jonas Schievink 79b028419f create_function docs: mention what returning `Err` does 2018-01-26 19:24:01 +01:00
Jonas Schievink 67f8e1d49c Fix rustdoc rendering warning 2018-01-26 18:35:21 +01:00
Jonas Schievink 2d89eb39da Don't use a `StdResult` alias for better docs.
This is a pretty opinionated change, but I find documentation to be
clearer when using plain old names everybody understands immediately.
2018-01-26 18:32:58 +01:00
kyren 79ba909db0 Experimentally use the `failure` crate for errors 2018-01-21 20:08:51 -05:00
kyren 685fc12aad Missed unprotected call to luaL_ref 2017-12-17 16:55:37 -05:00
kyren 42007260ca Add automatic Lua "user accessible registry" keys
Also, during the implementation of this, I noticed a problem with the 0.10
memory safety, which is that luaL_ref is also memory unsafe.  I attempted to
change the API to support luaL_ref potentially returning Result, but this change
will cause an enormous amount of API chaos, (just as an example, it becomes
impossible to implement Clone for LuaRef as is).  Instead, luaL_ref now is
guarded by gc_guard.
2017-12-17 00:46:22 -05:00
kyren e6d84a4bb3 Change API names, add unset function 2017-12-16 18:05:53 -05:00
kyren ad23fe83e0 auto formatting 2017-12-16 17:46:32 -05:00
kyren bfb6111e0a API for registry access via string keys only (for now)
Also includes some fixes for stack usage and changes an assert_eq to lua_assert
2017-12-16 17:44:13 -05:00
kyren 56c9493f23 spelling fix for my spelling fix 2017-12-05 07:30:34 -05:00
kyren d609d38675 spelling fixes 2017-12-05 00:12:00 -05:00
kyren 447810364a extra space 2017-12-04 23:57:08 -05:00
kyren 66a4e9a8e7 Add `ExpiredUserData` error and avoid what was previously a panic
Also make sure that panic messages clearly state that they are internal errors,
so people report them as a bug.  Since the only panics left are all internal
errors, just move the internal error message into the panic / assert macros.
2017-12-04 02:50:27 -05:00
kyren 80a98ef29c Couple of changes:
- Update readme, changelog, cargo version number in preparation for release
- Remove panicking behavior on recursive callback calls, add additional error
  variant for recursive callback errors.
2017-12-04 01:47:04 -05:00
kyren 0c644e7136 more reorganization in an attempt to shrink the size of lua.rs 2017-12-04 01:04:12 -05:00
kyren a44b6b5170 Move function and thread into their own modules, auto-formatting 2017-12-04 00:57:39 -05:00