summaryrefslogtreecommitdiffstats
path: root/js/src/vm/Compartment-inl.h
blob: fcf2cccdc2c0199f3633e85aabff4e27fefa23fe (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef vm_Compartment_inl_h
#define vm_Compartment_inl_h

#include "vm/Compartment.h"

#include <type_traits>

#include "jsapi.h"
#include "jsfriendapi.h"
#include "jsnum.h"
#include "gc/Barrier.h"
#include "gc/Marking.h"
#include "js/CallArgs.h"
#include "js/friend/ErrorMessages.h"  // js::GetErrorMessage, JSMSG_*
#include "js/Wrapper.h"
#include "vm/Iteration.h"
#include "vm/JSObject.h"

#include "vm/JSContext-inl.h"

struct JSClass;

inline js::StringWrapperMap::Ptr JS::Compartment::lookupWrapper(
    JSString* str) const {
  return zone()->crossZoneStringWrappers().lookup(str);
}

inline bool JS::Compartment::wrap(JSContext* cx, JS::MutableHandleValue vp) {
  /* Only GC things have to be wrapped or copied. */
  if (!vp.isGCThing()) {
    return true;
  }

  /*
   * Symbols are GC things, but never need to be wrapped or copied because
   * they are always allocated in the atoms zone. They still need to be
   * marked in the new compartment's zone, however.
   */
  if (vp.isSymbol()) {
    cx->markAtomValue(vp);
    return true;
  }

  /* Handle strings. */
  if (vp.isString()) {
    JS::RootedString str(cx, vp.toString());
    if (!wrap(cx, &str)) {
      return false;
    }
    vp.setString(str);
    return true;
  }

  if (vp.isBigInt()) {
    JS::RootedBigInt bi(cx, vp.toBigInt());
    if (!wrap(cx, &bi)) {
      return false;
    }
    vp.setBigInt(bi);
    return true;
  }

  MOZ_ASSERT(vp.isObject());

  /*
   * All that's left are objects.
   *
   * Object wrapping isn't the fastest thing in the world, in part because
   * we have to unwrap and invoke the prewrap hook to find the identity
   * object before we even start checking the cache. Neither of these
   * operations are needed in the common case, where we're just wrapping
   * a plain JS object from the wrappee's side of the membrane to the
   * wrapper's side.
   *
   * To optimize this, we note that the cache should only ever contain
   * identity objects - that is to say, objects that serve as the
   * canonical representation for a unique object identity observable by
   * script. Unwrap and prewrap are both steps that we take to get to the
   * identity of an incoming objects, and as such, they shuld never map
   * one identity object to another object. This means that we can safely
   * check the cache immediately, and only risk false negatives. Do this
   * in opt builds, and do both in debug builds so that we can assert
   * that we get the same answer.
   */
#ifdef DEBUG
  JS::AssertValueIsNotGray(vp);
  JS::RootedObject cacheResult(cx);
#endif
  if (js::ObjectWrapperMap::Ptr p = lookupWrapper(&vp.toObject())) {
#ifdef DEBUG
    cacheResult = p->value().get();
#else
    vp.setObject(*p->value().get());
    return true;
#endif
  }

  JS::RootedObject obj(cx, &vp.toObject());
  if (!wrap(cx, &obj)) {
    return false;
  }
  vp.setObject(*obj);
  MOZ_ASSERT_IF(cacheResult, obj == cacheResult);
  return true;
}

inline bool JS::Compartment::wrap(JSContext* cx,
                                  MutableHandle<mozilla::Maybe<Value>> vp) {
  if (vp.get().isNothing()) {
    return true;
  }

  return wrap(cx, MutableHandle<Value>::fromMarkedLocation(vp.get().ptr()));
}

namespace js {
namespace detail {

/**
 * Return the name of class T as a static null-terminated ASCII string constant
 * (for error messages).
 */
template <class T>
const char* ClassName() {
  return T::class_.name;
}

template <class T, class ErrorCallback>
MOZ_MUST_USE T* UnwrapAndTypeCheckValueSlowPath(JSContext* cx,
                                                HandleValue value,
                                                ErrorCallback throwTypeError) {
  JSObject* obj = nullptr;
  if (value.isObject()) {
    obj = &value.toObject();
    if (IsWrapper(obj)) {
      obj = CheckedUnwrapStatic(obj);
      if (!obj) {
        ReportAccessDenied(cx);
        return nullptr;
      }
    }
  }

  if (!obj || !obj->is<T>()) {
    throwTypeError();
    return nullptr;
  }

  return &obj->as<T>();
}

template <class ErrorCallback>
MOZ_MUST_USE JSObject* UnwrapAndTypeCheckValueSlowPath(
    JSContext* cx, HandleValue value, const JSClass* clasp,
    ErrorCallback throwTypeError) {
  JSObject* obj = nullptr;
  if (value.isObject()) {
    obj = &value.toObject();
    if (IsWrapper(obj)) {
      obj = CheckedUnwrapStatic(obj);
      if (!obj) {
        ReportAccessDenied(cx);
        return nullptr;
      }
    }
  }

  if (!obj || !obj->hasClass(clasp)) {
    throwTypeError();
    return nullptr;
  }

  return obj;
}

}  // namespace detail

/**
 * Remove all wrappers from `val` and try to downcast the result to class `T`.
 *
 * DANGER: The result may not be same-compartment with `cx`.
 *
 * This calls `throwTypeError` if the value isn't an object, cannot be
 * unwrapped, or isn't an instance of the expected type. `throwTypeError` must
 * in fact throw a TypeError (or OOM trying).
 */
template <class T, class ErrorCallback>
inline MOZ_MUST_USE T* UnwrapAndTypeCheckValue(JSContext* cx, HandleValue value,
                                               ErrorCallback throwTypeError) {
  cx->check(value);

  static_assert(!std::is_convertible_v<T*, Wrapper*>,
                "T can't be a Wrapper type; this function discards wrappers");

  if (value.isObject() && value.toObject().is<T>()) {
    return &value.toObject().as<T>();
  }

  return detail::UnwrapAndTypeCheckValueSlowPath<T>(cx, value, throwTypeError);
}

/**
 * Remove all wrappers from |val| and try to downcast the result to an object of
 * the class |clasp|.
 *
 * DANGER: The result may not be same-compartment with |cx|.
 *
 * This calls |throwTypeError| if the value isn't an object, cannot be
 * unwrapped, or isn't an instance of the expected type.  |throwTypeError| must
 * in fact throw a TypeError (or OOM trying).
 */
template <class ErrorCallback>
inline MOZ_MUST_USE JSObject* UnwrapAndTypeCheckValue(
    JSContext* cx, HandleValue value, const JSClass* clasp,
    ErrorCallback throwTypeError) {
  cx->check(value);

  if (value.isObject() && value.toObject().hasClass(clasp)) {
    return &value.toObject();
  }

  return detail::UnwrapAndTypeCheckValueSlowPath(cx, value, clasp,
                                                 throwTypeError);
}

/**
 * Remove all wrappers from `args.thisv()` and try to downcast the result to
 * class `T`.
 *
 * DANGER: The result may not be same-compartment with `cx`.
 *
 * This throws a TypeError if the value isn't an object, cannot be unwrapped,
 * or isn't an instance of the expected type.
 */
template <class T>
inline MOZ_MUST_USE T* UnwrapAndTypeCheckThis(JSContext* cx,
                                              const CallArgs& args,
                                              const char* methodName) {
  HandleValue thisv = args.thisv();
  return UnwrapAndTypeCheckValue<T>(cx, thisv, [cx, methodName, thisv] {
    JS_ReportErrorNumberLatin1(cx, GetErrorMessage, nullptr,
                               JSMSG_INCOMPATIBLE_PROTO, detail::ClassName<T>(),
                               methodName, InformalValueTypeName(thisv));
  });
}

/**
 * Remove all wrappers from `args[argIndex]` and try to downcast the result to
 * class `T`.
 *
 * DANGER: The result may not be same-compartment with `cx`.
 *
 * This throws a TypeError if the specified argument is missing, isn't an
 * object, cannot be unwrapped, or isn't an instance of the expected type.
 */
template <class T>
inline MOZ_MUST_USE T* UnwrapAndTypeCheckArgument(JSContext* cx, CallArgs& args,
                                                  const char* methodName,
                                                  int argIndex) {
  HandleValue val = args.get(argIndex);
  return UnwrapAndTypeCheckValue<T>(cx, val, [cx, val, methodName, argIndex] {
    ToCStringBuf cbuf;
    if (char* numStr = NumberToCString(cx, &cbuf, argIndex + 1, 10)) {
      JS_ReportErrorNumberLatin1(
          cx, GetErrorMessage, nullptr, JSMSG_WRONG_TYPE_ARG, numStr,
          methodName, detail::ClassName<T>(), InformalValueTypeName(val));
    } else {
      ReportOutOfMemory(cx);
    }
  });
}

/**
 * Unwrap an object of a known type.
 *
 * If `obj` is an object of class T, this returns a pointer to that object. If
 * `obj` is a wrapper for such an object, this tries to unwrap the object and
 * return a pointer to it. If access is denied, or `obj` was a wrapper but has
 * been nuked, this reports an error and returns null.
 *
 * In all other cases, the behavior is undefined, so call this only if `obj` is
 * known to have been an object of class T, or a wrapper to a T, at some point.
 */
template <class T>
inline MOZ_MUST_USE T* UnwrapAndDowncastObject(JSContext* cx, JSObject* obj) {
  static_assert(!std::is_convertible_v<T*, Wrapper*>,
                "T can't be a Wrapper type; this function discards wrappers");

  if (IsProxy(obj)) {
    if (JS_IsDeadWrapper(obj)) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_DEAD_OBJECT);
      return nullptr;
    }

    // It would probably be OK to do an unchecked unwrap here, but we allow
    // arbitrary security policies, so check anyway.
    obj = obj->maybeUnwrapAs<T>();
    if (!obj) {
      ReportAccessDenied(cx);
      return nullptr;
    }
  }

  return &obj->as<T>();
}

