summaryrefslogtreecommitdiff
path: root/deps/v8/src/builtins/promise-misc.tq
blob: df3010669e5e2455684d68087ba6f6ae75d66fed (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
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include 'src/builtins/builtins-promise.h'
#include 'src/builtins/builtins-promise-gen.h'

namespace runtime {
extern transitioning runtime
AllowDynamicFunction(implicit context: Context)(JSAny): JSAny;

extern transitioning runtime
ReportMessageFromMicrotask(implicit context: Context)(JSAny): JSAny;
}

// Unsafe functions that should be used very carefully.
namespace promise_internal {
extern macro PromiseBuiltinsAssembler::ZeroOutEmbedderOffsets(JSPromise): void;

extern macro PromiseBuiltinsAssembler::AllocateJSPromise(Context): HeapObject;
}

extern macro
PromiseBuiltinsAssembler::IsContextPromiseHookEnabled(uint32): bool;

extern macro
PromiseBuiltinsAssembler::IsIsolatePromiseHookEnabled(uint32): bool;

extern macro
PromiseBuiltinsAssembler::PromiseHookFlags(): uint32;

namespace promise {
extern macro IsFunctionWithPrototypeSlotMap(Map): bool;

@export
macro PromiseHasHandler(promise: JSPromise): bool {
  return promise.HasHandler();
}

@export
macro PromiseInit(promise: JSPromise): void {
  promise.reactions_or_result = kZero;
  promise.flags = SmiTag(JSPromiseFlags{
    status: PromiseState::kPending,
    has_handler: false,
    handled_hint: false,
    is_silent: false,
    async_task_id: 0
  });
  promise_internal::ZeroOutEmbedderOffsets(promise);
}

macro InnerNewJSPromise(implicit context: Context)(): JSPromise {
  const promiseFun = *NativeContextSlot(ContextSlot::PROMISE_FUNCTION_INDEX);
  dcheck(IsFunctionWithPrototypeSlotMap(promiseFun.map));
  const promiseMap = UnsafeCast<Map>(promiseFun.prototype_or_initial_map);
  const promiseHeapObject = promise_internal::AllocateJSPromise(context);
  *UnsafeConstCast(&promiseHeapObject.map) = promiseMap;
  const promise = UnsafeCast<JSPromise>(promiseHeapObject);
  promise.properties_or_hash = kEmptyFixedArray;
  promise.elements = kEmptyFixedArray;
  promise.reactions_or_result = kZero;
  promise.flags = SmiTag(JSPromiseFlags{
    status: PromiseState::kPending,
    has_handler: false,
    handled_hint: false,
    is_silent: false,
    async_task_id: 0
  });
  return promise;
}

macro NewPromiseFulfillReactionJobTask(implicit context: Context)(
    handlerContext: Context, argument: Object, handler: Callable|Undefined,
    promiseOrCapability: JSPromise|PromiseCapability|
    Undefined): PromiseFulfillReactionJobTask {
  const nativeContext = LoadNativeContext(handlerContext);
  return new PromiseFulfillReactionJobTask{
    map: PromiseFulfillReactionJobTaskMapConstant(),
    argument,
    context: handlerContext,
    handler,
    promise_or_capability: promiseOrCapability,
    continuation_preserved_embedder_data:
        *ContextSlot(
        nativeContext, ContextSlot::CONTINUATION_PRESERVED_EMBEDDER_DATA_INDEX)
  };
}

macro NewPromiseRejectReactionJobTask(implicit context: Context)(
    handlerContext: Context, argument: Object, handler: Callable|Undefined,
    promiseOrCapability: JSPromise|PromiseCapability|
    Undefined): PromiseRejectReactionJobTask {
  const nativeContext = LoadNativeContext(handlerContext);
  return new PromiseRejectReactionJobTask{
    map: PromiseRejectReactionJobTaskMapConstant(),
    argument,
    context: handlerContext,
    handler,
    promise_or_capability: promiseOrCapability,
    continuation_preserved_embedder_data:
        *ContextSlot(
        nativeContext, ContextSlot::CONTINUATION_PRESERVED_EMBEDDER_DATA_INDEX)
  };
}

@export
transitioning macro RunContextPromiseHookInit(implicit context: Context)(
    promise: JSPromise, parent: Object): void {
  const maybeHook = *NativeContextSlot(
      ContextSlot::PROMISE_HOOK_INIT_FUNCTION_INDEX);
  const hook = Cast<Callable>(maybeHook) otherwise return;
  const parentObject = Is<JSPromise>(parent) ? Cast<JSPromise>(parent)
      otherwise unreachable: Undefined;

  try {
    Call(context, hook, Undefined, promise, parentObject);
  } catch (e, _message) {
    runtime::ReportMessageFromMicrotask(e);
  }
}

@export
transitioning macro RunContextPromiseHookResolve(implicit context: Context)(
    promise: JSPromise): void {
  // Use potentially unused variables.
  const _unusedPromise = promise;
  @if(V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS) {
    RunContextPromiseHook(
        ContextSlot::PROMISE_HOOK_RESOLVE_FUNCTION_INDEX, promise,
        PromiseHookFlags());
  }
}

@export
transitioning macro RunContextPromiseHookResolve(implicit context: Context)(
    promise: JSPromise, flags: uint32): void {
  RunContextPromiseHook(
      ContextSlot::PROMISE_HOOK_RESOLVE_FUNCTION_INDEX, promise, flags);
}

@export
transitioning macro RunContextPromiseHookBefore(implicit context: Context)(
    promiseOrCapability: JSPromise|PromiseCapability|Undefined): void {
  // Use potentially unused variables.
  const _unusedPromiseOrCapability = promiseOrCapability;
  @if(V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS) {
    RunContextPromiseHook(
        ContextSlot::PROMISE_HOOK_BEFORE_FUNCTION_INDEX, promiseOrCapability,
        PromiseHookFlags());
  }
}

@export
transitioning macro RunContextPromiseHookBefore(implicit context: Context)(
    promiseOrCapability: JSPromise|PromiseCapability|Undefined, flags: uint32):
    void {
  RunContextPromiseHook(
      ContextSlot::PROMISE_HOOK_BEFORE_FUNCTION_INDEX, promiseOrCapability,
      flags);
}

@export
transitioning macro RunContextPromiseHookAfter(implicit context: Context)(
    promiseOrCapability: JSPromise|PromiseCapability|Undefined): void {
  // Use potentially unused variables.
  const _unusedPromiseOrCapability = promiseOrCapability;
  @if(V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS) {
    RunContextPromiseHook(
        ContextSlot::PROMISE_HOOK_AFTER_FUNCTION_INDEX, promiseOrCapability,
        PromiseHookFlags());
  }
}

@export
transitioning macro RunContextPromiseHookAfter(implicit context: Context)(
    promiseOrCapability: JSPromise|PromiseCapability|Undefined, flags: uint32):
    void {
  RunContextPromiseHook(
      ContextSlot::PROMISE_HOOK_AFTER_FUNCTION_INDEX, promiseOrCapability,
      flags);
}

transitioning macro RunContextPromiseHook(implicit context: Context)(
    slot: Slot<NativeContext, Undefined|Callable>,
    promiseOrCapability: JSPromise|PromiseCapability|Undefined,
    flags: uint32): void {
  // Use potentially unused variables.
  const _unusedSlot = slot;
  const _unusedPromiseOrCapability = promiseOrCapability;
  const _unusedFlags = flags;
  @if(V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS) {
    if (!IsContextPromiseHookEnabled(flags)) return;
    const maybeHook = *NativeContextSlot(slot);
    const hook = Cast<Callable>(maybeHook) otherwise return;

    let promise: JSPromise;
    typeswitch (promiseOrCapability) {
      case (jspromise: JSPromise): {
        promise = jspromise;
      }
      case (capability: PromiseCapability): {
        promise = Cast<JSPromise>(capability.promise) otherwise return;
      }
      case (Undefined): {
        return;
      }
    }

    try {
      Call(context, hook, Undefined, promise);
    } catch (e, _message) {
      runtime::ReportMessageFromMicrotask(e);
    }
  }
}

transitioning macro RunAnyPromiseHookInit(implicit context: Context)(
    promise: JSPromise, parent: Object): void {
  const promiseHookFlags = PromiseHookFlags();
  // Fast return if no hooks are set.
  if (promiseHookFlags == 0) return;
  @if(V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS) {
    if (IsContextPromiseHookEnabled(promiseHookFlags)) {
      RunContextPromiseHookInit(promise, parent);
    }
  }
  if (IsIsolatePromiseHookEnabled(promiseHookFlags)) {
    runtime::PromiseHookInit(promise, parent);
  }
}

// These allocate and initialize a promise with pending state and
// undefined fields.
//
// This uses the given parent as the parent promise for the promise
// init hook.
@export
transitioning macro NewJSPromise(implicit context: Context)(parent: Object):
    JSPromise {
  const instance = InnerNewJSPromise();
  PromiseInit(instance);
  RunAnyPromiseHookInit(instance, parent);
  return instance;
}

// This uses undefined as the parent promise for the promise init
// hook.
@export
transitioning macro NewJSPromise(implicit context: Context)(): JSPromise {
  return NewJSPromise(Undefined);
}

// This allocates and initializes a promise with the given state and
// fields.
@export
transitioning macro NewJSPromise(implicit context: Context)(
    status: constexpr PromiseState, result: JSAny): JSPromise {
  dcheck(status != PromiseState::kPending);

  const instance = InnerNewJSPromise();
  instance.reactions_or_result = result;
  instance.SetStatus(status);
  promise_internal::ZeroOutEmbedderOffsets(instance);
  RunAnyPromiseHookInit(instance, Undefined);
  return instance;
}

macro NewPromiseReaction(implicit context: Context)(
    handlerContext: Context, next: Zero|PromiseReaction,
    promiseOrCapability: JSPromise|PromiseCapability|Undefined,
    fulfillHandler: Callable|Undefined,
    rejectHandler: Callable|Undefined): PromiseReaction {
  const nativeContext = LoadNativeContext(handlerContext);
  return new PromiseReaction{
    map: PromiseReactionMapConstant(),
    next: next,
    reject_handler: rejectHandler,
    fulfill_handler: fulfillHandler,
    promise_or_capability: promiseOrCapability,
    continuation_preserved_embedder_data:
        *ContextSlot(
        nativeContext, ContextSlot::CONTINUATION_PRESERVED_EMBEDDER_DATA_INDEX)
  };
}

extern macro PromiseResolveThenableJobTaskMapConstant(): Map;

// https://tc39.es/ecma262/#sec-newpromiseresolvethenablejob
macro NewPromiseResolveThenableJobTask(implicit context: Context)(
    promiseToResolve: JSPromise, thenable: JSReceiver,
    then: Callable): PromiseResolveThenableJobTask {
  // 2. Let getThenRealmResult be GetFunctionRealm(then).
  // 3. If getThenRealmResult is a normal completion, then let thenRealm be
  //    getThenRealmResult.[[Value]].
  // 4. Otherwise, let thenRealm be null.
  //
  // The only cases where |thenRealm| can be null is when |then| is a revoked
  // Proxy object, which would throw when it is called anyway. So instead of
  // setting the context to null as the spec does, we just use the current
  // realm.
  const thenContext: Context = ExtractHandlerContext(then);
  const nativeContext = LoadNativeContext(thenContext);

  // 1. Let job be a new Job abstract closure with no parameters that
  //    captures promiseToResolve, thenable, and then...
  // 5. Return { [[Job]]: job, [[Realm]]: thenRealm }.
  return new PromiseResolveThenableJobTask{
    map: PromiseResolveThenableJobTaskMapConstant(),
    context: nativeContext,
    promise_to_resolve: promiseToResolve,
    thenable,
    then
  };
}

struct InvokeThenOneArgFunctor {
  transitioning
  macro Call(
      nativeContext: NativeContext, then: JSAny, receiver: JSAny, arg1: JSAny,
      _arg2: JSAny): JSAny {
    return Call(nativeContext, then, receiver, arg1);
  }
}

struct InvokeThenTwoArgFunctor {
  transitioning
  macro Call(
      nativeContext: NativeContext, then: JSAny, receiver: JSAny, arg1: JSAny,
      arg2: JSAny): JSAny {
    return Call(nativeContext, then, receiver, arg1, arg2);
  }
}

transitioning
macro InvokeThen<F: type>(implicit context: Context)(
    nativeContext: NativeContext, receiver: JSAny, arg1: JSAny, arg2: JSAny,
    callFunctor: F): JSAny {
  // We can skip the "then" lookup on {receiver} if it's [[Prototype]]
  // is the (initial) Promise.prototype and the Promise#then protector
  // is intact, as that guards the lookup path for the "then" property
  // on JSPromise instances which have the (initial) %PromisePrototype%.
  if (!Is<Smi>(receiver) &&
      IsPromiseThenLookupChainIntact(
          nativeContext, UnsafeCast<HeapObject>(receiver).map)) {
    const then =
        *NativeContextSlot(nativeContext, ContextSlot::PROMISE_THEN_INDEX);
    return callFunctor.Call(nativeContext, then, receiver, arg1, arg2);
  } else
    deferred {
      const then = UnsafeCast<JSAny>(GetProperty(receiver, kThenString));
      return callFunctor.Call(nativeContext, then, receiver, arg1, arg2);
    }
}

transitioning
macro InvokeThen(implicit context: Context)(
    nativeContext: NativeContext, receiver: JSAny, arg: JSAny): JSAny {
  return InvokeThen(
      nativeContext, receiver, arg, Undefined, InvokeThenOneArgFunctor{});
}

transitioning
macro InvokeThen(implicit context: Context)(
    nativeContext: NativeContext, receiver: JSAny, arg1: JSAny,
    arg2: JSAny): JSAny {
  return InvokeThen(
      nativeContext, receiver, arg1, arg2, InvokeThenTwoArgFunctor{});
}

transitioning
macro BranchIfAccessCheckFailed(implicit context: Context)(
    nativeContext: NativeContext, promiseConstructor: JSAny,
    executor: JSAny): void labels IfNoAccess {
  try {
    // If executor is a bound function, load the bound function until we've
    // reached an actual function.
    let foundExecutor = executor;
    while (true) {
      typeswitch (foundExecutor) {
        case (f: JSFunction): {
          // Load the context from the function and compare it to the Promise
          // constructor's context. If they match, everything is fine,
          // otherwise, bail out to the runtime.
          const functionContext = f.context;
          const nativeFunctionContext = LoadNativeContext(functionContext);
          if (TaggedEqual(nativeContext, nativeFunctionContext)) {
            goto HasAccess;
          } else {
            goto CallRuntime;
          }
        }
        case (b: JSBoundFunction): {
          foundExecutor = b.bound_target_function;
        }
        case (Object): {
          goto CallRuntime;
        }
      }
    }
  } label CallRuntime deferred {
    const result = runtime::AllowDynamicFunction(promiseConstructor);
    if (result != True) {
      goto IfNoAccess;
    }
  } label HasAccess {}
}
}