summaryrefslogtreecommitdiff
path: root/src/mongo/scripting/mozjs/wraptype.h
blob: 4f85802d4ec47f011332e32825dafec64e852924 (plain)
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/**
 * 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.
 */

#pragma once

#include <cstddef>
#include <jsapi.h>
#include <type_traits>

#include "mongo/scripting/mozjs/base.h"
#include "mongo/scripting/mozjs/exception.h"
#include "mongo/scripting/mozjs/objectwrapper.h"
#include "mongo/util/assert_util.h"

// The purpose of this class is to take in specially crafted types and generate
// a wrapper which installs the type, along with any useful life cycle methods
// and free functions that might be associated with it. The template magic in
// here, along with some useful macros, hides a lot of the implementation
// complexity of exposing C++ code into javascript. Most prominently, we have
// to wrap every function that can be called from javascript to prevent any C++
// exceptions from leaking out. We do this, with template and macro based
// codegen, and turn mongo exceptions into instances of Status, then convert
// those into javascript exceptions before returning. That allows all consumers
// of this library to throw exceptions freely, with the understanding that
// they'll be visible in javascript. Javascript exceptions are trapped at the
// top level and converted back to mongo exceptions by an error handler on
// ImplScope.

// MONGO_*_JS_FUNCTION_* macros are public and allow wrapped types to install
// their own functions on types and into the global scope
#define MONGO_DECLARE_JS_FUNCTION(function)                 \
    struct function {                                       \
        static const char* name() {                         \
            return #function;                               \
        }                                                   \
        static void call(JSContext* cx, JS::CallArgs args); \
    };

