2 * Copyright (C) 2013-2015 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #import "JavaScriptCore.h"
29 #if JSC_OBJC_API_ENABLED
32 #import "JSAPIWrapperObject.h"
33 #import "JSCallbackObject.h"
34 #import "JSContextInternal.h"
35 #import "JSWrapperMap.h"
36 #import "ObjCCallbackFunction.h"
37 #import "ObjcRuntimeExtras.h"
38 #import "JSCInlines.h"
40 #import <wtf/TCSpinLock.h>
41 #import <wtf/Vector.h>
42 #import <wtf/HashSet.h>
44 #include <mach-o/dyld.h>
46 static const int32_t webkitFirstVersionWithInitConstructorSupport = 0x21A0400; // 538.4.0
48 @class JSObjCClassInfo;
50 @interface JSWrapperMap ()
52 - (JSObjCClassInfo*)classInfoForClass:(Class)cls;
56 // Default conversion of selectors to property names.
57 // All semicolons are removed, lowercase letters following a semicolon are capitalized.
58 static NSString *selectorToPropertyName(const char* start)
60 // Use 'index' to check for colons, if there are none, this is easy!
61 const char* firstColon = strchr(start, ':');
63 return [NSString stringWithUTF8String:start];
65 // 'header' is the length of string up to the first colon.
66 size_t header = firstColon - start;
67 // The new string needs to be long enough to hold 'header', plus the remainder of the string, excluding
68 // at least one ':', but including a '\0'. (This is conservative if there are more than one ':').
69 char* buffer = static_cast<char*>(malloc(header + strlen(firstColon + 1) + 1));
70 // Copy 'header' characters, set output to point to the end of this & input to point past the first ':'.
71 memcpy(buffer, start, header);
72 char* output = buffer + header;
73 const char* input = start + header + 1;
75 // On entry to the loop, we have already skipped over a ':' from the input.
78 // Skip over any additional ':'s. We'll leave c holding the next character after the
79 // last ':', and input pointing past c.
80 while ((c = *(input++)) == ':');
81 // Copy the character, converting to upper case if necessary.
82 // If the character we copy is '\0', then we're done!
83 if (!(*(output++) = toupper(c)))
85 // Loop over characters other than ':'.
86 while ((c = *(input++)) != ':') {
87 // Copy the character.
88 // If the character we copy is '\0', then we're done!
89 if (!(*(output++) = c))
92 // If we get here, we've consumed a ':' - wash, rinse, repeat.
95 NSString *result = [NSString stringWithUTF8String:buffer];
100 static bool constructorHasInstance(JSContextRef ctx, JSObjectRef constructorRef, JSValueRef possibleInstance, JSValueRef*)
102 JSC::ExecState* exec = toJS(ctx);
103 JSC::JSLockHolder locker(exec);
105 JSC::JSObject* constructor = toJS(constructorRef);
106 JSC::JSValue instance = toJS(exec, possibleInstance);
107 return JSC::JSObject::defaultHasInstance(exec, instance, constructor->get(exec, exec->propertyNames().prototype));
110 static JSObjectRef makeWrapper(JSContextRef ctx, JSClassRef jsClass, id wrappedObject)
112 JSC::ExecState* exec = toJS(ctx);
113 JSC::JSLockHolder locker(exec);
116 JSC::JSCallbackObject<JSC::JSAPIWrapperObject>* object = JSC::JSCallbackObject<JSC::JSAPIWrapperObject>::create(exec, exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->objcWrapperObjectStructure(), jsClass, 0);
117 object->setWrappedObject(wrappedObject);
118 if (JSC::JSObject* prototype = jsClass->prototype(exec))
119 object->setPrototype(exec->vm(), prototype);
121 return toRef(object);
124 // Make an object that is in all ways a completely vanilla JavaScript object,
125 // other than that it has a native brand set that will be displayed by the default
126 // Object.prototype.toString conversion.
127 static JSValue *objectWithCustomBrand(JSContext *context, NSString *brand, Class cls = 0)
129 JSClassDefinition definition;
130 definition = kJSClassDefinitionEmpty;
131 definition.className = [brand UTF8String];
132 JSClassRef classRef = JSClassCreate(&definition);
133 JSObjectRef result = makeWrapper([context JSGlobalContextRef], classRef, cls);
134 JSClassRelease(classRef);
135 return [JSValue valueWithJSValueRef:result inContext:context];
138 static JSValue *constructorWithCustomBrand(JSContext *context, NSString *brand, Class cls)
140 JSClassDefinition definition;
141 definition = kJSClassDefinitionEmpty;
142 definition.className = [brand UTF8String];
143 definition.hasInstance = constructorHasInstance;
144 JSClassRef classRef = JSClassCreate(&definition);
145 JSObjectRef result = makeWrapper([context JSGlobalContextRef], classRef, cls);
146 JSClassRelease(classRef);
147 return [JSValue valueWithJSValueRef:result inContext:context];
150 // Look for @optional properties in the prototype containing a selector to property
151 // name mapping, separated by a __JS_EXPORT_AS__ delimiter.
152 static NSMutableDictionary *createRenameMap(Protocol *protocol, BOOL isInstanceMethod)
154 NSMutableDictionary *renameMap = [[NSMutableDictionary alloc] init];
156 forEachMethodInProtocol(protocol, NO, isInstanceMethod, ^(SEL sel, const char*){
157 NSString *rename = @(sel_getName(sel));
158 NSRange range = [rename rangeOfString:@"__JS_EXPORT_AS__"];
159 if (range.location == NSNotFound)
161 NSString *selector = [rename substringToIndex:range.location];
162 NSUInteger begin = range.location + range.length;
163 NSUInteger length = [rename length] - begin - 1;
164 NSString *name = [rename substringWithRange:(NSRange){ begin, length }];
165 renameMap[selector] = name;
171 inline void putNonEnumerable(JSValue *base, NSString *propertyName, JSValue *value)
173 [base defineProperty:propertyName descriptor:@{
174 JSPropertyDescriptorValueKey: value,
175 JSPropertyDescriptorWritableKey: @YES,
176 JSPropertyDescriptorEnumerableKey: @NO,
177 JSPropertyDescriptorConfigurableKey: @YES
181 static bool isInitFamilyMethod(NSString *name)
185 // Skip over initial underscores.
186 for (; i < [name length]; ++i) {
187 if ([name characterAtIndex:i] != '_')
192 NSUInteger initIndex = 0;
193 NSString* init = @"init";
194 for (; i < [name length] && initIndex < [init length]; ++i, ++initIndex) {
195 if ([name characterAtIndex:i] != [init characterAtIndex:initIndex])
199 // We didn't match all of 'init'.
200 if (initIndex < [init length])
203 // If we're at the end or the next character is a capital letter then this is an init-family selector.
204 return i == [name length] || [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[name characterAtIndex:i]];
207 static bool shouldSkipMethodWithName(NSString *name)
209 // For clients that don't support init-based constructors just copy
210 // over the init method as we would have before.
211 if (!supportsInitMethodConstructors())
214 // Skip over init family methods because we handle those specially
215 // for the purposes of hooking up the constructor correctly.
216 return isInitFamilyMethod(name);
219 // This method will iterate over the set of required methods in the protocol, and:
220 // * Determine a property name (either via a renameMap or default conversion).
221 // * If an accessorMap is provided, and contains this name, store the method in the map.
222 // * Otherwise, if the object doesn't already contain a property with name, create it.
223 static void copyMethodsToObject(JSContext *context, Class objcClass, Protocol *protocol, BOOL isInstanceMethod, JSValue *object, NSMutableDictionary *accessorMethods = nil)
225 NSMutableDictionary *renameMap = createRenameMap(protocol, isInstanceMethod);
227 forEachMethodInProtocol(protocol, YES, isInstanceMethod, ^(SEL sel, const char* types){
228 const char* nameCStr = sel_getName(sel);
229 NSString *name = @(nameCStr);
231 if (shouldSkipMethodWithName(name))
234 if (accessorMethods && accessorMethods[name]) {
235 JSObjectRef method = objCCallbackFunctionForMethod(context, objcClass, protocol, isInstanceMethod, sel, types);
238 accessorMethods[name] = [JSValue valueWithJSValueRef:method inContext:context];
240 name = renameMap[name];
242 name = selectorToPropertyName(nameCStr);
243 if ([object hasProperty:name])
245 JSObjectRef method = objCCallbackFunctionForMethod(context, objcClass, protocol, isInstanceMethod, sel, types);
247 putNonEnumerable(object, name, [JSValue valueWithJSValueRef:method inContext:context]);
254 static bool parsePropertyAttributes(objc_property_t property, char*& getterName, char*& setterName)
256 bool readonly = false;
257 unsigned attributeCount;
258 objc_property_attribute_t* attributes = property_copyAttributeList(property, &attributeCount);
259 if (attributeCount) {
260 for (unsigned i = 0; i < attributeCount; ++i) {
261 switch (*(attributes[i].name)) {
263 getterName = strdup(attributes[i].value);
266 setterName = strdup(attributes[i].value);
280 static char* makeSetterName(const char* name)
282 size_t nameLength = strlen(name);
283 char* setterName = (char*)malloc(nameLength + 5); // "set" Name ":\0"
287 setterName[3] = toupper(*name);
288 memcpy(setterName + 4, name + 1, nameLength - 1);
289 setterName[nameLength + 3] = ':';
290 setterName[nameLength + 4] = '\0';
294 static void copyPrototypeProperties(JSContext *context, Class objcClass, Protocol *protocol, JSValue *prototypeValue)
296 // First gather propreties into this list, then handle the methods (capturing the accessor methods).
302 __block Vector<Property> propertyList;
304 // Map recording the methods used as getters/setters.
305 NSMutableDictionary *accessorMethods = [NSMutableDictionary dictionary];
308 JSValue *undefined = [JSValue valueWithUndefinedInContext:context];
310 forEachPropertyInProtocol(protocol, ^(objc_property_t property){
311 char* getterName = 0;
312 char* setterName = 0;
313 bool readonly = parsePropertyAttributes(property, getterName, setterName);
314 const char* name = property_getName(property);
316 // Add the names of the getter & setter methods to
318 getterName = strdup(name);
319 accessorMethods[@(getterName)] = undefined;
322 setterName = makeSetterName(name);
323 accessorMethods[@(setterName)] = undefined;
326 // Add the properties to a list.
327 propertyList.append((Property){ name, getterName, setterName });
330 // Copy methods to the prototype, capturing accessors in the accessorMethods map.
331 copyMethodsToObject(context, objcClass, protocol, YES, prototypeValue, accessorMethods);
333 // Iterate the propertyList & generate accessor properties.
334 for (size_t i = 0; i < propertyList.size(); ++i) {
335 Property& property = propertyList[i];
337 JSValue *getter = accessorMethods[@(property.getterName)];
338 free(property.getterName);
339 ASSERT(![getter isUndefined]);
341 JSValue *setter = undefined;
342 if (property.setterName) {
343 setter = accessorMethods[@(property.setterName)];
344 free(property.setterName);
345 ASSERT(![setter isUndefined]);
348 [prototypeValue defineProperty:@(property.name) descriptor:@{
349 JSPropertyDescriptorGetKey: getter,
350 JSPropertyDescriptorSetKey: setter,
351 JSPropertyDescriptorEnumerableKey: @NO,
352 JSPropertyDescriptorConfigurableKey: @YES
357 @interface JSObjCClassInfo : NSObject {
358 JSContext *m_context;
361 JSClassRef m_classRef;
362 JSC::Weak<JSC::JSObject> m_prototype;
363 JSC::Weak<JSC::JSObject> m_constructor;
366 - (id)initWithContext:(JSContext *)context forClass:(Class)cls;
367 - (JSValue *)wrapperForObject:(id)object;
368 - (JSValue *)constructor;
369 - (JSC::JSObject *)prototype;
373 @implementation JSObjCClassInfo
375 - (id)initWithContext:(JSContext *)context forClass:(Class)cls
381 const char* className = class_getName(cls);
384 m_block = [cls isSubclassOfClass:getNSBlockClass()];
385 JSClassDefinition definition;
386 definition = kJSClassDefinitionEmpty;
387 definition.className = className;
388 m_classRef = JSClassCreate(&definition);
395 JSClassRelease(m_classRef);
399 static JSValue *allocateConstructorForCustomClass(JSContext *context, const char* className, Class cls)
401 if (!supportsInitMethodConstructors())
402 return constructorWithCustomBrand(context, [NSString stringWithFormat:@"%sConstructor", className], cls);
404 // For each protocol that the class implements, gather all of the init family methods into a hash table.
405 __block HashMap<String, Protocol *> initTable;
406 Protocol *exportProtocol = getJSExportProtocol();
407 for (Class currentClass = cls; currentClass; currentClass = class_getSuperclass(currentClass)) {
408 forEachProtocolImplementingProtocol(currentClass, exportProtocol, ^(Protocol *protocol) {
409 forEachMethodInProtocol(protocol, YES, YES, ^(SEL selector, const char*) {
410 const char* name = sel_getName(selector);
411 if (!isInitFamilyMethod(@(name)))
413 initTable.set(name, protocol);
418 for (Class currentClass = cls; currentClass; currentClass = class_getSuperclass(currentClass)) {
419 __block unsigned numberOfInitsFound = 0;
420 __block SEL initMethod = 0;
421 __block Protocol *initProtocol = 0;
422 __block const char* types = 0;
423 forEachMethodInClass(currentClass, ^(Method method) {
424 SEL selector = method_getName(method);
425 const char* name = sel_getName(selector);
426 auto iter = initTable.find(name);
428 if (iter == initTable.end())
431 numberOfInitsFound++;
432 initMethod = selector;
433 initProtocol = iter->value;
434 types = method_getTypeEncoding(method);
437 if (!numberOfInitsFound)
440 if (numberOfInitsFound > 1) {
441 NSLog(@"ERROR: Class %@ exported more than one init family method via JSExport. Class %@ will not have a callable JavaScript constructor function.", cls, cls);
445 JSObjectRef method = objCCallbackFunctionForInit(context, cls, initProtocol, initMethod, types);
446 return [JSValue valueWithJSValueRef:method inContext:context];
448 return constructorWithCustomBrand(context, [NSString stringWithFormat:@"%sConstructor", className], cls);
451 typedef std::pair<JSC::JSObject*, JSC::JSObject*> ConstructorPrototypePair;
453 - (ConstructorPrototypePair)allocateConstructorAndPrototype
455 JSObjCClassInfo* superClassInfo = [m_context.wrapperMap classInfoForClass:class_getSuperclass(m_class)];
457 ASSERT(!m_constructor || !m_prototype);
458 ASSERT((m_class == [NSObject class]) == !superClassInfo);
459 if (!superClassInfo) {
460 JSContextRef cContext = [m_context JSGlobalContextRef];
461 JSValue *constructor = m_context[@"Object"];
463 m_constructor = toJS(JSValueToObject(cContext, valueInternalValue(constructor), 0));
466 JSValue *prototype = constructor[@"prototype"];
467 m_prototype = toJS(JSValueToObject(cContext, valueInternalValue(prototype), 0));
470 const char* className = class_getName(m_class);
472 // Create or grab the prototype/constructor pair.
474 JSValue *constructor;
476 prototype = [JSValue valueWithJSValueRef:toRef(m_prototype.get()) inContext:m_context];
478 prototype = objectWithCustomBrand(m_context, [NSString stringWithFormat:@"%sPrototype", className]);
481 constructor = [JSValue valueWithJSValueRef:toRef(m_constructor.get()) inContext:m_context];
483 constructor = allocateConstructorForCustomClass(m_context, className, m_class);
485 JSContextRef cContext = [m_context JSGlobalContextRef];
486 m_prototype = toJS(JSValueToObject(cContext, valueInternalValue(prototype), 0));
487 m_constructor = toJS(JSValueToObject(cContext, valueInternalValue(constructor), 0));
489 putNonEnumerable(prototype, @"constructor", constructor);
490 putNonEnumerable(constructor, @"prototype", prototype);
492 Protocol *exportProtocol = getJSExportProtocol();
493 forEachProtocolImplementingProtocol(m_class, exportProtocol, ^(Protocol *protocol){
494 copyPrototypeProperties(m_context, m_class, protocol, prototype);
495 copyMethodsToObject(m_context, m_class, protocol, NO, constructor);
499 JSC::JSObject* superClassPrototype = [superClassInfo prototype];
500 JSObjectSetPrototype([m_context JSGlobalContextRef], toRef(m_prototype.get()), toRef(superClassPrototype));
502 return ConstructorPrototypePair(m_constructor.get(), m_prototype.get());
505 - (JSValue *)wrapperForObject:(id)object
507 ASSERT([object isKindOfClass:m_class]);
508 ASSERT(m_block == [object isKindOfClass:getNSBlockClass()]);
510 if (JSObjectRef method = objCCallbackFunctionForBlock(m_context, object)) {
511 JSValue *constructor = [JSValue valueWithJSValueRef:method inContext:m_context];
512 JSValue *prototype = [JSValue valueWithNewObjectInContext:m_context];
513 putNonEnumerable(constructor, @"prototype", prototype);
514 putNonEnumerable(prototype, @"constructor", constructor);
519 JSC::JSObject* prototype = [self prototype];
521 JSObjectRef wrapper = makeWrapper([m_context JSGlobalContextRef], m_classRef, object);
522 JSObjectSetPrototype([m_context JSGlobalContextRef], wrapper, toRef(prototype));
523 return [JSValue valueWithJSValueRef:wrapper inContext:m_context];
526 - (JSValue *)constructor
528 JSC::JSObject* constructor = m_constructor.get();
530 constructor = [self allocateConstructorAndPrototype].first;
531 ASSERT(!!constructor);
532 return [JSValue valueWithJSValueRef:toRef(constructor) inContext:m_context];
535 - (JSC::JSObject*)prototype
537 JSC::JSObject* prototype = m_prototype.get();
539 prototype = [self allocateConstructorAndPrototype].second;
546 @implementation JSWrapperMap {
547 JSContext *m_context;
548 NSMutableDictionary *m_classMap;
549 JSC::WeakGCMap<id, JSC::JSObject> m_cachedJSWrappers;
550 NSMapTable *m_cachedObjCWrappers;
553 - (id)initWithContext:(JSContext *)context
559 NSPointerFunctionsOptions keyOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality;
560 NSPointerFunctionsOptions valueOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
561 m_cachedObjCWrappers = [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:valueOptions capacity:0];
564 m_classMap = [[NSMutableDictionary alloc] init];
570 [m_cachedObjCWrappers release];
571 [m_classMap release];
575 - (JSObjCClassInfo*)classInfoForClass:(Class)cls
580 // Check if we've already created a JSObjCClassInfo for this Class.
581 if (JSObjCClassInfo* classInfo = (JSObjCClassInfo*)m_classMap[cls])
584 // Skip internal classes beginning with '_' - just copy link to the parent class's info.
585 if ('_' == *class_getName(cls))
586 return m_classMap[cls] = [self classInfoForClass:class_getSuperclass(cls)];
588 return m_classMap[cls] = [[[JSObjCClassInfo alloc] initWithContext:m_context forClass:cls] autorelease];
591 - (JSValue *)jsWrapperForObject:(id)object
593 JSC::JSObject* jsWrapper = m_cachedJSWrappers.get(object);
595 return [JSValue valueWithJSValueRef:toRef(jsWrapper) inContext:m_context];
598 if (class_isMetaClass(object_getClass(object)))
599 wrapper = [[self classInfoForClass:(Class)object] constructor];
601 JSObjCClassInfo* classInfo = [self classInfoForClass:[object class]];
602 wrapper = [classInfo wrapperForObject:object];
605 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=105891
606 // This general approach to wrapper caching is pretty effective, but there are a couple of problems:
607 // (1) For immortal objects JSValues will effectively leak and this results in error output being logged - we should avoid adding associated objects to immortal objects.
608 // (2) A long lived object may rack up many JSValues. When the contexts are released these will unprotect the associated JavaScript objects,
609 // but still, would probably nicer if we made it so that only one associated object was required, broadcasting object dealloc.
610 JSC::ExecState* exec = toJS([m_context JSGlobalContextRef]);
611 jsWrapper = toJS(exec, valueInternalValue(wrapper)).toObject(exec);
612 m_cachedJSWrappers.set(object, jsWrapper);
616 - (JSValue *)objcWrapperForJSValueRef:(JSValueRef)value
618 JSValue *wrapper = static_cast<JSValue *>(NSMapGet(m_cachedObjCWrappers, value));
620 wrapper = [[[JSValue alloc] initWithValue:value inContext:m_context] autorelease];
621 NSMapInsert(m_cachedObjCWrappers, value, wrapper);
628 id tryUnwrapObjcObject(JSGlobalContextRef context, JSValueRef value)
630 if (!JSValueIsObject(context, value))
632 JSValueRef exception = 0;
633 JSObjectRef object = JSValueToObject(context, value, &exception);
635 JSC::JSLockHolder locker(toJS(context));
636 if (toJS(object)->inherits(JSC::JSCallbackObject<JSC::JSAPIWrapperObject>::info()))
637 return (id)JSC::jsCast<JSC::JSAPIWrapperObject*>(toJS(object))->wrappedObject();
638 if (id target = tryUnwrapConstructor(object))
643 // This class ensures that the JSExport protocol is registered with the runtime.
644 NS_ROOT_CLASS @interface JSExport <JSExport>
646 @implementation JSExport
649 bool supportsInitMethodConstructors()
651 static int32_t versionOfLinkTimeLibrary = 0;
652 if (!versionOfLinkTimeLibrary)
653 versionOfLinkTimeLibrary = NSVersionOfLinkTimeLibrary("JavaScriptCore");
654 return versionOfLinkTimeLibrary >= webkitFirstVersionWithInitConstructorSupport;
657 Protocol *getJSExportProtocol()
659 static Protocol *protocol = objc_getProtocol("JSExport");
663 Class getNSBlockClass()
665 static Class cls = objc_getClass("NSBlock");