Skip to content

Commit b40ec02

Browse files
committed
[JSC] Proxy should directly call a function when it does not have apply handler
https://bugs.webkit.org/show_bug.cgi?id=328101 rdar://190449810 Reviewed by Sosuke Suzuki. Similar to the other ProxyObject cache mechanism, we cache `apply` handler and skip calling Proxy's apply operation when this is not set. Then call operation can directly call Proxy's set callee. Test: JSTests/stress/proxy-call-without-apply-trap.js * JSTests/stress/proxy-call-without-apply-trap.js: Added. (shouldBe): (callProxy): (callDirect): (tailCall): (callMethod): (construct): (noInline.get const): (noInline): (shouldBe.handler.apply): (i.i.testLoopCount.1.Object.prototype.apply): (const.handler.get apply): (else.shouldThrow): (callPolymorphic): (tailCallPolymorphic): (callMegamorphic): (tailCallMegamorphic): (noInline.handler.apply): * Source/JavaScriptCore/bytecode/RepatchInlines.h: (JSC::forwardProxyCallToTarget): (JSC::linkFor): (JSC::virtualForWithFunction): * Source/JavaScriptCore/runtime/ProxyObject.cpp: (JSC::ProxyObject::finishCreation): (JSC::JSC_DEFINE_HOST_FUNCTION): (JSC::ProxyObject::getCallData): (JSC::ProxyObject::getConstructData): * Source/JavaScriptCore/runtime/ProxyObject.h: (JSC::ProxyObject::callTargetIfKnownToHaveNoApplyTrap): Canonical link: https://commits.webkit.org/324312@main
1 parent 675aae0 commit b40ec02

4 files changed

Lines changed: 309 additions & 14 deletions

