Debian Codegraph @

CorsixTH/Src/main.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 <cstdio>
26 #include <cstdlib>
27 #include <cstring>
28 #include <filesystem>
29 #include <string>
30 #include <string_view>
31
32 #include "lua.hpp"
33 #include "lua_rnc.h"
34 #include "lua_sdl.h"
35 #include "persist_lua.h"
36 #include "th_lua.h"
37
38 #ifdef CORSIX_TH_SEARCH_LOCAL_DATADIRS
39 #include <array>
40
41 #include "../../libs/whereami/whereami.h"
42 #endif
43
44 // Config file checking
45 #ifndef CORSIX_TH_USE_PACK_PRAGMAS
46 #error "config.h is out of date - please rerun CMake"
47 #endif
48 // End of config file checking
49
50 extern "C" {
51 int luaopen_random(lua_State* L);
52 #ifdef CORSIX_TH_LINK_LUA_MODULES
53 int luaopen_lfs(lua_State* L);
54 int luaopen_lpeg(lua_State* L);
55 #endif
56 }
57
58 namespace {
59
60 bool file_exists(const std::filesystem::path& f) {
61 const std::filesystem::file_status st = std::filesystem::status(f);
62 return std::filesystem::exists(st) && !std::filesystem::is_directory(st);
63 }
64
65 std::string search_script_file(lua_State* L) {
66 // 1. Check for --interpreter
67 const int iNArgs = lua_gettop(L);
68 for (int i = 1; i <= iNArgs; ++i) {
69 if (lua_type(L, i) == LUA_TSTRING) {
70 std::string_view interpreterPrefix("--interpreter=");
71 std::string_view arg = lua_tolstring(L, i, nullptr);
72 if (arg.substr(0, interpreterPrefix.size()) == interpreterPrefix)
73 return std::string(arg.substr(interpreterPrefix.size()));
74 }
75 }
76
77 #ifdef CORSIX_TH_SEARCH_LOCAL_DATADIRS
78 // 2. Find CorsixTH.lua in working dir and program dir
79 static constexpr std::array<const char*, 5> asSearchDirs{
80 "./",
81 "CorsixTH/",
82 "Contents/Resources/",
83 "../Resources/",
84 "../share/corsix-th/",
85 };
86 std::string strProgramDir;
87 {
88 int iProgramPathLength = wai_getExecutablePath(nullptr, 0, nullptr);
89 if (iProgramPathLength != 0) {
90 char* sProgramDir = new char[iProgramPathLength + 1];
91 int iProgramDirLength;
92 int iProgramPathLengthReal = wai_getExecutablePath(
93 sProgramDir, iProgramPathLength, &iProgramDirLength);
94 if (iProgramPathLengthReal != iProgramPathLength ||
95 iProgramPathLength <= iProgramDirLength) {
96 if (iProgramPathLengthReal != iProgramPathLength)
97 std::fprintf(stderr,
98 "Path length of CorsixTH binary changed?!?! "
99 "Old: %d, new: %d.\n",
100 iProgramPathLength, iProgramPathLengthReal);
101 else
102 std::fprintf(stderr,
103 "Path to CorsixTH looks like a directory?!?! "
104 "Path is: '%s'.\n",
105 sProgramDir);
106 std::fprintf(stderr, "Please report this incident!\n");
107 std::fflush(stderr);
108 exit(255);
109 }
110 sProgramDir[iProgramDirLength] = '/';
111 sProgramDir[iProgramDirLength + 1] = '\0';
112 strProgramDir = sProgramDir;
113 delete[] sProgramDir;
114 }
115 }
116 for (auto sSearchDir : asSearchDirs) {
117 std::string strPathInWorkingDir =
118 std::string(sSearchDir) + CORSIX_TH_INTERPRETER_NAME;
119 if (file_exists(strPathInWorkingDir)) return strPathInWorkingDir;
120 if (!strProgramDir.empty()) {
121 std::string strPathInProgramDir = strProgramDir + strPathInWorkingDir;
122 if (file_exists(strPathInProgramDir)) return strPathInProgramDir;
123 }
124 }
125 #endif
126
127 // 3. Check CORSIX_TH_INTERPRETER_PATH
128 if (file_exists(CORSIX_TH_INTERPRETER_PATH))
129 return CORSIX_TH_INTERPRETER_PATH;
130
131 return "";
132 }
133
134 } // namespace
135
136 int lua_init_no_eval(lua_State* L) {
137 // assert(_VERSION == LUA_VERSION)
138 size_t iLength;
139 lua_getglobal(L, "_VERSION");
140 const char* sVersion = lua_tolstring(L, -1, &iLength);
141 if (iLength != std::strlen(LUA_VERSION) ||
142 std::strcmp(sVersion, LUA_VERSION) != 0) {
143 lua_pushliteral(
144 L,
145 "Linked against a version of Lua different to the one used "
146 "when compiling.\nPlease recompile CorsixTH against the same "
147 "Lua version it is linked against.");
148 return lua_error(L);
149 }
150 lua_pop(L, 1);
151
152 // math.random* = Mersenne twister variant
153 luaT_cpcall(L, luaopen_random, nullptr);
154
155 // Fill in package.preload table so that calls to require("X") from Lua
156 // will call the appropriate luaopen_X function in C.
157 preload_lua_package(L, "rnc", luaopen_rnc);
158 preload_lua_package(L, "TH", luaopen_th);
159 preload_lua_package(L, "persist", luaopen_persist);
160 preload_lua_package(L, "sdl", luaopen_sdl);
161
162 #ifdef CORSIX_TH_LINK_LUA_MODULES
163 preload_lua_package(L, "lfs", luaopen_lfs);
164 preload_lua_package(L, "lpeg", luaopen_lpeg);
165 #endif
166
167 // require "debug" (Harmless in Lua 5.1, useful in 5.2 for compatibility)
168 luaT_execute(L, "require \"debug\"");
169
170 auto scriptFilePath = search_script_file(L);
171 if (scriptFilePath.empty()) {
172 std::fprintf(stderr,
173 "CorsixTH cannot find CorsixTH.lua. If you want use a custom "
174 "location, specify it by --interpreter=FILE\n");
175 std::fflush(stderr);
176 exit(1);
177 }
178
179 lua_getglobal(L, "assert");
180 lua_getglobal(L, "loadfile");
181 lua_pushstring(L, scriptFilePath.c_str());
182
183 lua_call(L, 1, 2);
184 lua_call(L, 2, 1);
185 lua_insert(L, 1);
186 return lua_gettop(L);
187 }
188
189 int lua_init(lua_State* L) {
190 lua_call(L, lua_init_no_eval(L) - 1, LUA_MULTRET);
191 return lua_gettop(L);
192 }
193
194 int lua_stacktrace(lua_State* L) {
195 // err = tostring(err)
196 lua_settop(L, 1);
197 lua_getglobal(L, "tostring");
198 lua_insert(L, 1);
199 lua_call(L, 1, 1);
200
201 // err = <description> .. err
202 lua_pushliteral(L, "An error has occurred in CorsixTH:\n");
203 lua_insert(L, 1);
204 lua_concat(L, 2);
205
206 // return debug.traceback(err, 2)
207 lua_getglobal(L, "debug");
208 lua_getfield(L, -1, "traceback");
209 lua_pushvalue(L, 1);
210 lua_pushinteger(L, 2);
211 lua_call(L, 2, 1);
212
213 return 1;
214 }
215
216 int lua_panic(lua_State* L) {
217 std::fprintf(stderr,
218 "A Lua error has occurred in CorsixTH outside of protected "
219 "mode!\n");
220 std::fflush(stderr);
221
222 if (lua_type(L, -1) == LUA_TSTRING)
223 std::fprintf(stderr, "%s\n", lua_tostring(L, -1));
224 else
225 std::fprintf(stderr, "%p\n", lua_topointer(L, -1));
226 std::fflush(stderr);
227
228 // A stack trace would be nice, but they cannot be done in a panic.
229
230 return 0;
231 }