#define MONGO_ATTACH_JS_FUNCTION_WITH_FLAGS(name, flags) \
    JS_FS(#name, smUtils::wrapFunction<Functions::name>, 0, flags)

#define MONGO_ATTACH_JS_FUNCTION(name) MONGO_ATTACH_JS_FUNCTION_WITH_FLAGS(name, 0)

#define MONGO_ATTACH_JS_CONSTRAINED_METHOD(name, ...)                                              \
    {                                                                                              \
        #name, {smUtils::wrapConstrainedMethod < Functions::name, false, __VA_ARGS__ >, nullptr }, \
                0,                                                                                 \
                0,                                                                                 \
                nullptr                                                                            \
    }

#define MONGO_ATTACH_JS_CONSTRAINED_METHOD_NO_PROTO(name, ...)                                    \
    {                                                                                             \
        #name, {smUtils::wrapConstrainedMethod < Functions::name, true, __VA_ARGS__ >, nullptr }, \
                0,                                                                                \
                0,                                                                                \
                nullptr                                                                           \
    }

namespace mongo {
namespace mozjs {

namespace smUtils {

template <typename T>
bool wrapFunction(JSContext* cx, unsigned argc, JS::Value* vp) {
    try {
        JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
        T::call(cx, args);
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
}

// Now all the spidermonkey type methods
template <typename T>
bool addProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::HandleValue v) {
    try {
        T::addProperty(cx, obj, id, v);
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

template <typename T>
bool call(JSContext* cx, unsigned argc, JS::Value* vp) {
    try {
        T::call(cx, JS::CallArgsFromVp(argc, vp));
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

template <typename T>
bool construct(JSContext* cx, unsigned argc, JS::Value* vp) {
    try {
        T::construct(cx, JS::CallArgsFromVp(argc, vp));
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

template <typename T>
bool delProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::ObjectOpResult& result) {
    try {
        T::delProperty(cx, obj, id, result);
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

template <typename T>
bool enumerate(JSContext* cx,
               JS::HandleObject obj,
               JS::AutoIdVector& properties,
               bool enumerableOnly) {
    try {
        T::enumerate(cx, obj, properties, enumerableOnly);
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

template <typename T>
bool getProperty(JSContext* cx, JS::HandleObject obj, JS::HandleId id, JS::MutableHandleValue vp) {
    if (JSID_IS_SYMBOL(id)) {
        // Just default to the SpiderMonkey's standard implementations for Symbol methods
        vp.setUndefined();
        return true;
    }

    try {
        T::getProperty(cx, obj, id, vp);
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

template <typename T>
bool hasInstance(JSContext* cx, JS::HandleObject obj, JS::MutableHandleValue vp, bool* bp) {
    try {
        T::hasInstance(cx, obj, vp, bp);
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

template <typename T>
bool setProperty(JSContext* cx,
                 JS::HandleObject obj,
                 JS::HandleId id,
                 JS::MutableHandleValue vp,
                 JS::ObjectOpResult& result) {
    try {
        T::setProperty(cx, obj, id, vp, result);
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

template <typename T>
bool resolve(JSContext* cx, JS::HandleObject obj, JS::HandleId id, bool* resolvedp) {
    if (JSID_IS_SYMBOL(id)) {
        // Just default to the SpiderMonkey's standard implementations for Symbol methods
        *resolvedp = false;
        return true;
    }

    try {
        T::resolve(cx, obj, id, resolvedp);
        return true;
    } catch (...) {
        mongoToJSException(cx);
        return false;
    }
};

}  // namespace smUtils

template <typename T>
class WrapType : public T {
public:
    WrapType(JSContext* context)
        : _context(context),
          _proto(),
          _constructor(),
          _jsclass({T::className,
                    T::classFlags,
                    T::addProperty != BaseInfo::addProperty ? smUtils::addProperty<T> : nullptr,
                    T::delProperty != BaseInfo::delProperty ? smUtils::delProperty<T> : nullptr,
                    T::getProperty != BaseInfo::getProperty ? smUtils::getProperty<T> : nullptr,
                    T::setProperty != BaseInfo::setProperty ? smUtils::setProperty<T> : nullptr,
                    // We don't use the regular enumerate because we want the fancy new one
                    nullptr,
                    T::resolve != BaseInfo::resolve ? smUtils::resolve<T> : nullptr,
                    T::mayResolve != BaseInfo::mayResolve ? T::mayResolve : nullptr,
                    T::finalize != BaseInfo::finalize ? T::finalize : nullptr,
                    T::call != BaseInfo::call ? smUtils::call<T> : nullptr,
                    T::hasInstance != BaseInfo::hasInstance ? smUtils::hasInstance<T> : nullptr,
                    T::construct != BaseInfo::construct ? smUtils::construct<T> : nullptr,
                    nullptr}) {
        _installEnumerate(T::enumerate != BaseInfo::enumerate ? smUtils::enumerate<T> : nullptr);

        // The global object is different.  We need it for basic setup
        // before the other types are installed.  Might as well just do it
        // in the constructor.
        if (T::classFlags & JSCLASS_GLOBAL_FLAGS) {
            _jsclass.trace = JS_GlobalObjectTraceHook;

            JS::RootedObject proto(_context);

            JSAutoRequest ar(_context);

            _proto.init(_context,
                        _assertPtr(JS_NewGlobalObject(
                            _context, &_jsclass, nullptr, JS::DontFireOnNewGlobalHook)));

            JSAutoCompartment ac(_context, _proto);
            _installFunctions(_proto, T::freeFunctions);
        }
    }

    ~WrapType() {
        // Persistent globals don't RAII, you have to reset() them manually
        _proto.reset();
        _constructor.reset();
    }

    void install(JS::HandleObject global) {
        switch (static_cast<InstallType>(T::installType)) {
            case InstallType::Global:
                _installGlobal(global);
                break;
            case InstallType::Private:
                _installPrivate(global);
                break;
            case InstallType::OverNative:
                _installOverNative(global);
                break;
        }
    }

    /**
     * newObject methods don't invoke the constructor.  So they're good for
     * types without a constructor or inside the constructor
     */
    void newObject(JS::MutableHandleObject out) {
        out.set(_assertPtr(JS_NewObjectWithGivenProto(_context, &_jsclass, _proto)));
    }

    void newObject(JS::MutableHandleValue out) {
        JS::RootedObject obj(_context);
        newObject(&obj);

        out.setObjectOrNull(obj);
    }

    void newObjectWithProto(JS::MutableHandleObject out, JS::HandleObject proto) {
        out.set(_assertPtr(JS_NewObjectWithGivenProto(_context, &_jsclass, proto)));
    }

    void newObjectWithProto(JS::MutableHandleValue out, JS::HandleObject proto) {
        JS::RootedObject obj(_context);
        newObjectWithProto(&obj, proto);

        out.setObjectOrNull(obj);
    }

    /**
     * newInstance calls the constructor, a la new Type() in js
     */
    void newInstance(JS::MutableHandleObject out) {
        dassert(T::installType == InstallType::OverNative || T::construct != BaseInfo::construct);

        JS::AutoValueVector args(_context);

        newInstance(args, out);
    }

    void newInstance(const JS::HandleValueArray& args, JS::MutableHandleObject out) {
        dassert(T::installType == InstallType::OverNative || T::construct != BaseInfo::construct);

        out.set(_assertPtr(JS_New(
            _context, T::installType == InstallType::OverNative ? _constructor : _proto, args)));
    }

    void newInstance(JS::MutableHandleValue out) {
        dassert(T::installType == InstallType::OverNative || T::construct != BaseInfo::construct);

        JS::AutoValueVector args(_context);

        newInstance(args, out);
    }

    void newInstance(const JS::HandleValueArray& args, JS::MutableHandleValue out) {
        dassert(T::installType == InstallType::OverNative || T::construct != BaseInfo::construct);

        out.setObjectOrNull(_assertPtr(JS_New(
            _context, T::installType == InstallType::OverNative ? _constructor : _proto, args)));
    }

    // instanceOf doesn't go up the prototype tree.  It's a lower level more specific match
    bool instanceOf(JS::HandleObject obj) {
        return JS_InstanceOf(_context, obj, &_jsclass, nullptr);
    }

    bool instanceOf(JS::HandleValue value) {
        if (!value.isObject())
            return false;

        JS::RootedObject obj(_context, value.toObjectOrNull());

        return instanceOf(obj);
    }

    const JSClass* getJSClass() const {
        return &_jsclass;
    }

    JS::HandleObject getProto() const {
        return _proto;
    }

    JS::HandleObject getCtor() const {
        return _constructor;
    }

private:
    /**
     * Use this if you want your types installed visibly in the global scope
     */
    void _installGlobal(JS::HandleObject global) {
        JS::RootedObject parent(_context);
        _inheritFrom(T::inheritFrom, global, &parent);

        _proto.init(_context,
                    _assertPtr(JS_InitClass(
                        _context,
                        global,
                        parent,
                        &_jsclass,
                        T::construct != BaseInfo::construct ? smUtils::construct<T> : nullptr,
                        0,
                        nullptr,
                        T::methods,
                        nullptr,
                        nullptr)));

        _installFunctions(global, T::freeFunctions);
        _postInstall(global, T::postInstall);
    }

    // Use this if you want your types installed, but not visible in the
    // global scope
    void _installPrivate(JS::HandleObject global) {
        dassert(T::construct == BaseInfo::construct);

        JS::RootedObject parent(_context);
        _inheritFrom(T::inheritFrom, global, &parent);

        // See newObject() for why we have to do this dance with the explicit
        // SetPrototype
        _proto.init(_context, _assertPtr(JS_NewObject(_context, &_jsclass)));
        if (parent.get() && !JS_SetPrototype(_context, _proto, parent))
            throwCurrentJSException(
                _context, ErrorCodes::JSInterpreterFailure, "Failed to set prototype");

        _installFunctions(_proto, T::methods);
        _installFunctions(global, T::freeFunctions);

        _installConstructor(T::construct != BaseInfo::construct ? smUtils::construct<T> : nullptr);

        _postInstall(global, T::postInstall);
    }

    // Use this to attach things to types that we don't provide like
    // Object, or Array
    void _installOverNative(JS::HandleObject global) {
        dassert(T::addProperty == BaseInfo::addProperty);
        dassert(T::call == BaseInfo::call);
        dassert(T::construct == BaseInfo::construct);
        dassert(T::delProperty == BaseInfo::delProperty);
        dassert(T::enumerate == BaseInfo::enumerate);
        dassert(T::finalize == BaseInfo::finalize);
        dassert(T::getProperty == BaseInfo::getProperty);
        dassert(T::hasInstance == BaseInfo::hasInstance);
        dassert(T::resolve == BaseInfo::resolve);
        dassert(T::setProperty == BaseInfo::setProperty);

        JS::RootedValue value(_context);
        if (!JS_GetProperty(_context, global, T::className, &value))
            throwCurrentJSException(
                _context, ErrorCodes::JSInterpreterFailure, "Couldn't get className property");

        if (!value.isObject())
            uasserted(ErrorCodes::BadValue, "className isn't object");

        JS::RootedObject classNameObject(_context);
        if (!JS_ValueToObject(_context, value, &classNameObject))
            throwCurrentJSException(_context,
                                    ErrorCodes::JSInterpreterFailure,
                                    "Couldn't convert className property into an object.");

        JS::RootedValue protoValue(_context);
        if (!JS_GetPropertyById(_context,
                                classNameObject,
                                InternedStringId(_context, InternedString::prototype),
                                &protoValue))
            throwCurrentJSException(
                _context, ErrorCodes::JSInterpreterFailure, "Couldn't get className prototype");

        if (!protoValue.isObject())
            uasserted(ErrorCodes::BadValue, "className's prototype isn't object");

        _constructor.init(_context, value.toObjectOrNull());
        _proto.init(_context, protoValue.toObjectOrNull());

        _installFunctions(_proto, T::methods);
        _installFunctions(global, T::freeFunctions);
        _postInstall(global, T::postInstall);
    }

    void _installFunctions(JS::HandleObject global, const JSFunctionSpec* fs) {
        if (!fs)
            return;
        if (JS_DefineFunctions(_context, global, fs))
            return;

        throwCurrentJSException(
            _context, ErrorCodes::JSInterpreterFailure, "Failed to define functions");
    }

    // We have to do this awkward dance to set the new style enumeration.
    // You used to be able to set this with JSCLASS_NEW_ENUMERATE in class
    // flags, in the future you'll probably only set ObjectOps, but for now
    // we have this.  There are a host of static_asserts in js/Class.h that
    // ensure that these two structures are equal.
    //
    // This is a landmine to watch out for during upgrades
    using enumerateT = bool (*)(JSContext*, JS::HandleObject, JS::AutoIdVector&, bool);
    void _installEnumerate(enumerateT enumerate) {
        if (!enumerate)
            return;

        auto implClass = reinterpret_cast<js::Class*>(&_jsclass);

        implClass->ops.enumerate = enumerate;
    }

    // This is for inheriting from something other than Object
    void _inheritFrom(const char* name, JS::HandleObject global, JS::MutableHandleObject out) {
        if (!name)
            return;

        JS::RootedValue val(_context);

        if (!JS_GetProperty(_context, global, name, &val)) {
            throwCurrentJSException(
                _context, ErrorCodes::JSInterpreterFailure, "Failed to get parent");
        }

        if (!val.isObject()) {
            uasserted(ErrorCodes::JSInterpreterFailure, "Parent is not an object");
        }

        out.set(val.toObjectOrNull());
    }

    using postInstallT = void (*)(JSContext*, JS::HandleObject, JS::HandleObject);
    void _postInstall(JS::HandleObject global, postInstallT postInstall) {
        if (!postInstall)
            return;

        postInstall(_context, global, _proto);
    }

    void _installConstructor(JSNative ctor) {
        if (!ctor)
            return;

        auto ptr = JS_NewFunction(_context, ctor, 0, JSFUN_CONSTRUCTOR, nullptr);
        if (!ptr) {
            throwCurrentJSException(
                _context, ErrorCodes::JSInterpreterFailure, "Failed to install constructor");
        }

        JS::RootedObject ctorObj(_context, JS_GetFunctionObject(ptr));

        if (!JS_LinkConstructorAndPrototype(_context, ctorObj, _proto))
            throwCurrentJSException(_context,
                                    ErrorCodes::JSInterpreterFailure,
                                    "Failed to link constructor and prototype");
    }

    JSObject* _assertPtr(JSObject* ptr) {
        if (!ptr)
            throwCurrentJSException(
                _context, ErrorCodes::JSInterpreterFailure, "Failed to JS_NewX");

        return ptr;
    }

    JSContext* _context;
    JS::PersistentRootedObject _proto;
    JS::PersistentRootedObject _constructor;
    JSClass _jsclass;
};

}  // namespace mozjs
}  // namespace mongo