File tree

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
"use strict";
2+
3+
function shouldBe(actual, expected, message) {
4+
if (actual !== expected)
5+
throw new Error(`${message}: expected ${String(expected)} but got ${String(actual)}`);
6+
}
7+
8+
function shouldThrow(func, errorType, message) {
9+
let error;
10+
try {
11+
func();
12+
} catch (e) {
13+
error = e;
14+
}
15+
if (!(error instanceof errorType))
16+
throw new Error(`${message}: expected ${errorType.name} but got ${String(error)}`);
17+
}
18+
19+
function target(a, b) {
20+
return [this, a, b, arguments.length];
21+
}
22+
23+
function callProxy(proxy, thisValue, a, b) {
24+
const result = proxy.call(thisValue, a, b);
25+
return result;
26+
}
27+
noInline(callProxy);
28+
29+
function callDirect(proxy, a) {
30+
const result = proxy(a);
31+
return result;
32+
}
33+
noInline(callDirect);
34+
35+
function tailCall(proxy, a) {
36+
"use strict";
37+
return proxy(a);
38+
}
39+
noInline(tailCall);
40+
41+
function callMethod(object, a, b) {
42+
const result = object.method(a, b);
43+
return result;
44+
}
45+
noInline(callMethod);
46+
47+
function construct(proxy, a) {
48+
return new proxy(a);
49+
}
50+
noInline(construct);
51+
52+
{
53+
const proxy = new Proxy(target, { });
54+
const nested = new Proxy(new Proxy(target, { }), { get() { return 0; } });
55+
const thisValue = { };
56+
for (let i = 0; i < testLoopCount; ++i) {
57+
let result = callMethod({ method: proxy }, i, i + 1);
58+
shouldBe(result[1], i, "first argument");
59+
shouldBe(result[2], i + 1, "second argument");
60+
shouldBe(result[3], 2, "argument count");
61+
result = callDirect(proxy, i);
62+
shouldBe(result[0], undefined, "this of a plain call");
63+
shouldBe(result[2], undefined, "missing argument");
64+
shouldBe(result[3], 1, "argument count with missing argument");
65+
shouldBe(callProxy(proxy, thisValue, 1, 2)[0], thisValue, "this through Function.prototype.call");
66+
result = tailCall(proxy, i);
67+
shouldBe(result[0], undefined, "this of a tail call");
68+
shouldBe(result[3], 1, "argument count of a tail call");
69+
shouldBe(tailCall(nested, i)[1], i, "tail call through nested proxies");
70+
}
71+
}
72+
73+
{
74+
let applyCount = 0;
75+
const handler = { };
76+
const proxy = new Proxy(target, handler);
77+
for (let i = 0; i < testLoopCount; ++i) {
78+
if (i === (testLoopCount >> 1))
79+
handler.apply = function (t, thisArgument, args) { ++applyCount; return "trapped"; };
80+
let result = callDirect(proxy, i);
81+
if (i < (testLoopCount >> 1))
82+
shouldBe(result[1], i, "before adding the apply trap");
83+
else
84+
shouldBe(result, "trapped", "after adding the apply trap");
85+
}
86+
shouldBe(applyCount, testLoopCount - (testLoopCount >> 1), "apply trap count");
87+
}
88+
89+
{
90+
const proxy = new Proxy(target, { });
91+
for (let i = 0; i < testLoopCount; ++i) {
92+
if (i === (testLoopCount >> 1))
93+
Object.prototype.apply = function () { return "from Object.prototype"; };
94+
let result = callDirect(proxy, i);
95+
if (i < (testLoopCount >> 1))
96+
shouldBe(result[1], i, "before adding Object.prototype.apply");
97+
else
98+
shouldBe(result, "from Object.prototype", "after adding Object.prototype.apply");
99+
}
100+
delete Object.prototype.apply;
101+
}
102+
103+
{
104+
let getterCount = 0;
105+
const handler = {
106+
get apply() {
107+
++getterCount;
108+
return undefined;
109+
}
110+
};
111+
const proxy = new Proxy(target, handler);
112+
for (let i = 0; i < testLoopCount; ++i)
113+
shouldBe(callDirect(proxy, i)[1], i, "apply getter returning undefined");
114+
shouldBe(getterCount, testLoopCount, "apply getter count");
115+
}
116+
117+
{
118+
const { proxy, revoke } = Proxy.revocable(target, { });
119+
for (let i = 0; i < testLoopCount; ++i) {
120+
if (i === (testLoopCount >> 1))
121+
revoke();
122+
if (i < (testLoopCount >> 1))
123+
shouldBe(callDirect(proxy, i)[1], i, "before revocation");
124+
else
125+
shouldThrow(() => callDirect(proxy, i), TypeError, "after revocation");
126+
}
127+
}
128+
129+
{
130+
class C { constructor(a) { this.a = a; } }
131+
const proxy = new Proxy(C, { });
132+
const nonCallable = new Proxy({ }, { });
133+
const native = new Proxy(Math.max, { });
134+
const bound = new Proxy(target.bind(null, "bound"), { });
135+
for (let i = 0; i < testLoopCount; ++i) {
136+
shouldThrow(() => callDirect(proxy, i), TypeError, "calling a class constructor");
137+
shouldBe(construct(proxy, i).a, i, "constructing through the proxy");
138+
shouldThrow(() => callDirect(nonCallable, i), TypeError, "calling a non-callable proxy");
139+
shouldBe(callDirect(native, i), i, "native target");
140+
let result = callDirect(bound, i);
141+
shouldBe(result[1], "bound", "bound target first argument");
142+
shouldBe(result[2], i, "bound target second argument");
143+
}
144+
}
145+
146+
{
147+
const error = new Error("thrown");
148+
const proxy = new Proxy(function () { throw error; }, { });
149+
for (let i = 0; i < testLoopCount; ++i) {
150+
let caught;
151+
try {
152+
callDirect(proxy, i);
153+
} catch (e) {
154+
caught = e;
155+
}
156+
shouldBe(caught, error, "exception from the target");
157+
}
158+
}
159+
160+
function callPolymorphic(callee, a) {
161+
const result = callee(a);
162+
return result;
163+
}
164+
noInline(callPolymorphic);
165+
166+
function tailCallPolymorphic(callee, a) {
167+
return callee(a);
168+
}
169+
noInline(tailCallPolymorphic);
170+
171+
function callMegamorphic(callee, a) {
172+
const result = callee(a);
173+
return result;
174+
}
175+
noInline(callMegamorphic);
176+
177+
function tailCallMegamorphic(callee, a) {
178+
return callee(a);
179+
}
180+
noInline(tailCallMegamorphic);
181+
182+
{
183+
const functions = [];
184+
for (let i = 0; i < 4; ++i)
185+
functions.push(new Function("a", `return a + ${i};`));
186+
const handler = { };
187+
const proxy = new Proxy(target, handler);
188+
const internalFunctionProxy = new Proxy(Array, { });
189+
for (let i = 0; i < testLoopCount; ++i) {
190+
for (let j = 0; j < functions.length; ++j) {
191+
shouldBe(callPolymorphic(functions[j], i), i + j, "polymorphic function");
192+
shouldBe(tailCallPolymorphic(functions[j], i), i + j, "polymorphic function tail call");
193+
}
194+
if (i === (testLoopCount >> 1))
195+
handler.apply = function () { return "trapped"; };
196+
let result = callPolymorphic(proxy, i);
197+
if (i < (testLoopCount >> 1))
198+
shouldBe(result[1], i, "polymorphic proxy before adding the apply trap");
199+
else
200+
shouldBe(result, "trapped", "polymorphic proxy after adding the apply trap");
201+
result = tailCallPolymorphic(proxy, i);
202+
if (i < (testLoopCount >> 1))
203+
shouldBe(result[1], i, "polymorphic proxy tail call before adding the apply trap");
204+
else
205+
shouldBe(result, "trapped", "polymorphic proxy tail call after adding the apply trap");
206+
shouldBe(callPolymorphic(internalFunctionProxy, 3).length, 3, "polymorphic proxy of an internal function");
207+
shouldBe(tailCallPolymorphic(internalFunctionProxy, 3).length, 3, "polymorphic proxy tail call of an internal function");
208+
}
209+
}
210+
211+
{
212+
const functions = [];
213+
for (let i = 0; i < 32; ++i)
214+
functions.push(new Function("a", `return a + ${i};`));
215+
const handler = { };
216+
const proxy = new Proxy(target, handler);
217+
const nested = new Proxy(new Proxy(target, { }), { });
218+
const internalFunctionProxy = new Proxy(Array, { });
219+
for (let i = 0; i < testLoopCount; ++i) {
220+
const j = i % functions.length;
221+
shouldBe(callMegamorphic(functions[j], i), i + j, "megamorphic function");
222+
shouldBe(tailCallMegamorphic(functions[j], i), i + j, "megamorphic function tail call");
223+
if (i === (testLoopCount >> 1))
224+
handler.apply = function () { return "trapped"; };
225+
let result = callMegamorphic(proxy, i);
226+
if (i < (testLoopCount >> 1))
227+
shouldBe(result[1], i, "megamorphic proxy before adding the apply trap");
228+
else
229+
shouldBe(result, "trapped", "megamorphic proxy after adding the apply trap");
230+
result = tailCallMegamorphic(proxy, i);
231+
if (i < (testLoopCount >> 1))
232+
shouldBe(result[1], i, "megamorphic proxy tail call before adding the apply trap");
233+
else
234+
shouldBe(result, "trapped", "megamorphic proxy tail call after adding the apply trap");
235+
shouldBe(callMegamorphic(nested, i)[1], i, "megamorphic nested proxy");
236+
shouldBe(tailCallMegamorphic(nested, i)[1], i, "megamorphic nested proxy tail call");
237+
shouldBe(callMegamorphic(internalFunctionProxy, 3).length, 3, "megamorphic proxy of an internal function");
238+
shouldBe(tailCallMegamorphic(internalFunctionProxy, 3).length, 3, "megamorphic proxy tail call of an internal function");
239+
}
240+
}

