-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathVMMain.cpp
More file actions
234 lines (206 loc) · 7.7 KB
/
VMMain.cpp
File metadata and controls
234 lines (206 loc) · 7.7 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
/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2013-2016, Daemon Developers
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Daemon developers nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL DAEMON DEVELOPERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
*/
#include "VMMain.h"
#include "CommonProxies.h"
#include "common/IPC/CommonSyscalls.h"
#include "common/StackTrace.h"
#if defined(__native_client__)
#include <unistd.h>
#endif
IPC::Channel VM::rootChannel;
#ifdef BUILD_VM_NATIVE_EXE
// When using native exe, turn this off if you want to use core dumps (*nix) or attach a debugger
// upon crashing (Windows). Disabling it is like -nocrashhandler for Daemon.
Cvar::Cvar<bool> VM::useNativeExeCrashHandler(
VM_STRING_PREFIX "nativeExeCrashHandler", "catch and log crashes/fatal exceptions in native exe VM", Cvar::NONE, true);
#endif
#ifdef BUILD_VM_IN_PROCESS
// Special exception type used to cleanly exit a thread for in-process VMs
// Using an anonymous namespace so the compiler knows that the exception is
// only used in the current file.
namespace {
class ExitException {};
}
namespace Sys {
extern std::thread::id mainThread;
}
#endif
// Common initialization code for both VM types
static void CommonInit(Sys::OSHandle rootSocket)
{
VM::rootChannel = IPC::Channel(IPC::Socket::FromHandle(rootSocket));
// Send ABI version information, also acts as a sign that the module loaded
Util::Writer writer;
writer.Write<uint32_t>(IPC::ABI_VERSION_DETECTION_ABI_VERSION);
writer.Write<std::string>(IPC::SYSCALL_ABI_VERSION);
VM::rootChannel.SendMsg(writer);
// Start the main loop
while (true) {
Util::Reader reader = VM::rootChannel.RecvMsg();
uint32_t id = reader.Read<uint32_t>();
if (id == IPC::ID_EXIT) {
return;
}
VM::VMHandleSyscall(id, std::move(reader));
}
}
static void SendErrorMsg(Str::StringRef message)
{
// Only try sending an ErrorMsg once
static std::atomic_flag errorEntered;
if (!errorEntered.test_and_set()) {
// Disable checks for sending sync messages when handling async messages.
// At this point we don't really care since this is an error.
VM::rootChannel.canSendSyncMsg = true;
// Try to tell the engine about the error, but ignore errors doing so.
try {
VM::SendMsg<VM::ErrorMsg>(message);
} catch (...) {}
}
}
#ifdef __native_client__
// HACK: when we get a fatal exception in the terminate handler and call abort() to trigger
// a crash dump (as there doesn't seem to be an API for requesting a minidump directly),
// the error message is passed through this variable.
static char realErrorMessage[256];
#endif
void Sys::Error(Str::StringRef message)
{
if (!OnMainThread()) {
// On a non-main thread we can't use IPC, so we can't communicate the error message. Just exit.
// Also note that throwing ExitException would only work as intended on the main thread.
#ifdef __native_client__
// Don't abort, to avoid "nacl_loader.exe has stopped working" popup on Windows
_exit(222);
#else
// Trigger a core dump if enabled. Would give us something to work with since the
// error message can't be shown.
std::abort();
#endif
}
#ifdef __native_client__
if (realErrorMessage[0]) {
message = realErrorMessage;
}
#endif
PrintStackTrace();
SendErrorMsg(message);
#ifdef BUILD_VM_IN_PROCESS
// Then engine will close the root socket when it wants us to exit, which
// will trigger an error in the IPC functions. If we reached this point then
// we try to exit the thread semi-cleanly by throwing an exception.
throw ExitException();
#else
// The SendMsg should never return since the engine should kill our process.
// Just in case it doesn't, exit here.
_exit(255);
#endif
}
#ifdef BUILD_VM_IN_PROCESS
// Entry point called in a new thread inside the existing process
extern "C" DLLEXPORT ALIGN_STACK_FOR_MINGW void vmMain(Sys::OSHandle rootSocket)
{
Sys::mainThread = std::this_thread::get_id();
try {
try {
CommonInit(rootSocket);
} catch (ExitException&) {
return;
} catch (Sys::DropErr& err) {
Sys::Error(err.what());
} catch (std::exception& err) {
Sys::Error("Unhandled exception (%s): %s", typeid(err).name(), err.what());
} catch (...) {
Sys::Error("Unhandled exception of unknown type");
}
} catch (...) {}
}
#else
// The terminate handler feature lets us print the exception message WITHOUT unwinding the stack,
// so that the full stack where the exception arose can be seen in an NaCl crash dump, a
// traditional Unix core dump (for native exe), a debugger, etc.
NORETURN static void TerminateHandler()
{
#ifdef __native_client__
// Using a lambda triggers -Wformat-security...
# define DispatchError(...) snprintf(realErrorMessage, sizeof(realErrorMessage), __VA_ARGS__)
#elif defined(BUILD_VM_NATIVE_EXE)
auto DispatchError = [](const char* msg, const auto&... fmtArgs) {
if (VM::useNativeExeCrashHandler.Get()) {
Sys::Error(msg, fmtArgs...);
} else {
Log::Warn(XSTRING(VM_NAME) " VM terminating:");
Log::Warn(msg, fmtArgs...);
// fall through to abort() for core dump etc.
}
};
#endif
if (Sys::OnMainThread()) {
try {
// A terminate handler is only called if there is an active exception
std::rethrow_exception(std::current_exception());
} catch (std::exception& err) {
DispatchError("Unhandled exception (%s): %s", typeid(err).name(), err.what());
} catch (...) {
DispatchError("Unhandled exception of unknown type");
}
}
std::abort();
}
// Entry point called in a new process
int main(int argc, char** argv)
{
// The socket handle is sent as the first argument
if (argc != 2) {
fprintf(stderr, "This program is not meant to be invoked directly, it must be invoked by the engine's VM loader.\n");
exit(1);
}
char* end;
#ifdef _WIN32
Sys::OSHandle rootSocket = reinterpret_cast<Sys::OSHandle>(static_cast<intptr_t>(strtol(argv[1], &end, 10)));
#else
Sys::OSHandle rootSocket = static_cast<Sys::OSHandle>(strtol(argv[1], &end, 10));
#endif
if (argv[1] == end || *end != '\0') {
fprintf(stderr, "Parameter is not a valid handle number\n");
exit(1);
}
std::set_terminate(TerminateHandler);
// Set up crash handling for this process. This will allow crashes to be
// sent back to the engine and reported to the user.
#ifdef __native_client__
Sys::SetupCrashHandler();
#endif
try {
CommonInit(rootSocket);
} catch (Sys::DropErr& err) {
Sys::Error(err.what());
}
// Other exceptions go to TerminateHandler()
}
#endif