forked from lunarmodules/ldoc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathldoc.cpp
More file actions
239 lines (215 loc) · 8.01 KB
/
ldoc.cpp
File metadata and controls
239 lines (215 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/**
* @file ldoc.cpp
* @brief Standalone executable launcher for the LDoc documentation tool.
*
* This launcher embeds the main 'ldoc.lua' script as a hex-encoded byte array
* (generated via CMake) to eliminate the need for an external script file in the
* binary directory.
*
* Key Features:
* - Portable Execution: Resolves the installation prefix dynamically relative
* to the EXE location.
* - Environment Setup: Automatically configures Lua's 'package.path' and
* 'package.cpath' using a custom C++/Lua bridge to find shared libraries and
* modules in the system-independent 'share' and 'lib' directories.
* - Encoding Safety: Uses UTF-8 conversion for Windows WideChar paths to ensure
* compatibility with the Lua interpreter.
*
* -----------------------------------------------------------------------------
* MIT License
*
* Copyright (c) 2026 The OneLuaPro project authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* -----------------------------------------------------------------------------
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <vector>
#ifdef USE_PATHCCH
// newer, but incompatible with Win7 due to missing api-ms-win-core-path-l1-1-0.dll
#include <pathcch.h>
#define MAX_PATH_BUFFER PATHCCH_MAX_CCH
#else
// older, but compatible with Win7
#include <shlwapi.h>
#define MAX_PATH_BUFFER 32768 // same as PATHCCH_MAX_CCH
#endif
#include <lua.hpp>
#include "ldoc_source.h"
#define appName "ldoc.exe"
static std::string WideCharToUTF8(LPCWSTR text) {
if (!text) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);
if (size_needed <= 0) return std::string();
std::vector<char> buffer(size_needed);
WideCharToMultiByte(CP_UTF8, 0, text, -1, buffer.data(), size_needed, NULL, NULL);
return std::string(buffer.data());
}
static const char *setPaths = R"(
function setPaths(basePath, paths, cpaths)
local cleanBase = basePath:gsub("\\+$", "")
local function process(list)
local result = {}
local isRelative = false
for _, v in ipairs(list) do
if v == "<RELATIVE>" then
isRelative = true
else
local entry = v:gsub("^\\+", ""):gsub("\\+$", "")
if isRelative then
table.insert(result, entry)
else
table.insert(result, cleanBase .. "\\" .. entry)
end
end
end
return table.concat(result, ";")
end
package.path = process(paths)
package.cpath = process(cpaths)
end
)";
static const char* LUA_PATHS[] = {
R"(bin\lua\?.lua)",
R"(bin\lua\?\init.lua)",
R"(bin\?.lua)",
R"(bin\?\init.lua)",
"share\\lua\\" LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "\\?.lua",
"share\\lua\\" LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "\\?\\init.lua",
"<RELATIVE>", // Sentinel, relative paths from here
R"(.\?.lua)",
R"(.\?\init.lua)",
NULL // End of List
};
static const char* LUA_CPATHS[] = {
R"(bin\?.dll)",
"lib\\lua\\" LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "\\?.dll",
R"(bin\loadall.dll)",
"<RELATIVE>", // Sentinel, relative paths from here
R"(.\?.dll)",
NULL // End of List
};
static void SetupDeterministicDllResolution(){
/* DETERMINISTIC DLL RESOLUTION FOR ONELUAPRO:
* To keep the '/bin' directory clean, we do not load 'lua.dll' from there.
* Instead, we redirect the search to 'lib/lua/<MAJOR>.<MINOR>/'.
*
* IMPORTANT ARCHITECTURAL NOTE:
* This requires the executable to be linked with the '/DELAYLOAD:lua.dll'
* linker option and against 'delayimp.lib'.
* Delay-loading ensures that the process starts FIRST, allowing this
* code to set the custom search path BEFORE the OS tries to find the DLL.
*
* This guarantees that the interpreter and all DLL-plugins share the exact
* same DLL instance, which is e.g. critical for thread-pool stability. */
wchar_t exePath[MAX_PATH];
if (GetModuleFileNameW(NULL, exePath, MAX_PATH) > 0) {
wchar_t *lastSlash = wcsrchr(exePath, L'\\');
if (lastSlash) {
/* Strip executable name (e.g., 'lua.exe') to get the base '/bin' folder */
*lastSlash = L'\0';
/* Construct the relative path to the versioned library folder.
* The LUAI_TOWSTR macros inject the version numbers from 'lua.h' at
* compile time. */
wchar_t dllDir[MAX_PATH];
_snwprintf(dllDir, MAX_PATH,
L"%s\\..\\lib\\lua\\"
LUAI_TOWSTR(LUA_VERSION_MAJOR_N)
L"."
LUAI_TOWSTR(LUA_VERSION_MINOR_N),exePath);
/* Inject custom search path at the top of the DLL search order.
* Since lua.dll is delay-loaded, it will be successfully
* found in the version-specific sub-directory. */
SetDllDirectoryW(dllDir);
}
}
}
int main(int argc, char** argv) {
// Modity DLL search path
SetupDeterministicDllResolution();
// Determine path, where appName is currently located
WCHAR installPrefix[MAX_PATH_BUFFER];
if (!GetModuleFileNameW(NULL, installPrefix, MAX_PATH_BUFFER)) {
fprintf(stderr, "%s: Could not find executable path.\n", appName);
return 1;
}
// Navigate two levels up from <INSTALL_PREFIX>/bin/ldoc.exe to <INSTALL_PREFIX>
#ifdef USE_PATHCCH
PathCchRemoveFileSpec(installPrefix, PATHCCH_MAX_CCH);
PathCchRemoveFileSpec(installPrefix, PATHCCH_MAX_CCH);
#else
PathRemoveFileSpecW(installPrefix);
PathRemoveFileSpecW(installPrefix);
#endif
std::string utf8Prefix = WideCharToUTF8(installPrefix);
// Create new Lua state
lua_State *L = luaL_newstate();
if (!L) {
fprintf(stderr, "%s: Failed to create Lua state.\n", appName);
return 1;
}
// Open standard libs
luaL_openlibs(L);
// hand-over command-line args to lua by setting global table arg
lua_newtable(L);
for (int i = 0; i < argc; i++) {
lua_pushstring(L, argv[i]);
lua_rawseti(L, -2, i);
}
lua_setglobal(L, "arg");
// Globally register function setPaths()
luaL_dostring(L, setPaths);
// Putsh function on stack
lua_getglobal(L, "setPaths");
// Push 1st arg (the INSTALL_PREFIX)
lua_pushstring(L, utf8Prefix.c_str());
// Push 2nd arg (table of paths for package.path)
lua_newtable(L);
for (int i = 0; LUA_PATHS[i] != NULL; ++i) {
lua_pushstring(L, LUA_PATHS[i]);
lua_rawseti(L, -2, i + 1);
}
// Push 3rd arg (table of paths for package.cpath)
lua_newtable(L);
for (int i = 0; LUA_CPATHS[i] != NULL; ++i) {
lua_pushstring(L, LUA_CPATHS[i]);
lua_rawseti(L, -2, i + 1);
}
// Run function
if (lua_pcall(L, 3, 0, 0) != 0) {
fprintf(stderr, "%s: Error setting paths: %s\n", appName, lua_tostring(L, -1));
}
// Lua state now fully initialized with all standard search paths
// Use loadbuffer, because it works with byte-arrays ans sizes
if (luaL_loadbuffer(L, (const char*)ldoc_source_bytes, ldoc_source_size, "@ldoc.lua") == LUA_OK) {
// Execute the chunk
if (lua_pcall(L, 0, LUA_MULTRET, 0) != LUA_OK) {
fprintf(stderr, "%s: Runtime error: %s\n", appName, lua_tostring(L, -1));
}
}
else {
fprintf(stderr, "%s: Syntax error in embedded code: %s\n", appName, lua_tostring(L, -1));
}
lua_close(L);
return 0;
}