summaryrefslogtreecommitdiffstats
path: root/remote/cdp/domains/content/runtime/ExecutionContext.sys.mjs
blob: 4d394f6bf9023ca4cb69680979ee5f5f678efb6a (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
554
555
556
557
558
559
560
561
562
563
564
/* 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/. */

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  generateUUID: "chrome://remote/content/shared/UUID.sys.mjs",
});

const TYPED_ARRAY_CLASSES = [
  "Uint8Array",
  "Uint8ClampedArray",
  "Uint16Array",
  "Uint32Array",
  "Int8Array",
  "Int16Array",
  "Int32Array",
  "Float32Array",
  "Float64Array",
];

// Bug 1786299: Puppeteer expects specific error messages.
const ERROR_CYCLIC_REFERENCE = "Object reference chain is too long";
const ERROR_CANNOT_RETURN_BY_VALUE = "Object couldn't be returned by value";

function randomInt() {
  return crypto.getRandomValues(new Uint32Array(1))[0];
}

/**
 * This class represent a debuggable context onto which we can evaluate Javascript.
 * This is typically a document, but it could also be a worker, an add-on, ... or
 * any kind of context involving JS scripts.
 *
 * @param {Debugger} dbg
 *   A Debugger instance that we can use to inspect the given global.
 * @param {GlobalObject} debuggee
 *   The debuggable context's global object. This is typically the document window
 *   object. But it can also be any global object, like a worker global scope object.
 */
export class ExecutionContext {
  constructor(dbg, debuggee, id, isDefault) {
    this._debugger = dbg;
    this._debuggee = this._debugger.addDebuggee(debuggee);

    // Here, we assume that debuggee is a window object and we will propably have
    // to adapt that once we cover workers or contexts that aren't a document.
    this.window = debuggee;
    this.windowId = this.window.windowGlobalChild.innerWindowId;
    this.id = id;
    this.frameId = this.window.browsingContext.id.toString();
    this.isDefault = isDefault;

    // objectId => Debugger.Object
    this._remoteObjects = new Map();
  }

  destructor() {
    this._debugger.removeDebuggee(this._debuggee);
  }

  get browsingContext() {
    return this.window.browsingContext;
  }

  hasRemoteObject(objectId) {
    return this._remoteObjects.has(objectId);
  }

  getRemoteObject(objectId) {
    return this._remoteObjects.get(objectId);
  }

  getRemoteObjectByNodeId(nodeId) {
    for (const value of this._remoteObjects.values()) {
      if (value.nodeId == nodeId) {
        return value;
      }
    }

    return null;
  }

  releaseObject(objectId) {
    return this._remoteObjects.delete(objectId);
  }

  /**
   * Add a new debuggerObj to the object cache.
   *
   * Whenever an object is returned as reference, a new entry is added
   * to the internal object cache. It means the same underlying object or node
   * can be represented via multiple references.
   */
  setRemoteObject(debuggerObj) {
    const objectId = lazy.generateUUID();

    // TODO: Wrap Symbol into an object,
    // which would allow us to set the objectId.
    if (typeof debuggerObj == "object") {
      debuggerObj.objectId = objectId;
    }

    // For node objects add an unique identifier.
    if (
      debuggerObj instanceof Debugger.Object &&
      Node.isInstance(debuggerObj.unsafeDereference())
    ) {
      debuggerObj.nodeId = randomInt();
      // We do not differentiate between backendNodeId and nodeId (yet)
      debuggerObj.backendNodeId = debuggerObj.nodeId;
    }

    this._remoteObjects.set(objectId, debuggerObj);

    return objectId;
  }