‎Source/JavaScriptCore/bytecode/RepatchInlines.h‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
#include "FunctionCodeBlock.h"
3434
#include "JSObjectInlines.h"
3535
#include "LLIntEntrypoint.h"
36+
#include "ProxyObject.h"
3637
#include "Repatch.h"
3738
#include "VMTrapsInlines.h"
3839

@@ -128,6 +129,27 @@ inline void* handleHostCall(VM& vm, JSCell* owner, CallFrame* calleeFrame, JSVal
128129
RELEASE_AND_RETURN(scope, throwNotAConstructorErrorFromCallIC(globalObject, owner, callee, callLinkInfo));
129130
}
130131

132+
// A proxy without an "apply" trap calls its target with the same this and arguments, so the call can
133+
// enter the target directly instead of re-entering the VM from performProxyCall.
134+
ALWAYS_INLINE bool forwardProxyCallToTarget(CallFrame* calleeFrame, JSValue callee, CodeSpecializationKind kind)
135+
{
136+
if (kind != CodeSpecializationKind::CodeForCall)
137+
return false;
138+
JSValue target = callee;
139+
while (auto* proxy = dynamicDowncast<ProxyObject>(target)) {
140+
JSObject* proxyTarget = proxy->callTargetIfKnownToHaveNoApplyTrap();
141+
if (!proxyTarget)
142+
break;
143+
target = proxyTarget;
144+
}
145+
if (target == callee)
146+
return false;
147+
calleeFrame->setCallee(asObject(target));
148+
return true;
149+
}
150+
151+
ALWAYS_INLINE void* virtualForWithFunction(VM&, JSCell* owner, CallFrame* calleeFrame, CallLinkInfo*, JSCell*& calleeAsFunctionCell);
152+
131153
ALWAYS_INLINE void* linkFor(VM& vm, JSCell* owner, CallFrame* calleeFrame, CallLinkInfo* callLinkInfo)
132154
{
133155
auto throwScope = DECLARE_THROW_SCOPE(vm);
@@ -137,6 +159,11 @@ ALWAYS_INLINE void* linkFor(VM& vm, JSCell* owner, CallFrame* calleeFrame, CallL
137159
JSValue calleeAsValue = calleeFrame->guaranteedJSValueCallee();
138160
JSCell* calleeAsFunctionCell = getJSFunction(calleeAsValue);
139161
if (!calleeAsFunctionCell) {
162+
// The call site sees the proxy as its callee, so it must not be linked to the target.
163+
if (forwardProxyCallToTarget(calleeFrame, calleeAsValue, kind)) {
164+
JSCell* unusedCalleeAsFunctionCell;
165+
RELEASE_AND_RETURN(throwScope, virtualForWithFunction(vm, owner, calleeFrame, callLinkInfo, unusedCalleeAsFunctionCell));
166+
}
140167
if (auto* internalFunction = dynamicDowncast<InternalFunction>(calleeAsValue)) {
141168
CodePtr<JSEntryPtrTag> codePtr = vm.getCTIInternalFunctionTrampolineFor(kind);
142169
RELEASE_ASSERT(!!codePtr);
@@ -236,9 +263,18 @@ ALWAYS_INLINE void* virtualForWithFunction(VM& vm, JSCell* owner, CallFrame* cal
236263

237264
JSValue calleeAsValue = calleeFrame->guaranteedJSValueCallee();
238265
calleeAsFunctionCell = getJSFunction(calleeAsValue);
266+
// The call site sees the proxy as its callee, so a forwarded call must not report the target for linking.
267+
bool forwardedFromProxy = false;
268+
if (!calleeAsFunctionCell) [[unlikely]] {
269+
if (forwardProxyCallToTarget(calleeFrame, calleeAsValue, kind)) {
270+
forwardedFromProxy = true;
271+
calleeAsValue = calleeFrame->guaranteedJSValueCallee();
272+
calleeAsFunctionCell = getJSFunction(calleeAsValue);
273+
}
274+
}
239275
if (!calleeAsFunctionCell) [[unlikely]] {
240276
if (auto* internalFunction = dynamicDowncast<InternalFunction>(calleeAsValue)) {
241-
calleeAsFunctionCell = internalFunction;
277+
calleeAsFunctionCell = forwardedFromProxy ? nullptr : internalFunction;
242278
CodePtr<JSEntryPtrTag> codePtr = vm.getCTIInternalFunctionTrampolineFor(kind);
243279
ASSERT(!!codePtr);
244280
return codePtr.taggedPtr();
@@ -247,6 +283,8 @@ ALWAYS_INLINE void* virtualForWithFunction(VM& vm, JSCell* owner, CallFrame* cal
247283
}
248284

249285
JSFunction* function = uncheckedDowncast<JSFunction>(calleeAsFunctionCell);
286+
if (forwardedFromProxy)
287+
calleeAsFunctionCell = nullptr;
250288
JSScope* scope = function->scopeUnchecked();
251289
ExecutableBase* executable = function->executable();
252290

‎Source/JavaScriptCore/runtime/ProxyObject.cpp‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#include "config.h"
2727
#include "ProxyObject.h"
2828

29+
#include "BuiltinNames.h"
2930
#include "GetterSetter.h"
3031
#include "JSCInlines.h"
3132
#include "JSInternalFieldObjectImplInlines.h"
@@ -78,13 +79,11 @@ void ProxyObject::finishCreation(VM& vm, JSGlobalObject* globalObject, JSValue t
7879

7980
JSObject* targetAsObject = uncheckedDowncast<JSObject>(target);
8081

81-
m_isCallable = targetAsObject->isCallable();
82-
if (m_isCallable) {
83-
TypeInfo info = structure()->typeInfo();
84-
RELEASE_ASSERT(info.implementsHasInstance() && info.implementsDefaultHasInstance());
85-
}
82+
RELEASE_ASSERT(isCallableProxy() == targetAsObject->isCallable());
83+
if (isCallableProxy())
84+
RELEASE_ASSERT(structure()->typeInfo().implementsHasInstance());
8685

87-
m_isConstructible = targetAsObject->isConstructor();
86+
setPerCellBit(targetAsObject->isConstructor());
8887

8988
internalField(Field::Target).set(vm, this, targetAsObject);
9089
internalField(Field::Handler).set(vm, this, handler);
@@ -618,10 +617,10 @@ JSC_DEFINE_HOST_FUNCTION(performProxyCall, (JSGlobalObject* globalObject, CallFr
618617

619618
JSObject* handler = uncheckedDowncast<JSObject>(handlerValue);
620619
CallData callData;
621-
JSValue applyMethod = handler->getMethod(globalObject, callData, makeIdentifier(vm, "apply"_s), "'apply' property of a Proxy's handler should be callable"_s);
620+
JSObject* applyMethod = proxy->getHandlerTrap(globalObject, handler, callData, vm.propertyNames->builtinNames().applyPublicName(), ProxyObject::HandlerTrap::Apply);
622621
RETURN_IF_EXCEPTION(scope, encodedJSValue());
623622
JSObject* target = proxy->target();
624-
if (applyMethod.isUndefined()) {
623+
if (!applyMethod) {
625624
auto callData = JSC::getCallDataInline(target);
626625
RELEASE_ASSERT(callData.type != CallData::Type::None);
627626
RELEASE_AND_RETURN(scope, JSValue::encode(call(globalObject, target, callData, callFrame->thisValue(), ArgList(callFrame))));
@@ -641,7 +640,7 @@ CallData ProxyObject::getCallData(JSCell* cell)
641640
{
642641
CallData callData;
643642
ProxyObject* proxy = uncheckedDowncast<ProxyObject>(cell);
644-
if (proxy->m_isCallable) {
643+
if (proxy->isCallableProxy()) {
645644
callData.type = CallData::Type::Native;
646645
callData.native.function = performProxyCall;
647646
callData.native.isBoundFunction = false;
@@ -700,7 +699,7 @@ CallData ProxyObject::getConstructData(JSCell* cell)
700699
{
701700
CallData constructData;
702701
ProxyObject* proxy = uncheckedDowncast<ProxyObject>(cell);
703-
if (proxy->m_isConstructible) {
702+
if (proxy->isConstructibleProxy()) {
704703
constructData.type = CallData::Type::Native;
705704
constructData.native.function = performProxyConstruct;
706705
constructData.native.isBoundFunction = false;

0 commit comments

Comments
 (0)