forked from WebKit/WebKit-http
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjCCallbackFunction.mm
More file actions
719 lines (613 loc) · 26 KB
/
ObjCCallbackFunction.mm
File metadata and controls
719 lines (613 loc) · 26 KB
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#import "JavaScriptCore.h"
#if JSC_OBJC_API_ENABLED
#import "APICallbackFunction.h"
#import "APICast.h"
#import "Error.h"
#import "JSCJSValueInlines.h"
#import "JSCell.h"
#import "JSCellInlines.h"
#import "JSContextInternal.h"
#import "JSWrapperMap.h"
#import "JSValueInternal.h"
#import "ObjCCallbackFunction.h"
#import "ObjcRuntimeExtras.h"
#import <objc/runtime.h>
#import <wtf/RetainPtr.h>
class CallbackArgument {
WTF_MAKE_FAST_ALLOCATED;
public:
virtual ~CallbackArgument();
virtual void set(NSInvocation *, NSInteger, JSContext *, JSValueRef, JSValueRef*) = 0;
std::unique_ptr<CallbackArgument> m_next;
};
CallbackArgument::~CallbackArgument()
{
}
class CallbackArgumentBoolean : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) override
{
bool value = JSValueToBoolean([context JSGlobalContextRef], argument);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
template<typename T>
class CallbackArgumentInteger : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
T value = (T)JSC::toInt32(JSValueToNumber([context JSGlobalContextRef], argument, exception));
[invocation setArgument:&value atIndex:argumentNumber];
}
};
template<typename T>
class CallbackArgumentDouble : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
T value = (T)JSValueToNumber([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentJSValue : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) override
{
JSValue *value = [JSValue valueWithJSValueRef:argument inContext:context];
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentId : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) override
{
id value = valueToObject(context, argument);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentOfClass : public CallbackArgument {
public:
CallbackArgumentOfClass(Class cls)
: m_class(cls)
{
}
private:
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
id object = tryUnwrapObjcObject(contextRef, argument);
if (object && [object isKindOfClass:m_class.get()]) {
[invocation setArgument:&object atIndex:argumentNumber];
return;
}
if (JSValueIsNull(contextRef, argument) || JSValueIsUndefined(contextRef, argument)) {
object = nil;
[invocation setArgument:&object atIndex:argumentNumber];
return;
}
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("Argument does not match Objective-C Class")));
}
RetainPtr<Class> m_class;
};
class CallbackArgumentNSNumber : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToNumber([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentNSString : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToString([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentNSDate : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToDate([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentNSArray : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToArray([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentNSDictionary : public CallbackArgument {
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToDictionary([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentStruct : public CallbackArgument {
public:
CallbackArgumentStruct(NSInvocation *conversionInvocation, const char* encodedType)
: m_conversionInvocation(conversionInvocation)
, m_buffer(encodedType)
{
}
private:
virtual void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) override
{
JSValue *value = [JSValue valueWithJSValueRef:argument inContext:context];
[m_conversionInvocation invokeWithTarget:value];
[m_conversionInvocation getReturnValue:m_buffer];
[invocation setArgument:m_buffer atIndex:argumentNumber];
}
RetainPtr<NSInvocation> m_conversionInvocation;
StructBuffer m_buffer;
};
class ArgumentTypeDelegate {
public:
typedef std::unique_ptr<CallbackArgument> ResultType;
template<typename T>
static ResultType typeInteger()
{
return std::make_unique<CallbackArgumentInteger<T>>();
}
template<typename T>
static ResultType typeDouble()
{
return std::make_unique<CallbackArgumentDouble<T>>();
}
static ResultType typeBool()
{
return std::make_unique<CallbackArgumentBoolean>();
}
static ResultType typeVoid()
{
RELEASE_ASSERT_NOT_REACHED();
return nullptr;
}
static ResultType typeId()
{
return std::make_unique<CallbackArgumentId>();
}
static ResultType typeOfClass(const char* begin, const char* end)
{
StringRange copy(begin, end);
Class cls = objc_getClass(copy);
if (!cls)
return nullptr;
if (cls == [JSValue class])
return std::make_unique<CallbackArgumentJSValue>();
if (cls == [NSString class])
return std::make_unique<CallbackArgumentNSString>();
if (cls == [NSNumber class])
return std::make_unique<CallbackArgumentNSNumber>();
if (cls == [NSDate class])
return std::make_unique<CallbackArgumentNSDate>();
if (cls == [NSArray class])
return std::make_unique<CallbackArgumentNSArray>();
if (cls == [NSDictionary class])
return std::make_unique<CallbackArgumentNSDictionary>();
return std::make_unique<CallbackArgumentOfClass>(cls);
}
static ResultType typeBlock(const char*, const char*)
{
return nullptr;
}
static ResultType typeStruct(const char* begin, const char* end)
{
StringRange copy(begin, end);
if (NSInvocation *invocation = valueToTypeInvocationFor(copy))
return std::make_unique<CallbackArgumentStruct>(invocation, copy);
return nullptr;
}
};
class CallbackResult {
WTF_MAKE_FAST_ALLOCATED;
public:
virtual ~CallbackResult()
{
}
virtual JSValueRef get(NSInvocation *, JSContext *, JSValueRef*) = 0;
};
class CallbackResultVoid : public CallbackResult {
virtual JSValueRef get(NSInvocation *, JSContext *context, JSValueRef*) override
{
return JSValueMakeUndefined([context JSGlobalContextRef]);
}
};
class CallbackResultId : public CallbackResult {
virtual JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) override
{
id value;
[invocation getReturnValue:&value];
return objectToValue(context, value);
}
};
template<typename T>
class CallbackResultNumeric : public CallbackResult {
virtual JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) override
{
T value;
[invocation getReturnValue:&value];
return JSValueMakeNumber([context JSGlobalContextRef], value);
}
};
class CallbackResultBoolean : public CallbackResult {
virtual JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) override
{
bool value;
[invocation getReturnValue:&value];
return JSValueMakeBoolean([context JSGlobalContextRef], value);
}
};
class CallbackResultStruct : public CallbackResult {
public:
CallbackResultStruct(NSInvocation *conversionInvocation, const char* encodedType)
: m_conversionInvocation(conversionInvocation)
, m_buffer(encodedType)
{
}
private:
virtual JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) override
{
[invocation getReturnValue:m_buffer];
[m_conversionInvocation setArgument:m_buffer atIndex:2];
[m_conversionInvocation setArgument:&context atIndex:3];
[m_conversionInvocation invokeWithTarget:[JSValue class]];
JSValue *value;
[m_conversionInvocation getReturnValue:&value];
return valueInternalValue(value);
}
RetainPtr<NSInvocation> m_conversionInvocation;
StructBuffer m_buffer;
};
class ResultTypeDelegate {
public:
typedef std::unique_ptr<CallbackResult> ResultType;
template<typename T>
static ResultType typeInteger()
{
return std::make_unique<CallbackResultNumeric<T>>();
}
template<typename T>
static ResultType typeDouble()
{
return std::make_unique<CallbackResultNumeric<T>>();
}
static ResultType typeBool()
{
return std::make_unique<CallbackResultBoolean>();
}
static ResultType typeVoid()
{
return std::make_unique<CallbackResultVoid>();
}
static ResultType typeId()
{
return std::make_unique<CallbackResultId>();
}
static ResultType typeOfClass(const char*, const char*)
{
return std::make_unique<CallbackResultId>();
}
static ResultType typeBlock(const char*, const char*)
{
return std::make_unique<CallbackResultId>();
}
static ResultType typeStruct(const char* begin, const char* end)
{
StringRange copy(begin, end);
if (NSInvocation *invocation = typeToValueInvocationFor(copy))
return std::make_unique<CallbackResultStruct>(invocation, copy);
return nullptr;
}
};
enum CallbackType {
CallbackInitMethod,
CallbackInstanceMethod,
CallbackClassMethod,
CallbackBlock
};
namespace JSC {
class ObjCCallbackFunctionImpl {
public:
ObjCCallbackFunctionImpl(NSInvocation *invocation, CallbackType type, Class instanceClass, std::unique_ptr<CallbackArgument> arguments, std::unique_ptr<CallbackResult> result)
: m_type(type)
, m_instanceClass(instanceClass)
, m_invocation(invocation)
, m_arguments(WTF::move(arguments))
, m_result(WTF::move(result))
{
ASSERT((type != CallbackInstanceMethod && type != CallbackInitMethod) || instanceClass);
}
void destroy(Heap& heap)
{
// We need to explicitly release the target since we didn't call
// -retainArguments on m_invocation (and we don't want to do so).
if (m_type == CallbackBlock || m_type == CallbackClassMethod)
heap.releaseSoon(adoptNS([m_invocation.get() target]));
m_instanceClass = nil;
}
JSValueRef call(JSContext *context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
id wrappedBlock()
{
return m_type == CallbackBlock ? [m_invocation target] : nil;
}
id wrappedConstructor()
{
switch (m_type) {
case CallbackBlock:
return [m_invocation target];
case CallbackInitMethod:
return m_instanceClass.get();
default:
return nil;
}
}
bool isConstructible()
{
return !!wrappedBlock() || m_type == CallbackInitMethod;
}
String name();
private:
CallbackType m_type;
RetainPtr<Class> m_instanceClass;
RetainPtr<NSInvocation> m_invocation;
std::unique_ptr<CallbackArgument> m_arguments;
std::unique_ptr<CallbackResult> m_result;
};
static JSValueRef objCCallbackFunctionCallAsFunction(JSContextRef callerContext, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Retake the API lock - we need this for a few reasons:
// (1) We don't want to support the C-API's confusing drops-locks-once policy - should only drop locks if we can do so recursively.
// (2) We're calling some JSC internals that require us to be on the 'inside' - e.g. createTypeError.
// (3) We need to be locked (per context would be fine) against conflicting usage of the ObjCCallbackFunction's NSInvocation.
JSC::JSLockHolder locker(toJS(callerContext));
ObjCCallbackFunction* callback = static_cast<ObjCCallbackFunction*>(toJS(function));
ObjCCallbackFunctionImpl* impl = callback->impl();
JSContext *context = [JSContext contextWithJSGlobalContextRef:toGlobalRef(callback->globalObject()->globalExec())];
CallbackData callbackData;
JSValueRef result;
@autoreleasepool {
[context beginCallbackWithData:&callbackData calleeValue:function thisValue:thisObject argumentCount:argumentCount arguments:arguments];
result = impl->call(context, thisObject, argumentCount, arguments, exception);
if (context.exception)
*exception = valueInternalValue(context.exception);
[context endCallbackWithData:&callbackData];
}
return result;
}
static JSObjectRef objCCallbackFunctionCallAsConstructor(JSContextRef callerContext, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
JSC::JSLockHolder locker(toJS(callerContext));
ObjCCallbackFunction* callback = static_cast<ObjCCallbackFunction*>(toJS(constructor));
ObjCCallbackFunctionImpl* impl = callback->impl();
JSContext *context = [JSContext contextWithJSGlobalContextRef:toGlobalRef(toJS(callerContext)->lexicalGlobalObject()->globalExec())];
CallbackData callbackData;
JSValueRef result;
@autoreleasepool {
[context beginCallbackWithData:&callbackData calleeValue:constructor thisValue:nullptr argumentCount:argumentCount arguments:arguments];
result = impl->call(context, nullptr, argumentCount, arguments, exception);
if (context.exception)
*exception = valueInternalValue(context.exception);
[context endCallbackWithData:&callbackData];
}
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
if (*exception)
return nullptr;
if (!JSValueIsObject(contextRef, result)) {
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("Objective-C blocks called as constructors must return an object.")));
return nullptr;
}
return (JSObjectRef)result;
}
const JSC::ClassInfo ObjCCallbackFunction::s_info = { "CallbackFunction", &Base::s_info, 0, CREATE_METHOD_TABLE(ObjCCallbackFunction) };
ObjCCallbackFunction::ObjCCallbackFunction(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSObjectCallAsFunctionCallback functionCallback, JSObjectCallAsConstructorCallback constructCallback, std::unique_ptr<ObjCCallbackFunctionImpl> impl)
: Base(vm, globalObject->objcCallbackFunctionStructure())
, m_functionCallback(functionCallback)
, m_constructCallback(constructCallback)
, m_impl(WTF::move(impl))
{
}
ObjCCallbackFunction* ObjCCallbackFunction::create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, const String& name, std::unique_ptr<ObjCCallbackFunctionImpl> impl)
{
ObjCCallbackFunction* function = new (NotNull, allocateCell<ObjCCallbackFunction>(vm.heap)) ObjCCallbackFunction(vm, globalObject, objCCallbackFunctionCallAsFunction, objCCallbackFunctionCallAsConstructor, WTF::move(impl));
function->finishCreation(vm, name);
return function;
}
void ObjCCallbackFunction::destroy(JSCell* cell)
{
ObjCCallbackFunction& function = *jsCast<ObjCCallbackFunction*>(cell);
function.impl()->destroy(*Heap::heap(cell));
function.~ObjCCallbackFunction();
}
CallType ObjCCallbackFunction::getCallData(JSCell*, CallData& callData)
{
callData.native.function = APICallbackFunction::call<ObjCCallbackFunction>;
return CallTypeHost;
}
ConstructType ObjCCallbackFunction::getConstructData(JSCell* cell, ConstructData& constructData)
{
ObjCCallbackFunction* callback = jsCast<ObjCCallbackFunction*>(cell);
if (!callback->impl()->isConstructible())
return Base::getConstructData(cell, constructData);
constructData.native.function = APICallbackFunction::construct<ObjCCallbackFunction>;
return ConstructTypeHost;
}
String ObjCCallbackFunctionImpl::name()
{
if (m_type == CallbackInitMethod)
return class_getName(m_instanceClass.get());
// FIXME: Maybe we could support having the selector as the name of the non-init
// functions to make it a bit more user-friendly from the JS side?
return "";
}
JSValueRef ObjCCallbackFunctionImpl::call(JSContext *context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
id target;
size_t firstArgument;
switch (m_type) {
case CallbackInitMethod: {
RELEASE_ASSERT(!thisObject);
target = [m_instanceClass alloc];
if (!target || ![target isKindOfClass:m_instanceClass.get()]) {
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("self type check failed for Objective-C instance method")));
return JSValueMakeUndefined(contextRef);
}
[m_invocation setTarget:target];
firstArgument = 2;
break;
}
case CallbackInstanceMethod: {
target = tryUnwrapObjcObject(contextRef, thisObject);
if (!target || ![target isKindOfClass:m_instanceClass.get()]) {
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("self type check failed for Objective-C instance method")));
return JSValueMakeUndefined(contextRef);
}
[m_invocation setTarget:target];
firstArgument = 2;
break;
}
case CallbackClassMethod:
firstArgument = 2;
break;
case CallbackBlock:
firstArgument = 1;
}
size_t argumentNumber = 0;
for (CallbackArgument* argument = m_arguments.get(); argument; argument = argument->m_next.get()) {
JSValueRef value = argumentNumber < argumentCount ? arguments[argumentNumber] : JSValueMakeUndefined(contextRef);
argument->set(m_invocation.get(), argumentNumber + firstArgument, context, value, exception);
if (*exception)
return JSValueMakeUndefined(contextRef);
++argumentNumber;
}
[m_invocation invoke];
JSValueRef result = m_result->get(m_invocation.get(), context, exception);
// Balance our call to -alloc with a call to -autorelease. We have to do this after calling -init
// because init family methods are allowed to release the allocated object and return something
// else in its place.
if (m_type == CallbackInitMethod) {
id objcResult = tryUnwrapObjcObject(contextRef, result);
if (objcResult)
[objcResult autorelease];
}
return result;
}
} // namespace JSC
static bool blockSignatureContainsClass()
{
static bool containsClass = ^{
id block = ^(NSString *string){ return string; };
return _Block_has_signature(block) && strstr(_Block_signature(block), "NSString");
}();
return containsClass;
}
static inline bool skipNumber(const char*& position)
{
if (!isASCIIDigit(*position))
return false;
while (isASCIIDigit(*++position)) { }
return true;
}
static JSObjectRef objCCallbackFunctionForInvocation(JSContext *context, NSInvocation *invocation, CallbackType type, Class instanceClass, const char* signatureWithObjcClasses)
{
if (!signatureWithObjcClasses)
return nullptr;
const char* position = signatureWithObjcClasses;
auto result = parseObjCType<ResultTypeDelegate>(position);
if (!result || !skipNumber(position))
return nullptr;
switch (type) {
case CallbackInitMethod:
case CallbackInstanceMethod:
case CallbackClassMethod:
// Methods are passed two implicit arguments - (id)self, and the selector.
if ('@' != *position++ || !skipNumber(position) || ':' != *position++ || !skipNumber(position))
return nullptr;
break;
case CallbackBlock:
// Blocks are passed one implicit argument - the block, of type "@?".
if (('@' != *position++) || ('?' != *position++) || !skipNumber(position))
return nullptr;
// Only allow arguments of type 'id' if the block signature contains the NS type information.
if ((!blockSignatureContainsClass() && strchr(position, '@')))
return nullptr;
break;
}
std::unique_ptr<CallbackArgument> arguments;
auto* nextArgument = &arguments;
unsigned argumentCount = 0;
while (*position) {
auto argument = parseObjCType<ArgumentTypeDelegate>(position);
if (!argument || !skipNumber(position))
return nullptr;
*nextArgument = WTF::move(argument);
nextArgument = &(*nextArgument)->m_next;
++argumentCount;
}
JSC::ExecState* exec = toJS([context JSGlobalContextRef]);
JSC::JSLockHolder locker(exec);
auto impl = std::make_unique<JSC::ObjCCallbackFunctionImpl>(invocation, type, instanceClass, WTF::move(arguments), WTF::move(result));
const String& name = impl->name();
return toRef(JSC::ObjCCallbackFunction::create(exec->vm(), exec->lexicalGlobalObject(), name, WTF::move(impl)));
}
JSObjectRef objCCallbackFunctionForInit(JSContext *context, Class cls, Protocol *protocol, SEL sel, const char* types)
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:types]];
[invocation setSelector:sel];
return objCCallbackFunctionForInvocation(context, invocation, CallbackInitMethod, cls, _protocol_getMethodTypeEncoding(protocol, sel, YES, YES));
}
JSObjectRef objCCallbackFunctionForMethod(JSContext *context, Class cls, Protocol *protocol, BOOL isInstanceMethod, SEL sel, const char* types)
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:types]];
[invocation setSelector:sel];
// We need to retain the target Class because m_invocation doesn't retain it by default (and we don't want it to).
// FIXME: What releases it?
if (!isInstanceMethod)
[invocation setTarget:[cls retain]];
return objCCallbackFunctionForInvocation(context, invocation, isInstanceMethod ? CallbackInstanceMethod : CallbackClassMethod, isInstanceMethod ? cls : nil, _protocol_getMethodTypeEncoding(protocol, sel, YES, isInstanceMethod));
}
JSObjectRef objCCallbackFunctionForBlock(JSContext *context, id target)
{
if (!_Block_has_signature(target))
return nullptr;
const char* signature = _Block_signature(target);
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:signature]];
// We don't want to use -retainArguments because that leaks memory. Arguments
// would be retained indefinitely between invocations of the callback.
// Additionally, we copy the target because we want the block to stick around
// until the ObjCCallbackFunctionImpl is destroyed.
[invocation setTarget:[target copy]];
return objCCallbackFunctionForInvocation(context, invocation, CallbackBlock, nil, signature);
}
id tryUnwrapConstructor(JSObjectRef object)
{
if (!toJS(object)->inherits(JSC::ObjCCallbackFunction::info()))
return nil;
JSC::ObjCCallbackFunctionImpl* impl = static_cast<JSC::ObjCCallbackFunction*>(toJS(object))->impl();
if (!impl->isConstructible())
return nil;
return impl->wrappedConstructor();
}
#endif