Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
81 lines (77 loc) · 2.58 KB
/
Copy pathmain.cpp
File metadata and controls
81 lines (77 loc) · 2.58 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
#include <autoattach/autoattach.h>
#include <bee/nonstd/filesystem.h>
#include <bee/sys/path.h>
#include <util/log.h>
#ifndef _WIN32
# include <unistd.h>
# define DLLEXPORT __attribute__((visibility("default")))
# define DLLEXPORT_DECLARATION
#else
# include <windows.h>
# define DLLEXPORT __declspec(dllexport)
# define DLLEXPORT_DECLARATION __cdecl
#endif
#include <string>
#include <string_view>
namespace luadebug::autoattach {
static std::string readfile(const fs::path& filename) {
#ifdef _WIN32
FILE* f = _wfopen(filename.c_str(), L"rb");
#else
FILE* f = fopen(filename.c_str(), "rb");
#endif
if (!f) {
return std::string();
}
fseek(f, 0, SEEK_END);
long length = ftell(f);
fseek(f, 0, SEEK_SET);
std::string tmp;
tmp.resize(length);
fread(tmp.data(), 1, length, f);
fclose(f);
return tmp;
}
attach_status attach_lua(lua::state L) {
log::info("attach lua vm entry");
auto r = bee::sys::dll_path();
if (!r) {
log::fatal("dll_path error");
return attach_status::fatal;
}
auto root = (*r).parent_path().parent_path();
auto buf = readfile(root / "script" / "attach.lua");
if (lua::loadbuffer(L, buf.data(), buf.size(), "=(attach.lua)")) {
log::fatal("load attach.lua error: {}", lua::tostring(L, -1));
lua::pop(L, 1);
return attach_status::fatal;
}
lua::call<lua_pushstring>(L, root.generic_u8string().c_str());
#ifdef _WIN32
lua::call<lua_pushstring>(L, std::format("{}", GetCurrentProcessId()).c_str());
#else
lua::call<lua_pushstring>(L, std::format("{}", getpid()).c_str());
#endif
if (lua::pcall(L, 2, 1, 0)) {
/*
这里失败无法调用log::fatal,因为无法知道调试器已经加载到哪一步才失败的。
所以调试器不应该把错误抛到这里。
*/
log::error("{}", lua::tostring(L, -1));
lua::pop(L, 1);
return attach_status::wait;
}
using namespace std::string_view_literals;
bool ok = lua::tostring(L, -1) == "ok"sv;
lua::pop(L, 1);
return ok ? attach_status::success : attach_status::wait;
}
}
extern "C" {
DLLEXPORT void DLLEXPORT_DECLARATION launch() {
luadebug::autoattach::initialize(luadebug::autoattach::work_mode::launch);
}
DLLEXPORT void DLLEXPORT_DECLARATION attach() {
luadebug::autoattach::initialize(luadebug::autoattach::work_mode::attach);
}
}