  /**
   * Evaluate a Javascript expression.
   *
   * @param {string} expression
   *   The JS expression to evaluate against the JS context.
   * @param {boolean} awaitPromise
   *     Whether execution should `await` for resulting value
   *     and return once awaited promise is resolved.
   * @param {boolean} returnByValue
   *     Whether the result is expected to be a JSON object
   *     that should be sent by value.
   *
   * @returns {object} A multi-form object depending if the execution
   *   succeed or failed. If the expression failed to evaluate,
   *   it will return an object with an `exceptionDetails` attribute
   *   matching the `ExceptionDetails` CDP type. Otherwise it will
   *   return an object with `result` attribute whose type is
   *   `RemoteObject` CDP type.
   */
  async evaluate(expression, awaitPromise, returnByValue) {
    let rv = this._debuggee.executeInGlobal(expression);
    if (!rv) {
      return {
        exceptionDetails: {
          text: "Evaluation terminated!",
        },
      };
    }

    if (rv.throw) {
      return this._returnError(rv.throw);
    }

    let result = rv.return;

    if (result && result.isPromise && awaitPromise) {
      if (result.promiseState === "fulfilled") {
        result = result.promiseValue;
      } else if (result.promiseState === "rejected") {
        return this._returnError(result.promiseReason);
      } else {
        try {
          const promiseResult = await result.unsafeDereference();
          result = this._debuggee.makeDebuggeeValue(promiseResult);
        } catch (e) {
          // The promise has been rejected
          return this._returnError(this._debuggee.makeDebuggeeValue(e));
        }
      }
    }

    if (returnByValue) {
      result = this._toRemoteObjectByValue(result);
    } else {
      result = this._toRemoteObject(result);
    }

    return { result };
  }

  /**
   * Given a Debugger.Object reference for an Exception, return a JSON object
   * describing the exception by following CDP ExceptionDetails specification.
   */
  _returnError(exception) {
    if (
      this._debuggee.executeInGlobalWithBindings("exception instanceof Error", {
        exception,
      }).return
    ) {
      const text = this._debuggee.executeInGlobalWithBindings(
        "exception.message",
        { exception }
      ).return;
      return {
        exceptionDetails: {
          text,
        },
      };
    }

    // If that isn't an Error, consider the exception as a JS value
    return {
      exceptionDetails: {
        exception: this._toRemoteObject(exception),
      },
    };
  }

  async callFunctionOn(
    functionDeclaration,
    callArguments = [],
    returnByValue = false,
    awaitPromise = false,
    objectId = null
  ) {
    // Map the given objectId to a JS reference.
    let thisArg = null;
    if (objectId) {
      thisArg = this.getRemoteObject(objectId);
      if (!thisArg) {
        throw new Error(`Unable to get target object with id: ${objectId}`);
      }
    }

    // First evaluate the function
    const fun = this._debuggee.executeInGlobal("(" + functionDeclaration + ")");
    if (!fun) {
      return {
        exceptionDetails: {
          text: "Evaluation terminated!",
        },
      };
    }
    if (fun.throw) {
      return this._returnError(fun.throw);
    }

    // Then map all input arguments, which are matching CDP's CallArguments type,
    // into JS values
    const args = callArguments.map(arg => this._fromCallArgument(arg));

    // Finally, call the function with these arguments
    const rv = fun.return.apply(thisArg, args);
    if (rv.throw) {
      return this._returnError(rv.throw);
    }

    let result = rv.return;

    if (result && result.isPromise && awaitPromise) {
      if (result.promiseState === "fulfilled") {
        result = result.promiseValue;
      } else if (result.promiseState === "rejected") {
        return this._returnError(result.promiseReason);
      } else {
        try {
          const promiseResult = await result.unsafeDereference();
          result = this._debuggee.makeDebuggeeValue(promiseResult);
        } catch (e) {
          // The promise has been rejected
          return this._returnError(this._debuggee.makeDebuggeeValue(e));
        }
      }
    }

    if (returnByValue) {
      result = this._toRemoteObjectByValue(result);
    } else {
      result = this._toRemoteObject(result);
    }

    return { result };
  }