/**
 * Unwrap an object of a known (but not compile-time-known) class.
 *
 * If |obj| is an object with class |clasp|, this returns |obj|.  If |obj| is a
 * wrapper for such an object, this tries to unwrap the object and return a
 * pointer to it.  If access is denied, or |obj| was a wrapper but has been
 * nuked, this reports an error and returns null.
 *
 * In all other cases, the behavior is undefined, so call this only if |obj| is
 * known to have had class |clasp|, or been a wrapper to such an object, at some
 * point.
 */
inline MOZ_MUST_USE JSObject* UnwrapAndDowncastObject(JSContext* cx,
                                                      JSObject* obj,
                                                      const JSClass* clasp) {
  if (IsProxy(obj)) {
    if (JS_IsDeadWrapper(obj)) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_DEAD_OBJECT);
      return nullptr;
    }

    // It would probably be OK to do an unchecked unwrap here, but we allow
    // arbitrary security policies, so check anyway.
    obj = obj->maybeUnwrapAs(clasp);
    if (!obj) {
      ReportAccessDenied(cx);
      return nullptr;
    }
  }

  MOZ_ASSERT(obj->hasClass(clasp));
  return obj;
}

/**
 * Unwrap a value of a known type. See UnwrapAndDowncastObject.
 */
template <class T>
inline MOZ_MUST_USE T* UnwrapAndDowncastValue(JSContext* cx,
                                              const Value& value) {
  return UnwrapAndDowncastObject<T>(cx, &value.toObject());
}

