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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
|
/**
* Copyright (C) 2015 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/scripting/mozjs/proxyscope.h"
#include "mongo/db/client.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/service_context.h"
#include "mongo/platform/decimal128.h"
#include "mongo/scripting/mozjs/implscope.h"
#include "mongo/util/quick_exit.h"
namespace mongo {
namespace mozjs {
MozJSProxyScope::MozJSProxyScope(MozJSScriptEngine* engine)
: _engine(engine),
_implScope(nullptr),
_mutex(),
_state(State::Idle),
_status(Status::OK()),
_condvar(),
// Despite calling PR_CreateThread, we're actually using our own
// implementation of PosixNSPR.cpp in this directory. So these threads
// are actually hosted on top of stdx::threads and most of the flags
// don't matter.
_thread(PR_CreateThread(PR_USER_THREAD,
implThread,
this,
PR_PRIORITY_NORMAL,
PR_LOCAL_THREAD,
PR_JOINABLE_THREAD,
MozJSImplScope::kMaxStackBytes)) {
// Test the child on startup to make sure it's awake and that the
// implementation scope sucessfully constructed.
try {
runOnImplThread([] {});
} catch (...) {
shutdownThread();
throw;
}
}
MozJSProxyScope::~MozJSProxyScope() {
DESTRUCTOR_GUARD(kill(); shutdownThread(););
}
void MozJSProxyScope::init(const BSONObj* data) {
run([&] { _implScope->init(data); });
}
void MozJSProxyScope::reset() {
run([&] { _implScope->reset(); });
}
bool MozJSProxyScope::isKillPending() const {
return _implScope->isKillPending();
}
void MozJSProxyScope::registerOperation(OperationContext* txn) {
run([&] { _implScope->registerOperation(txn); });
}
void MozJSProxyScope::unregisterOperation() {
run([&] { _implScope->unregisterOperation(); });
}
void MozJSProxyScope::localConnectForDbEval(OperationContext* txn, const char* dbName) {
run([&] { _implScope->localConnectForDbEval(txn, dbName); });
}
void MozJSProxyScope::externalSetup() {
run([&] { _implScope->externalSetup(); });
}
std::string MozJSProxyScope::getError() {
std::string out;
run([&] { out = _implScope->getError(); });
return out;
}
/**
* This is an artifact of how out of memory errors were communicated in V8. We
* just throw out of memory errors from spidermonkey when we get them, rather
* than setting a flag and having to pick them up here.
*/
bool MozJSProxyScope::hasOutOfMemoryException() {
return false;
}
void MozJSProxyScope::gc() {
_implScope->gc();
}
void MozJSProxyScope::advanceGeneration() {
run([&] { _implScope->advanceGeneration(); });
}
double MozJSProxyScope::getNumber(const char* field) {
double out;
run([&] { out = _implScope->getNumber(field); });
return out;
}
int MozJSProxyScope::getNumberInt(const char* field) {
int out;
run([&] { out = _implScope->getNumberInt(field); });
return out;
}
long long MozJSProxyScope::getNumberLongLong(const char* field) {
long long out;
run([&] { out = _implScope->getNumberLongLong(field); });
return out;
}
Decimal128 MozJSProxyScope::getNumberDecimal(const char* field) {
Decimal128 out;
run([&] { out = _implScope->getNumberDecimal(field); });
return out;
}
std::string MozJSProxyScope::getString(const char* field) {
std::string out;
run([&] { out = _implScope->getString(field); });
return out;
}
bool MozJSProxyScope::getBoolean(const char* field) {
bool out;
run([&] { out = _implScope->getBoolean(field); });
return out;
}
BSONObj MozJSProxyScope::getObject(const char* field) {
BSONObj out;
run([&] { out = _implScope->getObject(field); });
return out;
}
void MozJSProxyScope::setNumber(const char* field, double val) {
run([&] { _implScope->setNumber(field, val); });
}
void MozJSProxyScope::setString(const char* field, StringData val) {
run([&] { _implScope->setString(field, val); });
}
void MozJSProxyScope::setBoolean(const char* field, bool val) {
run([&] { _implScope->setBoolean(field, val); });
}
void MozJSProxyScope::setElement(const char* field, const BSONElement& e, const BSONObj& parent) {
run([&] { _implScope->setElement(field, e, parent); });
}
void MozJSProxyScope::setObject(const char* field, const BSONObj& obj, bool readOnly) {
run([&] { _implScope->setObject(field, obj, readOnly); });
}
void MozJSProxyScope::setFunction(const char* field, const char* code) {
run([&] { _implScope->setFunction(field, code); });
}
int MozJSProxyScope::type(const char* field) {
int out;
run([&] { out = _implScope->type(field); });
return out;
}
void MozJSProxyScope::rename(const char* from, const char* to) {
run([&] { _implScope->rename(from, to); });
}
int MozJSProxyScope::invoke(ScriptingFunction func,
const BSONObj* argsObject,
const BSONObj* recv,
int timeoutMs,
bool ignoreReturn,
bool readOnlyArgs,
bool readOnlyRecv) {
int out;
run([&] {
out = _implScope->invoke(
func, argsObject, recv, timeoutMs, ignoreReturn, readOnlyArgs, readOnlyRecv);
});
return out;
}
bool MozJSProxyScope::exec(StringData code,
const std::string& name,
bool printResult,
bool reportError,
bool assertOnError,
int timeoutMs) {
bool out;
run([&] {
out = _implScope->exec(code, name, printResult, reportError, assertOnError, timeoutMs);
});
return out;
}
void MozJSProxyScope::injectNative(const char* field, NativeFunction func, void* data) {
run([&] { _implScope->injectNative(field, func, data); });
}
ScriptingFunction MozJSProxyScope::_createFunction(const char* raw,
ScriptingFunction functionNumber) {
ScriptingFunction out;
run([&] { out = _implScope->_createFunction(raw, functionNumber); });
return out;
}
OperationContext* MozJSProxyScope::getOpContext() const {
return _implScope->getOpContext();
}
void MozJSProxyScope::kill() {
_implScope->kill();
}
/**
* Invokes a function on the implementation thread
*
* It does this by serializing the invocation through a stdx::function and
* capturing any exceptions through _status.
*
* We transition:
*
* Idle -> ProxyRequest -> ImplResponse -> Idle
*/
template <typename Closure>
void MozJSProxyScope::run(Closure&& closure) {
// We can end up calling functions on the proxy scope from the impl thread
// when callbacks from javascript have a handle to the proxy scope and call
// methods on it from there. If we're on the same thread, it's safe to
// simply call back in, so let's do that.
if (_thread == PR_GetCurrentThread()) {
return closure();
}
runOnImplThread(std::move(closure));
}
void MozJSProxyScope::runOnImplThread(stdx::function<void()> f) {
stdx::unique_lock<stdx::mutex> lk(_mutex);
_function = std::move(f);
invariant(_state == State::Idle);
_state = State::ProxyRequest;
_condvar.notify_one();
_condvar.wait(lk, [this] { return _state == State::ImplResponse; });
_state = State::Idle;
// Clear the _status state and throw it if necessary
auto status = std::move(_status);
// Can validate the status outside the lock
lk.unlock();
uassertStatusOK(status);
}
void MozJSProxyScope::shutdownThread() {
{
stdx::lock_guard<stdx::mutex> lk(_mutex);
invariant(_state == State::Idle);
_state = State::Shutdown;
}
_condvar.notify_one();
PR_JoinThread(_thread);
}
/**
* The main loop for the implementation thread
*
* This owns the actual implementation scope (which needs to be created on this
* child thread) and has essentially two transition paths:
*
* Standard: ProxyRequest -> ImplResponse
* Invoke _function. Serialize exceptions to _status.
*
* Shutdown: Shutdown -> _
* break out of the loop and return.
*/
void MozJSProxyScope::implThread(void* arg) {
auto proxy = static_cast<MozJSProxyScope*>(arg);
if (hasGlobalServiceContext())
Client::initThread("js");
std::unique_ptr<MozJSImplScope> scope;
// This will leave _status set for the first noop runOnImplThread(), which
// captures the startup exception that way
try {
scope.reset(new MozJSImplScope(proxy->_engine));
proxy->_implScope = scope.get();
} catch (...) {
proxy->_status = exceptionToStatus();
}
while (true) {
stdx::unique_lock<stdx::mutex> lk(proxy->_mutex);
proxy->_condvar.wait(lk,
[proxy] {
return proxy->_state == State::ProxyRequest ||
proxy->_state == State::Shutdown;
});
if (proxy->_state == State::Shutdown)
break;
try {
proxy->_function();
} catch (...) {
proxy->_status = exceptionToStatus();
}
int exitCode;
if (proxy->_implScope && proxy->_implScope->getQuickExit(&exitCode)) {
scope.reset();
quickExit(exitCode);
}
proxy->_state = State::ImplResponse;
proxy->_condvar.notify_one();
}
}
} // namespace mozjs
} // namespace mongo
|