Debian Codegraph @

CorsixTH/Src/th_lua.cpp

raw
1 /*
2 Copyright (c) 2009 Peter "Corsix" Cawley
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "config.h"
24
25 #include <zlib.h>
26 #ifdef WITH_UPDATE_CHECK
27 #include <curl/curl.h>
28 #endif
29
30 #include <cstdio>
31 #include <cstring>
32 #include <stdexcept>
33 #include <string>
34
35 #include "bootstrap.h"
36 #include "lua.hpp"
37 #include "th.h"
38 #include "th_lua.h"
39 #include "th_lua_internal.h"
40
41 const char* update_check_url =
42 "https://corsixth.com/CorsixTH/check-for-updates";
43
44 void lua_register_anims(const lua_register_state* pState);
45 void lua_register_gfx(const lua_register_state* pState);
46 void lua_register_map(const lua_register_state* pState);
47 void lua_register_sound(const lua_register_state* pState);
48 void lua_register_movie(const lua_register_state* pState);
49 void lua_register_strings(const lua_register_state* pState);
50 void lua_register_ui(const lua_register_state* pState);
51 void lua_register_lfs_ext(const lua_register_state* pState);
52 void lua_register_iso_fs(const lua_register_state* pState);
53 void lua_register_midi(const lua_register_state* pState);
54
55 //! Set a field on the environment table of an object
56 void luaT_setenvfield(lua_State* L, int index, const char* k) {
57 lua_getfenv(L, index);
58 lua_pushstring(L, k);
59 lua_pushvalue(L, -3);
60 lua_settable(L, -3);
61 lua_pop(L, 2);
62 }
63
64 //! Get a field from the environment table of an object
65 void luaT_getenvfield(lua_State* L, int index, const char* k) {
66 lua_getfenv(L, index);
67 lua_getfield(L, -1, k);
68 lua_replace(L, -2);
69 }
70
71 #if LUA_VERSION_NUM >= 502
72 void luaT_getfenv52(lua_State* L, int iIndex) {
73 int iType = lua_type(L, iIndex);
74 switch (iType) {
75 case LUA_TUSERDATA:
76 lua_getuservalue(L, iIndex);
77 break;
78 case LUA_TFUNCTION:
79 if (lua_iscfunction(L, iIndex)) {
80 // Our convention: upvalue at #1 is environment
81 if (lua_getupvalue(L, iIndex, 1) == nullptr) lua_pushglobaltable(L);
82 } else {
83 // Language convention: upvalue called _ENV is environment
84 const char* sUpName = nullptr;
85 for (int i = 1; (sUpName = lua_getupvalue(L, iIndex, i)); ++i) {
86 if (std::strcmp(sUpName, "_ENV") == 0)
87 return;
88 else
89 lua_pop(L, 1);
90 }
91 lua_pushglobaltable(L);
92 }
93 break;
94 default:
95 luaL_error(L, "Unable to get environment of a %s in 5.2",
96 lua_typename(L, iType));
97 break;
98 }
99 }
100
101 int luaT_setfenv52(lua_State* L, int iIndex) {
102 int iType = lua_type(L, iIndex);
103 switch (iType) {
104 case LUA_TUSERDATA:
105 lua_setuservalue(L, iIndex);
106 return 1;
107 case LUA_TFUNCTION:
108 if (lua_iscfunction(L, iIndex)) {
109 // Our convention: upvalue at #1 is environment
110 if (lua_setupvalue(L, iIndex, 1) == nullptr) {
111 lua_pop(L, 1);
112 return 0;
113 }
114 return 1;
115 } else {
116 // Language convention: upvalue called _ENV is environment,
117 // which might be shared with other functions.
118 const char* sUpName = nullptr;
119 for (int i = 1; (sUpName = lua_getupvalue(L, iIndex, i)); ++i) {
120 lua_pop(L, 1); // lua_getupvalue puts the value on the
121 // stack, but we just want to replace it
122 if (std::strcmp(sUpName, "_ENV") == 0) {
123 luaL_loadstring(L,
124 "local upv = ... return function() return upv "
125 "end");
126 lua_insert(L, -2);
127 lua_call(L, 1, 1);
128 lua_upvaluejoin(L, iIndex, i, -1, 1);
129 lua_pop(L, 1);
130 return 1;
131 }
132 }
133 lua_pop(L, 1);
134 return 0;
135 }
136 default:
137 return 0;
138 }
139 }
140 #endif
141
142 //! Push a C closure as a callable table
143 void luaT_pushcclosuretable(lua_State* L, lua_CFunction fn, int n) {
144 luaT_pushcclosure(L, fn, n); // .. fn <top
145 lua_createtable(L, 0, 1); // .. fn mt <top
146 lua_pushliteral(L, "__call"); // .. fn mt __call <top
147 lua_pushvalue(L, -3); // .. fn mt __call fn <top
148 lua_settable(L, -3); // .. fn mt <top
149 lua_newtable(L); // .. fn mt t <top
150 lua_replace(L, -3); // .. t mt <top
151 lua_setmetatable(L, -2); // .. t <top
152 }
153
154 //! Check for a string or userdata
155 const uint8_t* luaT_checkfile(lua_State* L, int idx, size_t* pDataLen) {
156 const uint8_t* pData;
157 size_t iLength;
158 if (lua_type(L, idx) == LUA_TUSERDATA) {
159 pData = reinterpret_cast<const uint8_t*>(lua_touserdata(L, idx));
160 iLength = lua_objlen(L, idx);
161 } else {
162 pData =
163 reinterpret_cast<const uint8_t*>(luaL_checklstring(L, idx, &iLength));
164 }
165 if (pDataLen != nullptr) *pDataLen = iLength;
166 return pData;
167 }
168
169 namespace {
170
171 #ifdef WITH_UPDATE_CHECK
172 // https://everything.curl.dev/transfers/callbacks/write.html
173 size_t version_info_write_callback(char* ptr, size_t size, size_t nmemb,
174 void* userdata) {
175 size_t realsize = size * nmemb;
176 std::string* resp = static_cast<std::string*>(userdata);
177 resp->append(ptr, realsize);
178 return realsize;
179 }
180 #endif
181
182 int l_fetch_latest_version_info(lua_State* L) {
183 #ifdef WITH_UPDATE_CHECK
184 CURL* curl = curl_easy_init();
185
186 if (curl == nullptr) {
187 lua_pushnil(L);
188 lua_pushliteral(L, "Could not initialize curl");
189 return 2;
190 }
191
192 curl_easy_setopt(curl, CURLOPT_URL, update_check_url);
193 curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
194 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L);
195 curl_easy_setopt(curl, CURLOPT_MAXFILESIZE, 4096L);
196
197 std::string response;
198 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, version_info_write_callback);
199 curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&response);
200 CURLcode res = curl_easy_perform(curl);
201
202 curl_easy_cleanup(curl);
203
204 if (res != CURLE_OK) {
205 lua_pushnil(L);
206 lua_pushstring(L, curl_easy_strerror(res));
207 return 2;
208 }
209
210 lua_pushstring(L, response.c_str());
211 lua_pushnil(L);
212 return 2;
213 #else
214 lua_pushnil(L);
215 lua_pushliteral(L, "Update check was not enabled at compile time.");
216 return 2;
217 #endif
218 }
219
220 int l_load_strings(lua_State* L) {
221 size_t iDataLength;
222 const uint8_t* pData = luaT_checkfile(L, 1, &iDataLength);
223
224 try {
225 th_string_list oStrings(pData, iDataLength);
226 lua_settop(L, 0);
227 lua_createtable(L, static_cast<int>(oStrings.get_section_count()), 0);
228 for (size_t iSec = 0; iSec < oStrings.get_section_count(); ++iSec) {
229 size_t iCount = oStrings.get_section_size(iSec);
230 lua_createtable(L, static_cast<int>(iCount), 0);
231 for (size_t iStr = 0; iStr < iCount; ++iStr) {
232 lua_pushstring(L, oStrings.get_string(iSec, iStr));
233 lua_rawseti(L, 2, static_cast<int>(iStr + 1));
234 }
235 lua_rawseti(L, 1, static_cast<int>(iSec + 1));
236 }
237 } catch (std::invalid_argument&) {
238 lua_pushboolean(L, 0);
239 }
240 return 1;
241 }
242
243 int get_api_version() {
244 #include "../Lua/api_version.lua" // IWYU pragma: keep
245 }
246
247 int l_get_compile_options(lua_State* L) {
248 lua_settop(L, 0);
249 lua_newtable(L);
250
251 // Report architecture
252 lua_pushliteral(L, CORSIX_TH_ARCH);
253 lua_setfield(L, -2, "arch");
254
255 #ifdef WITH_UPDATE_CHECK
256 lua_pushboolean(L, 1);
257 #else
258 lua_pushboolean(L, 0);
259 #endif
260 lua_setfield(L, -2, "update_check");
261
262 #ifdef CORSIX_TH_USE_FFMPEG
263 lua_pushboolean(L, 1);
264 #else
265 lua_pushboolean(L, 0);
266 #endif
267 lua_setfield(L, -2, "movies");
268
269 #ifdef WITH_MIDI_DEVICE
270 lua_pushboolean(L, 1);
271 #else
272 lua_pushboolean(L, 0);
273 #endif
274 lua_setfield(L, -2, "midi_device");
275
276 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
277 lua_getfield(L, -1, "jit");
278 if (lua_type(L, -1) == LUA_TNIL) {
279 lua_replace(L, -2);
280 } else {
281 lua_getfield(L, -1, "version");
282 lua_replace(L, -3);
283 lua_pop(L, 1);
284 }
285 lua_setfield(L, -2, "jit");
286
287 // Report operating system
288 lua_pushliteral(L, CORSIX_TH_OS);
289 lua_setfield(L, -2, "os");
290
291 lua_pushinteger(L, get_api_version());
292 lua_setfield(L, -2, "api_version");
293
294 #ifdef CORSIX_TH_FONT
295 // Set default value of font file
296 lua_pushliteral(L, CORSIX_TH_FONT);
297 lua_setfield(L, -2, "font");
298 #endif
299
300 return 1;
301 }
302
303 int l_crc32(lua_State* L) {
304 size_t iDataLen;
305 const uint8_t* pData = luaT_checkfile(L, 1, &iDataLen);
306
307 lua_pushinteger(L, static_cast<lua_Integer>(crc32(
308 0L, pData, static_cast<unsigned int>(iDataLen))));
309
310 return 1;
311 }
312
313 } // namespace
314
315 void luaT_setclosure(const lua_register_state* pState, lua_CFunction fn,
316 int iUps) {
317 luaT_pushcclosure(pState->L, fn, iUps);
318 }
319
320 int luaopen_th(lua_State* L) {
321 lua_settop(L, 0);
322 lua_checkstack(L, 16 + static_cast<int>(lua_metatable::count));
323
324 lua_register_state oState;
325 const lua_register_state* pState = &oState;
326 oState.L = L;
327 for (int i = 0; i < static_cast<int>(lua_metatable::count); ++i) {
328 lua_createtable(L, 0, 5);
329 oState.metatables[i] = lua_gettop(L);
330 }
331 lua_createtable(L, 0, lua_gettop(L));
332 oState.main_table = lua_gettop(L);
333 oState.top = lua_gettop(L);
334
335 // Misc. functions
336 lua_settop(L, oState.top);
337 add_lua_function(pState, l_load_strings, "LoadStrings");
338 add_lua_function(pState, l_get_compile_options, "GetCompileOptions");
339 add_lua_function(pState, bootstrap_lua_resources, "GetBuiltinFont");
340 add_lua_function(pState, l_fetch_latest_version_info,
341 "FetchLatestVersionInfo");
342 add_lua_function(pState, l_crc32, "CRC32File");
343
344 // Classes
345 lua_register_map(pState);
346 lua_register_gfx(pState);
347 lua_register_anims(pState);
348 lua_register_sound(pState);
349 lua_register_movie(pState);
350 lua_register_strings(pState);
351 lua_register_ui(pState);
352 lua_register_lfs_ext(pState);
353 lua_register_iso_fs(pState);
354 lua_register_midi(pState);
355
356 lua_settop(L, oState.main_table);
357 return 1;
358 }
359
360 void luaT_execute_loadstring(lua_State* L, const char* sLuaString) {
361 static const int iRegistryCacheIndex = 7;
362 lua_rawgeti(L, LUA_REGISTRYINDEX, iRegistryCacheIndex);
363 if (lua_isnil(L, -1)) {
364 // Cache not yet created - create it.
365 lua_pop(L, 1);
366 lua_getglobal(L, "setmetatable");
367 if (lua_isnil(L, -1)) {
368 // Base library not yet loaded - fallback to simple
369 // uncached loadstring
370 lua_pop(L, 1);
371 if (luaL_loadstring(L, sLuaString)) lua_error(L);
372 }
373 lua_pop(L, 1);
374 #if LUA_VERSION_NUM >= 502
375 luaL_loadstring(L,
376 "local assert, load = assert, load\n"
377 "return setmetatable({}, {__mode = [[v]], \n"
378 "__index = function(t, k)\n"
379 "local v = assert(load(k))\n"
380 "t[k] = v\n"
381 "return v\n"
382 "end})");
383 #else
384 luaL_loadstring(L,
385 "local assert, loadstring = assert, loadstring\n"
386 "return setmetatable({}, {__mode = [[v]], \n"
387 "__index = function(t, k)\n"
388 "local v = assert(loadstring(k))\n"
389 "t[k] = v\n"
390 "return v\n"
391 "end})");
392 #endif
393 lua_call(L, 0, 1);
394 lua_pushvalue(L, -1);
395 lua_rawseti(L, LUA_REGISTRYINDEX, iRegistryCacheIndex);
396 }
397 lua_getfield(L, -1, sLuaString);
398 lua_replace(L, -2);
399 }
400
401 void luaT_execute(lua_State* L, const char* sLuaString) {
402 luaT_execute_loadstring(L, sLuaString);
403 lua_call(L, 0, LUA_MULTRET);
404 }
405
406 void preload_lua_package(lua_State* L, const char* name, lua_CFunction fn) {
407 luaT_execute(
408 L, std::string("package.preload.").append(name).append(" = ...").c_str(),
409 fn);
410 }
411
412 void luaT_push(lua_State* L, lua_CFunction f) { luaT_pushcfunction(L, f); }
413
414 void luaT_push(lua_State* L, int i) { lua_pushinteger(L, (lua_Integer)i); }
415
416 void luaT_push(lua_State* L, const char* s) { lua_pushstring(L, s); }
417
418 void luaT_pushtablebool(lua_State* L, const char* k, bool v) {
419 lua_pushstring(L, k);
420 lua_pushboolean(L, v);
421 lua_settable(L, -3);
422 }
423
424 void luaT_printvalue(lua_State* L, int idx) {
425 int t = lua_type(L, idx);
426 switch (t) {
427 case LUA_TSTRING: /* strings */
428 std::printf("string: '%s'\n", lua_tostring(L, idx));
429 break;
430 case LUA_TBOOLEAN: /* booleans */
431 std::printf("boolean %s\n", lua_toboolean(L, idx) ? "true" : "false");
432 break;
433 case LUA_TNUMBER: /* numbers */
434 std::printf("number: %g\n", lua_tonumber(L, idx));
435 break;
436 default: /* other values */
437 std::printf("%s: %p\n", lua_typename(L, t), lua_topointer(L, idx));
438 break;
439 }
440 }
441
442 void luaT_printstack(lua_State* L) {
443 int i;
444 int top = lua_gettop(L);
445
446 std::printf("total items in stack %d\n", top);
447
448 for (i = 1; i <= top; i++) { /* repeat for each level */
449 std::printf("(%d) ", i);
450 luaT_printvalue(L, i);
451 }
452 std::printf("\n"); /* end the listing */
453 }
454
455 void luaT_printrawtable(lua_State* L, int idx) {
456 /* table is in the stack at index 't' */
457 lua_pushnil(L); /* first key */
458 while (lua_next(L, idx) != 0) {
459 /* uses 'key' (at index -2) and 'value' (at index -1) */
460 std::printf("key: ");
461 luaT_printvalue(L, -2);
462 std::printf("value: ");
463 luaT_printvalue(L, -1);
464 /* removes 'value'; keeps 'key' for next iteration */
465 lua_pop(L, 1);
466 }
467 }