/**
 * Unwrap an object of a known (but not compile-time-known) class.  See
 * UnwrapAndDowncastObject.
 */
inline MOZ_MUST_USE JSObject* UnwrapAndDowncastValue(JSContext* cx,
                                                     const Value& value,
                                                     const JSClass* clasp) {
  return UnwrapAndDowncastObject(cx, &value.toObject(), clasp);
}

/**
 * Read a private slot that is known to point to a particular type of object.
 *
 * Some internal slots specified in various standards effectively have static
 * types. For example, the [[ownerReadableStream]] slot of a stream reader is
 * guaranteed to be a ReadableStream. However, because of compartments, we
 * sometimes store a cross-compartment wrapper in that slot. And since wrappers
 * can be nuked, that wrapper may become a dead object proxy.
 *
 * UnwrapInternalSlot() copes with the cross-compartment and dead object cases,
 * but not plain bugs where the slot hasn't been initialized or doesn't contain
 * the expected type of object. Call this only if the slot is certain to
 * contain either an instance of T, a wrapper for a T, or a dead object.
 *
 * `cx` and `unwrappedObj` are not required to be same-compartment.
 *
 * DANGER: The result may not be same-compartment with either `cx` or `obj`.
 */
template <class T>
inline MOZ_MUST_USE T* UnwrapInternalSlot(JSContext* cx,
                                          Handle<NativeObject*> unwrappedObj,
                                          uint32_t slot) {
  static_assert(!std::is_convertible_v<T*, Wrapper*>,
                "T can't be a Wrapper type; this function discards wrappers");

  return UnwrapAndDowncastValue<T>(cx, unwrappedObj->getFixedSlot(slot));
}

/**
 * Read a function slot that is known to point to a particular type of object.
 *
 * This is like UnwrapInternalSlot, but for extended function slots. Call this
 * only if the specified slot is known to have been initialized with an object
 * of class T or a wrapper for such an object.
 *
 * DANGER: The result may not be same-compartment with `cx`.
 */
template <class T>
MOZ_MUST_USE T* UnwrapCalleeSlot(JSContext* cx, CallArgs& args,
                                 size_t extendedSlot) {
  JSFunction& func = args.callee().as<JSFunction>();
  return UnwrapAndDowncastValue<T>(cx, func.getExtendedSlot(extendedSlot));
}

}  // namespace js

#endif /* vm_Compartment_inl_h */