  getProperties({ objectId, ownProperties }) {
    let debuggerObj = this.getRemoteObject(objectId);
    if (!debuggerObj) {
      throw new Error("Could not find object with given id");
    }

    const result = [];
    const serializeObject = (debuggerObj, isOwn) => {
      for (const propertyName of debuggerObj.getOwnPropertyNames()) {
        const descriptor = debuggerObj.getOwnPropertyDescriptor(propertyName);
        result.push({
          name: propertyName,

          configurable: descriptor.configurable,
          enumerable: descriptor.enumerable,
          writable: descriptor.writable,
          value: this._toRemoteObject(descriptor.value),
          get: descriptor.get
            ? this._toRemoteObject(descriptor.get)
            : undefined,
          set: descriptor.set
            ? this._toRemoteObject(descriptor.set)
            : undefined,

          isOwn,
        });
      }
    };

    // When `ownProperties` is set to true, we only iterate over own properties.
    // Otherwise, we also iterate over propreties inherited from the prototype chain.
    serializeObject(debuggerObj, true);

    if (!ownProperties) {
      while (true) {
        debuggerObj = debuggerObj.proto;
        if (!debuggerObj) {
          break;
        }
        serializeObject(debuggerObj, false);
      }
    }

    return {
      result,
    };
  }

  /**
   * Given a CDP `CallArgument`, return a JS value that represent this argument.
   * Note that `CallArgument` is actually very similar to `RemoteObject`
   */
  _fromCallArgument(arg) {
    if (arg.objectId) {
      if (!this.hasRemoteObject(arg.objectId)) {
        throw new Error("Could not find object with given id");
      }
      return this.getRemoteObject(arg.objectId);
    }

    if (arg.unserializableValue) {
      switch (arg.unserializableValue) {
        case "-0":
          return -0;
        case "Infinity":
          return Infinity;
        case "-Infinity":
          return -Infinity;
        case "NaN":
          return NaN;
        default:
          if (/^\d+n$/.test(arg.unserializableValue)) {
            // eslint-disable-next-line no-undef
            return BigInt(arg.unserializableValue.slice(0, -1));
          }
          throw new Error("Couldn't parse value object in call argument");
      }
    }

    return this._deserialize(arg.value);
  }

  /**
   * Given a JS value, create a copy of it within the debugee compartment.
   */
  _deserialize(obj) {
    if (typeof obj !== "object") {
      return obj;
    }
    const result = this._debuggee.executeInGlobalWithBindings(
      "JSON.parse(obj)",
      { obj: JSON.stringify(obj) }
    );
    if (result.throw) {
      throw new Error("Unable to deserialize object");
    }
    return result.return;
  }

  /**
   * Given a `Debugger.Object` object, return a JSON-serializable description of it
   * matching `RemoteObject` CDP type.
   *
   * @param {Debugger.Object} debuggerObj
   *  The object to serialize
   * @returns {RemoteObject}
   *  The serialized description of the given object
   */
  _toRemoteObject(debuggerObj) {
    const result = {};

    // First handle all non-primitive values which are going to be wrapped by the
    // Debugger API into Debugger.Object instances
    if (debuggerObj instanceof Debugger.Object) {
      const rawObj = debuggerObj.unsafeDereference();

      result.objectId = this.setRemoteObject(debuggerObj);
      result.type = typeof rawObj;

      // Map the Debugger API `class` attribute to CDP `subtype`
      const cls = debuggerObj.class;
      if (debuggerObj.isProxy) {
        result.subtype = "proxy";
      } else if (cls == "Array") {
        result.subtype = "array";
      } else if (cls == "RegExp") {
        result.subtype = "regexp";
      } else if (cls == "Date") {
        result.subtype = "date";
      } else if (cls == "Map") {
        result.subtype = "map";
      } else if (cls == "Set") {
        result.subtype = "set";
      } else if (cls == "WeakMap") {
        result.subtype = "weakmap";
      } else if (cls == "WeakSet") {
        result.subtype = "weakset";
      } else if (cls == "Error") {
        result.subtype = "error";
      } else if (cls == "Promise") {
        result.subtype = "promise";
      } else if (TYPED_ARRAY_CLASSES.includes(cls)) {
        result.subtype = "typedarray";
      } else if (Node.isInstance(rawObj)) {
        result.subtype = "node";
        result.className = ChromeUtils.getClassName(rawObj);
        result.description = rawObj.localName || rawObj.nodeName;
        if (rawObj.id) {
          result.description += `#${rawObj.id}`;
        }
      }
      return result;
    }

    // Now, handle all values that Debugger API isn't wrapping into Debugger.API.
    // This is all the primitive JS types.
    result.type = typeof debuggerObj;

    // Symbol and BigInt are primitive values but aren't serializable.
    // CDP expects them to be considered as objects, with an objectId to later inspect
    // them.
    if (result.type == "symbol") {
      result.description = debuggerObj.toString();
      result.objectId = this.setRemoteObject(debuggerObj);

      return result;
    }

    // A few primitive type can't be serialized and CDP has special case for them
    if (Object.is(debuggerObj, NaN)) {
      result.unserializableValue = "NaN";
    } else if (Object.is(debuggerObj, -0)) {
      result.unserializableValue = "-0";
    } else if (Object.is(debuggerObj, Infinity)) {
      result.unserializableValue = "Infinity";
    } else if (Object.is(debuggerObj, -Infinity)) {
      result.unserializableValue = "-Infinity";
    } else if (result.type == "bigint") {
      result.unserializableValue = `${debuggerObj}n`;
    }

    if (result.unserializableValue) {
      result.description = result.unserializableValue;
      return result;
    }

    // Otherwise, we serialize the primitive values as-is via `value` attribute
    result.value = debuggerObj;

    // null is special as it has a dedicated subtype
    if (debuggerObj === null) {
      result.subtype = "null";
    }

    return result;
  }

