2 * Copyright (C) 2013 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
33 #import "JSAPIWrapperObject.h"
34 #import "JSCallbackObject.h"
35 #import "JSContextInternal.h"
36 #import "JSWrapperMap.h"
37 #import "ObjCCallbackFunction.h"
38 #import "ObjcRuntimeExtras.h"
39 #import "Operations.h"
41 #import <wtf/TCSpinLock.h>
42 #import <wtf/Vector.h>
44 @class JSObjCClassInfo;
46 @interface JSWrapperMap ()
48 - (JSObjCClassInfo*)classInfoForClass:(Class)cls;
52 // Default conversion of selectors to property names.
53 // All semicolons are removed, lowercase letters following a semicolon are capitalized.
54 static NSString *selectorToPropertyName(const char* start)
56 // Use 'index' to check for colons, if there are none, this is easy!
57 const char* firstColon = index(start, ':');
59 return [NSString stringWithUTF8String:start];
61 // 'header' is the length of string up to the first colon.
62 size_t header = firstColon - start;
63 // The new string needs to be long enough to hold 'header', plus the remainder of the string, excluding
64 // at least one ':', but including a '\0'. (This is conservative if there are more than one ':').
65 char* buffer = static_cast<char*>(malloc(header + strlen(firstColon + 1) + 1));
66 // Copy 'header' characters, set output to point to the end of this & input to point past the first ':'.
67 memcpy(buffer, start, header);
68 char* output = buffer + header;
69 const char* input = start + header + 1;
71 // On entry to the loop, we have already skipped over a ':' from the input.
74 // Skip over any additional ':'s. We'll leave c holding the next character after the
75 // last ':', and input pointing past c.
76 while ((c = *(input++)) == ':');
77 // Copy the character, converting to upper case if necessary.
78 // If the character we copy is '\0', then we're done!
79 if (!(*(output++) = toupper(c)))
81 // Loop over characters other than ':'.
82 while ((c = *(input++)) != ':') {
83 // Copy the character.
84 // If the character we copy is '\0', then we're done!
85 if (!(*(output++) = c))
88 // If we get here, we've consumed a ':' - wash, rinse, repeat.
91 NSString *result = [NSString stringWithUTF8String:buffer];
96 static JSObjectRef makeWrapper(JSContextRef ctx, JSClassRef jsClass, id wrappedObject)
98 JSC::ExecState* exec = toJS(ctx);
99 JSC::APIEntryShim entryShim(exec);
102 JSC::JSCallbackObject<JSC::JSAPIWrapperObject>* object = JSC::JSCallbackObject<JSC::JSAPIWrapperObject>::create(exec, exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->objcWrapperObjectStructure(), jsClass, 0);
103 object->setWrappedObject(wrappedObject);
104 if (JSC::JSObject* prototype = jsClass->prototype(exec))
105 object->setPrototype(exec->vm(), prototype);
107 return toRef(object);
110 // Make an object that is in all ways a completely vanilla JavaScript object,
111 // other than that it has a native brand set that will be displayed by the default
112 // Object.prototype.toString conversion.
113 static JSValue *objectWithCustomBrand(JSContext *context, NSString *brand, Class cls = 0)
115 JSClassDefinition definition;
116 definition = kJSClassDefinitionEmpty;
117 definition.className = [brand UTF8String];
118 JSClassRef classRef = JSClassCreate(&definition);
119 JSObjectRef result = makeWrapper([context JSGlobalContextRef], classRef, cls);
120 JSClassRelease(classRef);
121 return [JSValue valueWithJSValueRef:result inContext:context];
124 // Look for @optional properties in the prototype containing a selector to property
125 // name mapping, separated by a __JS_EXPORT_AS__ delimiter.
126 static NSMutableDictionary *createRenameMap(Protocol *protocol, BOOL isInstanceMethod)
128 NSMutableDictionary *renameMap = [[NSMutableDictionary alloc] init];
130 forEachMethodInProtocol(protocol, NO, isInstanceMethod, ^(SEL sel, const char*){
131 NSString *rename = @(sel_getName(sel));
132 NSRange range = [rename rangeOfString:@"__JS_EXPORT_AS__"];
133 if (range.location == NSNotFound)
135 NSString *selector = [rename substringToIndex:range.location];
136 NSUInteger begin = range.location + range.length;
137 NSUInteger length = [rename length] - begin - 1;
138 NSString *name = [rename substringWithRange:(NSRange){ begin, length }];
139 renameMap[selector] = name;
145 inline void putNonEnumerable(JSValue *base, NSString *propertyName, JSValue *value)
147 [base defineProperty:propertyName descriptor:@{
148 JSPropertyDescriptorValueKey: value,
149 JSPropertyDescriptorWritableKey: @YES,
150 JSPropertyDescriptorEnumerableKey: @NO,
151 JSPropertyDescriptorConfigurableKey: @YES
155 // This method will iterate over the set of required methods in the protocol, and:
156 // * Determine a property name (either via a renameMap or default conversion).
157 // * If an accessorMap is provided, and contains this name, store the method in the map.
158 // * Otherwise, if the object doesn't already contain a property with name, create it.
159 static void copyMethodsToObject(JSContext *context, Class objcClass, Protocol *protocol, BOOL isInstanceMethod, JSValue *object, NSMutableDictionary *accessorMethods = nil)
161 NSMutableDictionary *renameMap = createRenameMap(protocol, isInstanceMethod);
163 forEachMethodInProtocol(protocol, YES, isInstanceMethod, ^(SEL sel, const char* types){
164 const char* nameCStr = sel_getName(sel);
165 NSString *name = @(nameCStr);
166 if (accessorMethods && accessorMethods[name]) {
167 JSObjectRef method = objCCallbackFunctionForMethod(context, objcClass, protocol, isInstanceMethod, sel, types);
170 accessorMethods[name] = [JSValue valueWithJSValueRef:method inContext:context];
172 name = renameMap[name];
174 name = selectorToPropertyName(nameCStr);
175 if ([object hasProperty:name])
177 JSObjectRef method = objCCallbackFunctionForMethod(context, objcClass, protocol, isInstanceMethod, sel, types);
179 putNonEnumerable(object, name, [JSValue valueWithJSValueRef:method inContext:context]);
186 static bool parsePropertyAttributes(objc_property_t property, char*& getterName, char*& setterName)
188 bool readonly = false;
189 unsigned attributeCount;
190 objc_property_attribute_t* attributes = property_copyAttributeList(property, &attributeCount);
191 if (attributeCount) {
192 for (unsigned i = 0; i < attributeCount; ++i) {
193 switch (*(attributes[i].name)) {
195 getterName = strdup(attributes[i].value);
198 setterName = strdup(attributes[i].value);
212 static char* makeSetterName(const char* name)
214 size_t nameLength = strlen(name);
215 char* setterName = (char*)malloc(nameLength + 5); // "set" Name ":\0"
219 setterName[3] = toupper(*name);
220 memcpy(setterName + 4, name + 1, nameLength - 1);
221 setterName[nameLength + 3] = ':';
222 setterName[nameLength + 4] = '\0';
226 static void copyPrototypeProperties(JSContext *context, Class objcClass, Protocol *protocol, JSValue *prototypeValue)
228 // First gather propreties into this list, then handle the methods (capturing the accessor methods).
234 __block Vector<Property> propertyList;
236 // Map recording the methods used as getters/setters.
237 NSMutableDictionary *accessorMethods = [NSMutableDictionary dictionary];
240 JSValue *undefined = [JSValue valueWithUndefinedInContext:context];
242 forEachPropertyInProtocol(protocol, ^(objc_property_t property){
243 char* getterName = 0;
244 char* setterName = 0;
245 bool readonly = parsePropertyAttributes(property, getterName, setterName);
246 const char* name = property_getName(property);
248 // Add the names of the getter & setter methods to
250 getterName = strdup(name);
251 accessorMethods[@(getterName)] = undefined;
254 setterName = makeSetterName(name);
255 accessorMethods[@(setterName)] = undefined;
258 // Add the properties to a list.
259 propertyList.append((Property){ name, getterName, setterName });
262 // Copy methods to the prototype, capturing accessors in the accessorMethods map.
263 copyMethodsToObject(context, objcClass, protocol, YES, prototypeValue, accessorMethods);
265 // Iterate the propertyList & generate accessor properties.
266 for (size_t i = 0; i < propertyList.size(); ++i) {
267 Property& property = propertyList[i];
269 JSValue *getter = accessorMethods[@(property.getterName)];
270 free(property.getterName);
271 ASSERT(![getter isUndefined]);
273 JSValue *setter = undefined;
274 if (property.setterName) {
275 setter = accessorMethods[@(property.setterName)];
276 free(property.setterName);
277 ASSERT(![setter isUndefined]);
280 [prototypeValue defineProperty:@(property.name) descriptor:@{
281 JSPropertyDescriptorGetKey: getter,
282 JSPropertyDescriptorSetKey: setter,
283 JSPropertyDescriptorEnumerableKey: @NO,
284 JSPropertyDescriptorConfigurableKey: @YES
289 @interface JSObjCClassInfo : NSObject {
290 JSContext *m_context;
293 JSClassRef m_classRef;
294 JSC::Weak<JSC::JSObject> m_prototype;
295 JSC::Weak<JSC::JSObject> m_constructor;
298 - (id)initWithContext:(JSContext *)context forClass:(Class)cls superClassInfo:(JSObjCClassInfo*)superClassInfo;
299 - (JSValue *)wrapperForObject:(id)object;
300 - (JSValue *)constructor;
304 @implementation JSObjCClassInfo
306 - (id)initWithContext:(JSContext *)context forClass:(Class)cls superClassInfo:(JSObjCClassInfo*)superClassInfo
312 const char* className = class_getName(cls);
315 m_block = [cls isSubclassOfClass:getNSBlockClass()];
316 JSClassDefinition definition;
317 definition = kJSClassDefinitionEmpty;
318 definition.className = className;
319 m_classRef = JSClassCreate(&definition);
321 [self allocateConstructorAndPrototypeWithSuperClassInfo:superClassInfo];
328 JSClassRelease(m_classRef);
332 - (void)allocateConstructorAndPrototypeWithSuperClassInfo:(JSObjCClassInfo*)superClassInfo
334 ASSERT(!m_constructor || !m_prototype);
335 ASSERT((m_class == [NSObject class]) == !superClassInfo);
336 if (!superClassInfo) {
337 JSContextRef cContext = [m_context JSGlobalContextRef];
338 JSValue *constructor = m_context[@"Object"];
340 m_constructor = toJS(JSValueToObject(cContext, valueInternalValue(constructor), 0));
343 JSValue *prototype = constructor[@"prototype"];
344 m_prototype = toJS(JSValueToObject(cContext, valueInternalValue(prototype), 0));
347 const char* className = class_getName(m_class);
349 // Create or grab the prototype/constructor pair.
351 JSValue *constructor;
353 prototype = [JSValue valueWithJSValueRef:toRef(m_prototype.get()) inContext:m_context];
355 prototype = objectWithCustomBrand(m_context, [NSString stringWithFormat:@"%sPrototype", className]);
358 constructor = [JSValue valueWithJSValueRef:toRef(m_constructor.get()) inContext:m_context];
360 constructor = objectWithCustomBrand(m_context, [NSString stringWithFormat:@"%sConstructor", className], m_class);
362 JSContextRef cContext = [m_context JSGlobalContextRef];
363 m_prototype = toJS(JSValueToObject(cContext, valueInternalValue(prototype), 0));
364 m_constructor = toJS(JSValueToObject(cContext, valueInternalValue(constructor), 0));
366 putNonEnumerable(prototype, @"constructor", constructor);
367 putNonEnumerable(constructor, @"prototype", prototype);
369 Protocol *exportProtocol = getJSExportProtocol();
370 forEachProtocolImplementingProtocol(m_class, exportProtocol, ^(Protocol *protocol){
371 copyPrototypeProperties(m_context, m_class, protocol, prototype);
372 copyMethodsToObject(m_context, m_class, protocol, NO, constructor);
376 JSObjectSetPrototype([m_context JSGlobalContextRef], toRef(m_prototype.get()), toRef(superClassInfo->m_prototype.get()));
380 - (void)reallocateConstructorAndOrPrototype
382 [self allocateConstructorAndPrototypeWithSuperClassInfo:[m_context.wrapperMap classInfoForClass:class_getSuperclass(m_class)]];
385 - (JSValue *)wrapperForObject:(id)object
387 ASSERT([object isKindOfClass:m_class]);
388 ASSERT(m_block == [object isKindOfClass:getNSBlockClass()]);
390 if (JSObjectRef method = objCCallbackFunctionForBlock(m_context, object))
391 return [JSValue valueWithJSValueRef:method inContext:m_context];
395 [self reallocateConstructorAndOrPrototype];
396 ASSERT(!!m_prototype);
398 JSObjectRef wrapper = makeWrapper([m_context JSGlobalContextRef], m_classRef, object);
399 JSObjectSetPrototype([m_context JSGlobalContextRef], wrapper, toRef(m_prototype.get()));
400 return [JSValue valueWithJSValueRef:wrapper inContext:m_context];
403 - (JSValue *)constructor
406 [self reallocateConstructorAndOrPrototype];
407 ASSERT(!!m_constructor);
408 return [JSValue valueWithJSValueRef:toRef(m_constructor.get()) inContext:m_context];
413 @implementation JSWrapperMap {
414 JSContext *m_context;
415 NSMutableDictionary *m_classMap;
416 JSC::WeakGCMap<id, JSC::JSObject> m_cachedJSWrappers;
417 NSMapTable *m_cachedObjCWrappers;
420 - (id)initWithContext:(JSContext *)context
426 NSPointerFunctionsOptions keyOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality;
427 NSPointerFunctionsOptions valueOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
428 m_cachedObjCWrappers = [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:valueOptions capacity:0];
431 m_classMap = [[NSMutableDictionary alloc] init];
437 [m_cachedObjCWrappers release];
438 [m_classMap release];
442 - (JSObjCClassInfo*)classInfoForClass:(Class)cls
447 // Check if we've already created a JSObjCClassInfo for this Class.
448 if (JSObjCClassInfo* classInfo = (JSObjCClassInfo*)m_classMap[cls])
451 // Skip internal classes beginning with '_' - just copy link to the parent class's info.
452 if ('_' == *class_getName(cls))
453 return m_classMap[cls] = [self classInfoForClass:class_getSuperclass(cls)];
455 return m_classMap[cls] = [[[JSObjCClassInfo alloc] initWithContext:m_context forClass:cls superClassInfo:[self classInfoForClass:class_getSuperclass(cls)]] autorelease];
458 - (JSValue *)jsWrapperForObject:(id)object
460 JSC::JSObject* jsWrapper = m_cachedJSWrappers.get(object);
462 return [JSValue valueWithJSValueRef:toRef(jsWrapper) inContext:m_context];
465 if (class_isMetaClass(object_getClass(object)))
466 wrapper = [[self classInfoForClass:(Class)object] constructor];
468 JSObjCClassInfo* classInfo = [self classInfoForClass:[object class]];
469 wrapper = [classInfo wrapperForObject:object];
472 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=105891
473 // This general approach to wrapper caching is pretty effective, but there are a couple of problems:
474 // (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.
475 // (2) A long lived object may rack up many JSValues. When the contexts are released these will unprotect the associated JavaScript objects,
476 // but still, would probably nicer if we made it so that only one associated object was required, broadcasting object dealloc.
477 JSC::ExecState* exec = toJS([m_context JSGlobalContextRef]);
478 jsWrapper = toJS(exec, valueInternalValue(wrapper)).toObject(exec);
479 m_cachedJSWrappers.set(object, jsWrapper);
483 - (JSValue *)objcWrapperForJSValueRef:(JSValueRef)value
485 JSValue *wrapper = static_cast<JSValue *>(NSMapGet(m_cachedObjCWrappers, value));
487 wrapper = [[[JSValue alloc] initWithValue:value inContext:m_context] autorelease];
488 NSMapInsert(m_cachedObjCWrappers, value, wrapper);
495 id tryUnwrapObjcObject(JSGlobalContextRef context, JSValueRef value)
497 if (!JSValueIsObject(context, value))
499 JSValueRef exception = 0;
500 JSObjectRef object = JSValueToObject(context, value, &exception);
502 if (toJS(object)->inherits(&JSC::JSCallbackObject<JSC::JSAPIWrapperObject>::s_info))
503 return (id)JSC::jsCast<JSC::JSAPIWrapperObject*>(toJS(object))->wrappedObject();
504 if (id target = tryUnwrapBlock(object))
509 Protocol *getJSExportProtocol()
511 static Protocol *protocol = objc_getProtocol("JSExport");
515 Class getNSBlockClass()
517 static Class cls = objc_getClass("NSBlock");