1use libloading::{Library, Symbol};
2
3use crate::LuaError;
4
5pub type LuaInt = std::os::raw::c_int;
6pub type LuaSize = usize;
7pub type LuaString = *const std::os::raw::c_char;
8
9pub const LUA_GLOBALSINDEX: LuaInt = -10002;
10
11pub const LUA_ERRRUN: LuaInt = 2;
12pub const LUA_ERRSYNTAX: LuaInt = 3;
13pub const LUA_ERRMEM: LuaInt = 4;
14pub const LUA_ERRERR: LuaInt = 5;
15pub const LUA_ERRFILE: LuaInt = 6;
16
17impl LuaError {
18 fn get_error_message(lua_state: LuaState) -> Option<String> {
19 unsafe { lua_state.get_string(-1).map(|str| str.into_owned()) }
20 }
21
22 pub(crate) fn from_lua_state(lua_state: LuaState, lua_int_error_code: LuaInt) -> Self {
23 use LuaError::*;
24 match lua_int_error_code {
25 LUA_ERRMEM => MemoryAllocationError,
26 LUA_ERRERR => ErrorHandlerError,
27 LUA_ERRSYNTAX | LUA_ERRRUN | LUA_ERRFILE => {
28 let msg = LuaError::get_error_message(lua_state);
29 match lua_int_error_code {
30 LUA_ERRSYNTAX => SyntaxError(msg),
31 LUA_ERRRUN => RuntimeError(msg),
32 LUA_ERRFILE => FileError(msg),
33 _ => unreachable!(),
34 }
35 }
36 _ => Unknown(lua_int_error_code),
37 }
38 }
39}
40
41lazy_static::lazy_static! {
42 static ref LUA_SHARED: LuaShared = LuaShared::import();
43}
44struct LuaShared {
45 lual_newstate: Symbol<'static, unsafe extern "C" fn() -> LuaState>,
46 lual_openlibs: Symbol<'static, unsafe extern "C" fn(state: LuaState)>,
47 lual_loadfile: Symbol<'static, unsafe extern "C" fn(state: LuaState, path: LuaString) -> LuaInt>,
48 lual_loadstring: Symbol<'static, unsafe extern "C" fn(state: LuaState, path: LuaString) -> LuaInt>,
49 lua_getfield: Symbol<'static, unsafe extern "C" fn(state: LuaState, index: LuaInt, k: LuaString)>,
50 lua_pushvalue: Symbol<'static, unsafe extern "C" fn(state: LuaState, index: LuaInt)>,
51 lua_pushboolean: Symbol<'static, unsafe extern "C" fn(state: LuaState, bool: LuaInt)>,
52 lua_tolstring: Symbol<'static, unsafe extern "C" fn(state: LuaState, index: LuaInt, out_size: *mut LuaSize) -> LuaString>,
53 lua_pcall: Symbol<'static, unsafe extern "C" fn(state: LuaState, nargs: LuaInt, nresults: LuaInt, errfunc: LuaInt) -> LuaInt>,
54 lua_remove: Symbol<'static, unsafe extern "C" fn(state: LuaState, index: LuaInt)>,
55 lua_close: Symbol<'static, unsafe extern "C" fn(state: LuaState)>,
56
57 #[cfg(test)]
58 lua_gettop: Symbol<'static, unsafe extern "C" fn(state: LuaState) -> LuaInt>,
59
60 #[cfg(test)]
61 lua_type: Symbol<'static, unsafe extern "C" fn(state: LuaState, index: LuaInt) -> LuaInt>,
62
63 #[cfg(test)]
64 lua_typename: Symbol<'static, unsafe extern "C" fn(state: LuaState, lua_type_id: LuaInt) -> LuaString>,
65}
66impl LuaShared {
67 fn import() -> Self {
68 unsafe {
69 let library = Self::find_library();
70 let library = Box::leak(Box::new(library)); macro_rules! find_symbol {
73 ( $symbol:literal ) => {
74 Self::find_symbol(library, concat!($symbol, "\0").as_bytes())
75 };
76 }
77
78 Self {
79 lual_newstate: find_symbol!("luaL_newstate"),
80 lual_openlibs: find_symbol!("luaL_openlibs"),
81 lual_loadfile: find_symbol!("luaL_loadfile"),
82 lual_loadstring: find_symbol!("luaL_loadstring"),
83 lua_getfield: find_symbol!("lua_getfield"),
84 lua_pushvalue: find_symbol!("lua_pushvalue"),
85 lua_pushboolean: find_symbol!("lua_pushboolean"),
86 lua_tolstring: find_symbol!("lua_tolstring"),
87 lua_pcall: find_symbol!("lua_pcall"),
88 lua_remove: find_symbol!("lua_remove"),
89 lua_close: find_symbol!("lua_close"),
90
91 #[cfg(test)]
92 lua_gettop: find_symbol!("lua_gettop"),
93
94 #[cfg(test)]
95 lua_type: find_symbol!("lua_type"),
96
97 #[cfg(test)]
98 lua_typename: find_symbol!("lua_typename"),
99 }
100 }
101 }
102
103 unsafe fn find_symbol<T>(library: &'static Library, name: &[u8]) -> Symbol<'static, T> {
104 match library.get(name) {
105 Ok(symbol) => symbol,
106 Err(err) => panic!("Failed to find symbol \"{}\"\n{:#?}", String::from_utf8_lossy(name), err),
107 }
108 }
109
110 #[cfg(target_os = "windows")]
111 unsafe fn find_library() -> Library {
112 match Library::new("lua_shared.dll") {
113 Ok(library) => library,
114 Err(error) => {
115 eprintln!("Failed to load lua_shared.dll, tier0.dll or vstdlib.dll!");
116
117 #[cfg(target_pointer_width = "32")]
118 eprintln!("Make sure you are using the 32-bit module binaries from the 32-bit branch of Garry's Mod.");
119
120 #[cfg(target_pointer_width = "64")]
121 eprintln!("Make sure you are using the 64-bit module binaries from the 64-bit branch of Garry's Mod.");
122
123 eprintln!("The binaries must be placed in the same directory as the executable, or be in the system's PATH.");
124
125 eprintln!("Executable path: {:?}", std::env::current_exe().ok());
126
127 panic!("{:#?}", error);
128 }
129 }
130 }
131
132 #[cfg(not(target_os = "windows"))]
133 unsafe fn find_library() -> Library {
134 let result_srv = Library::new("lua_shared_srv.so");
135 if let Ok(result_srv) = result_srv {
136 return result_srv;
137 }
138
139 match Library::new("lua_shared.so") {
140 Ok(library) => library,
141 Err(error) => {
142 eprintln!("Failed to load lua_shared_srv.so/lua_shared.so, libtier0_srv.so/libtier0.so or libvstdlib_srv.so/libvstdlib.so!");
143
144 #[cfg(target_pointer_width = "32")]
145 eprintln!("Make sure you are using the 32-bit module binaries from the 32-bit branch of Garry's Mod.");
146
147 #[cfg(target_pointer_width = "64")]
148 eprintln!("Make sure you are using the 64-bit module binaries from the 64-bit branch of Garry's Mod.");
149
150 eprintln!("The binaries must be placed in the same directory as the executable, or be in the system's PATH.");
151 eprintln!("You may need to add the directory of the current executable to the LD_LIBRARY_PATH environment variable.");
152
153 eprintln!("Executable path: {:?}", std::env::current_exe().ok());
154
155 panic!("{:#?}\n{:#?}", error, result_srv.unwrap_err());
156 }
157 }
158 }
159}
160
161#[repr(transparent)]
162#[derive(Clone, Copy, Debug)]
163pub(crate) struct LuaState(*const std::ffi::c_void);
164unsafe impl Send for LuaState {}
165impl LuaState {
166 pub(crate) unsafe fn new() -> Result<Self, LuaError> {
167 let lua = (LUA_SHARED.lual_newstate)();
168 (LUA_SHARED.lual_openlibs)(lua);
169 if lua.is_null() {
170 Err(LuaError::MemoryAllocationError)
171 } else {
172 Ok(lua)
173 }
174 }
175
176 #[inline]
177 #[cfg(test)]
178 pub(crate) unsafe fn get_top(&self) -> LuaInt {
179 (LUA_SHARED.lua_gettop)(*self)
180 }
181
182 #[cfg(test)]
183 pub(crate) unsafe fn get_type(&self, index: LuaInt) -> std::borrow::Cow<'_, str> {
184 let lua_type = (LUA_SHARED.lua_type)(*self, index);
185 let lua_type_str_ptr = (LUA_SHARED.lua_typename)(*self, lua_type);
186 let lua_type_str = std::ffi::CStr::from_ptr(lua_type_str_ptr);
187 lua_type_str.to_string_lossy()
188 }
189
190 pub(crate) unsafe fn remove(&self, index: LuaInt) {
191 (LUA_SHARED.lua_remove)(*self, index)
192 }
193
194 #[inline]
195 pub(crate) unsafe fn push_value(&self, index: LuaInt) {
196 (LUA_SHARED.lua_pushvalue)(*self, index)
197 }
198
199 #[inline]
200 pub(crate) unsafe fn get_field(&self, index: LuaInt, k: LuaString) {
201 (LUA_SHARED.lua_getfield)(*self, index, k)
202 }
203
204 #[inline]
205 pub(crate) unsafe fn push_boolean(&self, boolean: bool) {
206 (LUA_SHARED.lua_pushboolean)(*self, if boolean { 1 } else { 0 })
207 }
208
209 #[inline]
210 pub(crate) unsafe fn pcall(&self, nargs: LuaInt, nresults: LuaInt, errfunc: LuaInt) -> LuaInt {
211 (LUA_SHARED.lua_pcall)(*self, nargs, nresults, errfunc)
212 }
213
214 pub(crate) unsafe fn get_binary_string(&self, index: LuaInt) -> Option<Vec<u8>> {
215 let mut len: usize = 0;
216 let ptr = (LUA_SHARED.lua_tolstring)(*self, index, &mut len);
217
218 if ptr.is_null() {
219 return None;
220 }
221
222 let bytes = std::slice::from_raw_parts(ptr as *const u8, len).to_vec();
223 self.remove(index); Some(bytes)
226 }
227
228 pub(crate) unsafe fn get_string(&self, index: LuaInt) -> Option<std::borrow::Cow<'_, str>> {
229 let mut len: usize = 0;
230 let ptr = (LUA_SHARED.lua_tolstring)(*self, index, &mut len);
231
232 if ptr.is_null() {
233 return None;
234 }
235
236 let bytes = std::slice::from_raw_parts(ptr as *const u8, len);
237 self.remove(index); Some(String::from_utf8_lossy(bytes))
240 }
241
242 pub(crate) unsafe fn load_string(&self, src: LuaString) -> Result<(), LuaError> {
243 let lua_error_code = (LUA_SHARED.lual_loadstring)(*self, src);
244 if lua_error_code == 0 {
245 Ok(())
246 } else {
247 Err(LuaError::from_lua_state(*self, lua_error_code))
248 }
249 }
250
251 pub(crate) unsafe fn load_file(&self, path: LuaString) -> Result<(), LuaError> {
252 let lua_error_code = (LUA_SHARED.lual_loadfile)(*self, path);
253 if lua_error_code == 0 {
254 Ok(())
255 } else {
256 Err(LuaError::from_lua_state(*self, lua_error_code))
257 }
258 }
259
260 #[inline]
261 pub(crate) unsafe fn close(&self) {
262 (LUA_SHARED.lua_close)(*self)
263 }
264}
265impl std::ops::Deref for LuaState {
266 type Target = *const std::ffi::c_void;
267
268 fn deref(&self) -> &Self::Target {
269 &self.0
270 }
271}