  /**
   * Given a `Debugger.Object` object, return a JSON-serializable description of it
   * matching `RemoteObject` CDP type.
   *
   * @param {Debugger.Object} debuggerObj
   *  The object to serialize
   * @returns {RemoteObject}
   *  The serialized description of the given object
   */
  _toRemoteObjectByValue(debuggerObj) {
    const type = typeof debuggerObj;

    if (type == "undefined") {
      return { type };
    }

    let unserializableValue;
    if (Object.is(debuggerObj, -0)) {
      unserializableValue = "-0";
    } else if (Object.is(debuggerObj, NaN)) {
      unserializableValue = "NaN";
    } else if (Object.is(debuggerObj, Infinity)) {
      unserializableValue = "Infinity";
    } else if (Object.is(debuggerObj, -Infinity)) {
      unserializableValue = "-Infinity";
    } else if (typeof debuggerObj == "bigint") {
      unserializableValue = `${debuggerObj}n`;
    }

    if (unserializableValue) {
      return {
        type,
        unserializableValue,
        description: unserializableValue,
      };
    }

    const value = this._serialize(debuggerObj);
    return {
      type: typeof value,
      value,
      description: value != null ? value.toString() : value,
    };
  }

  /**
   * Convert a given `Debugger.Object` to an object.
   *
   * @param {Debugger.Object} debuggerObj
   *  The object to convert
   *
   * @returns {object}
   *  The converted object
   */
  _serialize(debuggerObj) {
    const result = this._debuggee.executeInGlobalWithBindings(
      `
      JSON.stringify(e, (key, value) => {
        if (typeof value === "symbol") {
          // CDP cannot return Symbols
          throw new Error();
        }

        return value;
      });
    `,
      { e: debuggerObj }
    );
    if (result.throw) {
      const exception = this._toRawObject(result.throw);
      if (exception.message === "cyclic object value") {
        throw new Error(ERROR_CYCLIC_REFERENCE);
      }

      throw new Error(ERROR_CANNOT_RETURN_BY_VALUE);
    }

    return JSON.parse(result.return);
  }

  _toRawObject(maybeDebuggerObject) {
    if (maybeDebuggerObject instanceof Debugger.Object) {
      // Retrieve the referent for the provided Debugger.object.
      // See https://firefox-source-docs.mozilla.org/devtools-user/debugger-api/debugger.object/index.html
      const rawObject = maybeDebuggerObject.unsafeDereference();
      return Cu.waiveXrays(rawObject);
    }

    // If maybeDebuggerObject was not a Debugger.Object, it is a primitive value
    // which can be used as is.
    return maybeDebuggerObject;
  }
}