Skip to content

Commit 0de7cd1

Browse files
committed
Don't move or wrap ffi::lua_Debug struct when inspecting stack
This can cause a crash if `ffi::lua_Debug` changed between `lua_getstack` and `lua_getinfo` calls. Fixes #610
1 parent 58953e5 commit 0de7cd1

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

src/hook.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
use std::borrow::Cow;
2-
use std::cell::UnsafeCell;
32
use std::ops::Deref;
43
#[cfg(not(feature = "luau"))]
54
use std::ops::{BitOr, BitOrAssign};
@@ -51,14 +50,18 @@ impl<'a> Debug<'a> {
5150
pub(crate) fn new(lua: &'a RawLua, ar: *mut lua_Debug) -> Self {
5251
Debug {
5352
lua: EitherLua::Borrowed(lua),
54-
ar: ActivationRecord::Borrowed(ar),
53+
ar: ActivationRecord(ar, false),
5554
}
5655
}
5756

58-
pub(crate) fn new_owned(guard: ReentrantMutexGuard<'a, RawLua>, _level: c_int, ar: lua_Debug) -> Self {
57+
pub(crate) fn new_owned(
58+
guard: ReentrantMutexGuard<'a, RawLua>,
59+
_level: c_int,
60+
ar: Box<lua_Debug>,
61+
) -> Self {
5962
Debug {
6063
lua: EitherLua::Owned(guard),
61-
ar: ActivationRecord::Owned(UnsafeCell::new(ar)),
64+
ar: ActivationRecord(Box::into_raw(ar), true),
6265
#[cfg(feature = "luau")]
6366
level: _level,
6467
}
@@ -207,19 +210,19 @@ impl<'a> Debug<'a> {
207210
}
208211
}
209212

210-
enum ActivationRecord {
211-
#[cfg(not(feature = "luau"))]
212-
Borrowed(*mut lua_Debug),
213-
Owned(UnsafeCell<lua_Debug>),
214-
}
213+
struct ActivationRecord(*mut lua_Debug, bool);
215214

216215
impl ActivationRecord {
217216
#[inline]
218217
fn get(&self) -> *mut lua_Debug {
219-
match self {
220-
#[cfg(not(feature = "luau"))]
221-
ActivationRecord::Borrowed(x) => *x,
222-
ActivationRecord::Owned(x) => x.get(),
218+
self.0
219+
}
220+
}
221+
222+
impl Drop for ActivationRecord {
223+
fn drop(&mut self) {
224+
if self.1 {
225+
drop(unsafe { Box::from_raw(self.0) });
223226
}
224227
}
225228
}

src/state.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -880,14 +880,14 @@ impl Lua {
880880
pub fn inspect_stack(&self, level: usize) -> Option<Debug<'_>> {
881881
let lua = self.lock();
882882
unsafe {
883-
let mut ar: ffi::lua_Debug = mem::zeroed();
883+
let mut ar = Box::new(mem::zeroed::<ffi::lua_Debug>());
884884
let level = level as c_int;
885885
#[cfg(not(feature = "luau"))]
886-
if ffi::lua_getstack(lua.state(), level, &mut ar) == 0 {
886+
if ffi::lua_getstack(lua.state(), level, &mut *ar) == 0 {
887887
return None;
888888
}
889889
#[cfg(feature = "luau")]
890-
if ffi::lua_getinfo(lua.state(), level, cstr!(""), &mut ar) == 0 {
890+
if ffi::lua_getinfo(lua.state(), level, cstr!(""), &mut *ar) == 0 {
891891
return None;
892892
}
893893
Some(Debug::new_owned(lua, level, ar))

0 commit comments

Comments
 (0)