JavaScriptCore Deep Dive 2 - API

Preface

Relatively speaking, this article is the closest one to everyday iOS development. It should feel familiar, yet also a little unfamiliar, because it adds some source-code analysis.

The public umbrella header JavaScriptCore.h exposes the main API surface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef JavaScriptCore_h
#define JavaScriptCore_h

#include <JavaScriptCore/JavaScript.h>
#include <JavaScriptCore/JSStringRefCF.h>

#if defined(__OBJC__) && JSC_OBJC_API_ENABLED

#import "JSContext.h"
#import "JSValue.h"
#import "JSManagedValue.h"
#import "JSVirtualMachine.h"
#import "JSExport.h"

#endif

#endif /* JavaScriptCore_h */

JavaScriptCore exposes several main header files to us. First, here is an overall relationship diagram:

JavaScriptCore Deep Dive 2 - API: Preface (figure 1)

Next, I will explain them one by one. While reading, you may need to jump back and forth, because some relationships feel like the classic chicken-and-egg problem: it is hard to tell which comes first.

JSVirtualMachine

An instance of JSVirtualMachine is a complete and independent JavaScript execution environment. It provides the underlying resources needed for JavaScript execution.

This class mainly does two things:

  • Enables concurrent JavaScript execution.
  • Manages memory for bridged JavaScript and Objective-C objects.

Every JSContext belongs to a JSVirtualMachine. Each virtual machine can contain multiple contexts and allows values, namely JSValue objects, to be passed between those contexts.

However, each virtual machine is complete and independent. It has its own heap and garbage collector. The GC cannot handle objects in another virtual machine’s heap, so values created in one virtual machine cannot be passed to another virtual machine.

Let’s peek at the source code, starting with the JSVirtualMachine header:

1
2
3
4
5
@interface JSVirtualMachine : NSObject
- (instancetype)init;
- (void)addManagedReference:(id)object withOwner:(id)owner;
- (void)removeManagedReference:(id)object withOwner:(id)owner;
@end

And then the .mm file:

1
2
3
4
5
6
@implementation JSVirtualMachine {
JSContextGroupRef m_group;// JSContext collection.
NSMapTable *m_contextCache;
NSMapTable *m_externalObjectGraph;
NSMapTable *m_externalRememberedSet;
}
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
- (instancetype)init
{
JSContextGroupRef group = JSContextGroupCreate();
self = [self initWithContextGroupRef:group];
// The extra JSContextGroupRetain is balanced here.
JSContextGroupRelease(group);
return self;
}

// The main logic is in initWithContextGroupRef:. This version is simplified.
- (instancetype)initWithContextGroupRef:(JSContextGroupRef)group
{
self = [super init];

// Retain operation.
m_group = JSContextGroupRetain(group);

// These three properties are actually NSMapTable hash tables.
m_contextCache = [[NSMapTable alloc] initWith...];
m_externalObjectGraph = [[NSMapTable alloc] initWith...];
m_externalRememberedSet = [[NSMapTable alloc] initWith...;

// Build the mapping between JSContextGroupRef and JSVirtualMachine.
[JSVMWrapperCache addWrapper:self forJSContextGroupRef:group];

return self;
}

The mapping in the second-to-last line is also stored in a global NSMapTable: JSContextGroupRef is the key, and JSVirtualMachine is the value. Given a JSContextGroupRef, it is therefore convenient to locate its owning JSVirtualMachine.

1
2
3
4
5
6
7
// globalWrapperCache = [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:valueOptions capacity:0];

+ (void)addWrapper:(JSVirtualMachine *)wrapper forJSContextGroupRef:(JSContextGroupRef)group
{
std::lock_guard<StaticLock> lock(wrapperCacheMutex);
NSMapInsert(globalWrapperCache, group, wrapper);
}

addManagedReference

The two managed-reference methods are what we really care about, because they involve memory management between JavaScript objects and Objective-C objects. To make this clearer, first look at how this method is called:

1
2
3
4
5
6
7
8
9
- (void)testDemo
{
JSContext *context = [[JSContext alloc] init];
JSValue *message = [JSValue valueWithObject:@"hello" inContext:context];
JSCollection *collection = [[JSCollection alloc] init];
JSValue *jsCollection = [JSValue valueWithObject:collection inContext:context];
JSManagedValue *weakCollection = [JSManagedValue managedValueWithValue:jsCollection andOwner:rootObject];
[context.virtualMachine addManagedReference:weakCollection withOwner:message];
}

The first parameter of addManagedReference is a JSManagedValue, and the second parameter is a JSValue.

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
- (void)addManagedReference:(id)object withOwner:(id)owner
{
// Increase the owner reference count.
if ([object isKindOfClass:[JSManagedValue class]])
[object didAddOwner:owner];

// Unwrap objects. See getInternalObjcObject.
object = getInternalObjcObject(object);
owner = getInternalObjcObject(owner);

if (!object || !owner) return;

JSC::JSLockHolder locker(toJS(m_group));
if ([self isOldExternalObject:owner] && ![self isOldExternalObject:object])
[self addExternalRememberedObject:owner];

// m_externalObjectGraph stores ownedObjects.
// ownedObjects stores the reference count of object.
NSMapTable *ownedObjects = [m_externalObjectGraph objectForKey:owner];
if (!ownedObjects) {
NSPointerFunctionsOptions weakIDOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
NSPointerFunctionsOptions integerOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsIntegerPersonality;
ownedObjects = [[NSMapTable alloc] initWithKeyOptions:weakIDOptions valueOptions:integerOptions capacity:1];

[m_externalObjectGraph setObject:ownedObjects forKey:owner];
[ownedObjects release];
}

size_t count = reinterpret_cast<size_t>(NSMapGet(ownedObjects, object));
NSMapInsert(ownedObjects, object, reinterpret_cast<void*>(count + 1));
}

didAddOwner

At the start of the method, didAddOwner increments the owner reference count for JSValue and stores it in m_owners, which is an NSMapTable *m_owners property of JSManagedValue.

1
2
3
4
5
- (void)didAddOwner:(id)owner
{
size_t count = reinterpret_cast<size_t>(NSMapGet(m_owners, owner));
NSMapInsert(m_owners, owner, reinterpret_cast<void*>(count + 1));
}

getInternalObjcObject

The next method, getInternalObjcObject, can be explained in one word: unwrap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static id getInternalObjcObject(id object)
{
if ([object isKindOfClass:[JSManagedValue class]]) {
// static_cast only checks the type at compile time; correctness must be guaranteed manually.
JSValue* value = [static_cast<JSManagedValue *>(object) value];
id temp = tryUnwrapObjcObject([value.context JSGlobalContextRef], [value JSValueRef]);
if (temp)
return temp;
return object;
}

if ([object isKindOfClass:[JSValue class]]) {
JSValue *value = static_cast<JSValue *>(object);
object = tryUnwrapObjcObject([value.context JSGlobalContextRef], [value JSValueRef]);
}

return object;
}

removeManagedReference

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
- (void)removeManagedReference:(id)object withOwner:(id)owner
{
// Decrease owner reference count for JSManagedValue.
if ([object isKindOfClass:[JSManagedValue class]])
[object didRemoveOwner:owner];

// Unwrap.
object = getInternalObjcObject(object);
owner = getInternalObjcObject(owner);

if (!object || !owner) return;

JSC::JSLockHolder locker(toJS(m_group));

// Find ownedObjects for owner.
NSMapTable *ownedObjects = [m_externalObjectGraph objectForKey:owner];
if (!ownedObjects) return;

// Find the reference count for object and decrement it.
size_t count = reinterpret_cast<size_t>(NSMapGet(ownedObjects, object));
if (count > 1) {
NSMapInsert(ownedObjects, object, reinterpret_cast<void*>(count - 1));
return;
}

if (count == 1)
NSMapRemove(ownedObjects, object);

if (![ownedObjects count]) {
[m_externalObjectGraph removeObjectForKey:owner];
[m_externalRememberedSet removeObjectForKey:owner];
}
}

didRemoveOwner

didRemoveOwner is the reverse process of didAddOwner. It decreases the reference count, and if it reaches zero, removes the owner from m_owners.

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void)didRemoveOwner:(id)owner
{
size_t count = reinterpret_cast<size_t>(NSMapGet(m_owners, owner));

if (!count) return;

if (count == 1) {
NSMapRemove(m_owners, owner);
return;
}

NSMapInsert(m_owners, owner, reinterpret_cast<void*>(count - 1));
}

Does this already feel messy? Let’s look at two diagrams first:

JavaScriptCore Deep Dive 2 - API: didRemoveOwner (figure 2) JavaScriptCore Deep Dive 2 - API: didRemoveOwner (figure 3)

Even at this point, we still have not fully explained how JSVirtualMachine and JSManagedValue achieve conditional strong retention without creating retain cycles.

Here is my inference:

Objective-C uses ARC for memory management, while JavaScript uses GC. Since we are already looking at JavaScriptCore source code, the GC implementation must exist at this level. In any case, for a JavaScript object to be truly released, the corresponding C++ object’s destructor must eventually be involved; otherwise GC could not work. With that premise, the code above becomes useful. When we use a JSManagedValue object, JMV, to wrap a JSValue object, JV, the JMV does not strongly retain JV; it weakly references it. As long as JMV is still alive, we can find at least one JMV corresponding to JV in m_externalObjectGraph. During garbage collection, this tells the GC not to release JV, even if JV’s reference count may already be zero and it may have become isolated. As long as JV’s memory block has not been released, we can continue accessing it. If at some point no JMV corresponding to JV can be found in m_externalObjectGraph, the GC can reclaim JV’s memory. And throughout this whole process, no retain cycle is created.

Some clues for this can also be seen in scanExternalObjectGraph. If you are interested, take a look at that method.

JSContext

A JSContext object represents a JavaScript execution environment. In native code, we use JSContext to execute JavaScript code, access values defined or computed in JavaScript, and allow JavaScript to access native objects, methods, and functions. It is like a bridge between Objective-C and JavaScript.

JavaScriptCore Deep Dive 2 - API: JSContext (figure 4)
1
2
3
4
5
6
SValue *value = [context evaluateScript:@"var a = 1+2*3;"];

NSLog(@"a = %@", [context objectForKeyedSubscript:@"a"]);
NSLog(@"a = %@", [context.globalObject objectForKeyedSubscript:@"a"]);
NSLog(@"a = %@", context[@"a"]);

JSContext Initialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine
{
self = [super init];

// JSContext strongly retains JSVirtualMachine.
m_virtualMachine = [virtualMachine retain];

// Get group from virtualMachine and create m_context inside that group.
m_context = JSGlobalContextCreateInGroup(getGroupFromVirtualMachine(virtualMachine), 0);

// Create m_wrapperMap to store JSValue objects.
m_wrapperMap = [[JSWrapperMap alloc] initWithContext:self];

// Add itself to the m_context dictionary in virtualMachine.
// One JSVirtualMachine can correspond to multiple JSContexts.
[m_virtualMachine addContext:self forGlobalContextRef:m_context];

return self;
}

Global Object

Let’s only glance at the global object, because going deeper into this method gets very complex. In short, one JSContext corresponds to one global object.

1
2
3
4
- (JSValue *)globalObject
{
return [JSValue valueWithJSValueRef:JSContextGetGlobalObject(m_context) inContext:self];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
JSObjectRef JSContextGetGlobalObject(JSContextRef ctx)
{
if (!ctx) {return 0;}

// Get current script execution state.
ExecState* exec = toJS(ctx);

// Lock.
JSLockHolder locker(exec);

// This is fairly complex; later articles may cover it.
return toRef(jsCast<JSObject*>(exec->lexicalGlobalObject()->methodTable()->toThis(exec->lexicalGlobalObject(), exec, NotStrictMode)));
}

Executing Scripts

1
2
3
4
5
6
7
8
9
- (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL
{
JSStringRef scriptJS = JSStringCreateWithCFString((CFStringRef)script);
JSStringRef sourceURLJS = sourceURL ? JSStringCreateWithCFString((CFStringRef)[sourceURL absoluteString]) : nullptr;
JSValueRef result = JSEvaluateScript(m_context, scriptJS, nullptr, sourceURLJS, 0, NULL);
if (sourceURLJS) JSStringRelease(sourceURLJS);
JSStringRelease(scriptJS);
return [JSValue valueWithJSValueRef:result inContext:self];
}

The core logic is in JSEvaluateScript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception)
{
// ExecState again: the current script execution state.
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);

JSObject* jsThisObject = toJS(thisObject);

startingLineNumber = std::max(1, startingLineNumber);

// evaluate sets "this" to the global object if it is NULL.
JSGlobalObject* globalObject = exec->vmEntryGlobalObject();

// Load source code.
SourceCode source = makeSource(script->string(), sourceURL ? sourceURL->string() : String(), TextPosition(OrdinalNumber::fromOneBasedInt(startingLineNumber), OrdinalNumber::first()));

// Execute JS code. This is the core entry point we want to analyze.
JSValue returnValue = profiledEvaluate(globalObject->globalExec(), ProfilingReason::API, source, jsThisObject, evaluationException);

// Convert to Ref form.
if (returnValue) return toRef(exec, returnValue);

return toRef(exec, jsUndefined());
}

JSValue

A JSValue instance is a reference to a JavaScript value. We use JSValue to convert basic data types, such as numbers and strings, between JavaScript and native code. We can also use it to create JavaScript objects that wrap native custom-class objects, or to create JavaScript functions implemented by native methods or blocks.

Every JSValue instance comes from a JSContext, which represents the JavaScript execution environment containing the value. Every JSValue strongly retains its JSContext. As long as any JSValue associated with a specific JSContext is retained, that JSContext stays alive. Other JSValue objects returned by instance methods of a JSValue belong to the same JSContext as the original JSValue.

Every JSValue is indirectly associated, through its JSContext, with a specific JSVirtualMachine that represents execution resources. A JSValue can only be passed to JSValue or JSContext instance methods managed by the same virtual machine. Passing a JSValue from one virtual machine into another virtual machine triggers an Objective-C exception.

Initialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- (JSValue *)initWithValue:(JSValueRef)value inContext:(JSContext *)context
{
if (!value || !context) return nil;

self = [super init];

// Notice: strongly retains context.
_context = [context retain];

// Store value, but do not strongly retain it.
m_value = value;

// This is equivalent to a GC protect count.
JSValueProtect([_context JSGlobalContextRef], m_value);

return self;
}

The second-to-last statement is equivalent to giving GC a strong reference. Tracing it further reveals a ProtectCountSet. When adding an element, it increments that element’s reference count so the element will not be released.

1
2
3
4
5
6
7
ProtectCountSet m_protectedValues;

void Heap::protect(JSValue k)
{
if (!k.isCell()) return;
m_protectedValues.add(k.asCell());
}

Type Conversion

The conversion relationship between Objective-C objects and JavaScript objects or values is:

1
2
3
4
5
6
7
8
9
10
11
12
  Objective-C type  |   JavaScript type
--------------------+---------------------
nil | undefined
NSNull | null
NSString | string
NSNumber | number, boolean
NSDictionary | Object object
NSArray | Array object
NSDate | Date object
NSBlock (1) | Function object (1)
id (2) | Wrapper object (2)
Class (3) | Constructor object (3)

Objective-C -> JavaScript

1
2
3
4
5
// Convert an Objective-C object to JSValue.
+ (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:objectToValue(context, value) inContext:context];
}
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
JSValueRef objectToValue(JSContext *context, id object)
{
JSGlobalContextRef contextRef = [context JSGlobalContextRef];

// Simple object.
ObjcContainerConvertor::Task task = objectToValueWithoutCopy(context, object);
if (task.type == ContainerNone) return task.js;

// Container object, which may contain simple objects or nested containers.
JSC::JSLockHolder locker(toJS(contextRef));
ObjcContainerConvertor convertor(context);
convertor.add(task);

do {
ObjcContainerConvertor::Task current = convertor.take();
JSObjectRef js = JSValueToObject(contextRef, current.js, 0);

if (current.type == ContainerArray) {
// Array.
NSArray *array = (NSArray *)current.objc;
NSUInteger count = [array count];
for (NSUInteger index = 0; index < count; ++index)
JSObjectSetPropertyAtIndex(contextRef, js, index, convertor.convert([array objectAtIndex:index]), 0);
}
else
{
// Dictionary.
NSDictionary *dictionary = (NSDictionary *)current.objc;
for (id key in [dictionary keyEnumerator]) {
if ([key isKindOfClass:[NSString class]]) {
JSStringRef propertyName = JSStringCreateWithCFString((CFStringRef)key);
JSObjectSetProperty(contextRef, js, propertyName, convertor.convert([dictionary objectForKey:key]), 0, 0);
JSStringRelease(propertyName);
}
}
}
} while (!convertor.isWorkListEmpty());

return task.js;
}
1
2
3
4
5
+ (JSValue *)valueWithJSValueRef:(JSValueRef)value inContext:(JSContext *)context
{
// context wraps JSValueRef, so JSValue cannot be separated from JSContext.
return [context wrapperForJSObject:value];
}

JavaScript -> Objective-C

1
2
3
4
5
6
7
8
9
10
11
- (id)toObject
{
return valueToObject(_context, m_value);
}

id valueToObject(JSContext *context, JSValueRef value)
{
JSContainerConvertor::Task result = valueToObjectWithoutCopy([context JSGlobalContextRef], value);
if (result.type == ContainerNone) return result.objc;
return containerValueToObject([context JSGlobalContextRef], result);
}
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
static id containerValueToObject(JSGlobalContextRef context, JSContainerConvertor::Task task)
{
JSC::JSLockHolder locker(toJS(context));
JSContainerConvertor convertor(context);
convertor.add(task);

do {
JSContainerConvertor::Task current = convertor.take();
JSObjectRef js = JSValueToObject(context, current.js, 0);

if (current.type == ContainerArray) {
ASSERT([current.objc isKindOfClass:[NSMutableArray class]]);
NSMutableArray *array = (NSMutableArray *)current.objc;

JSStringRef lengthString = JSStringCreateWithUTF8CString("length");
unsigned length = JSC::toUInt32(JSValueToNumber(context, JSObjectGetProperty(context, js, lengthString, 0), 0));
JSStringRelease(lengthString);

for (unsigned i = 0; i < length; ++i) {
id objc = convertor.convert(JSObjectGetPropertyAtIndex(context, js, i, 0));
[array addObject:objc ? objc : [NSNull null]];
}
} else {
NSMutableDictionary *dictionary = (NSMutableDictionary *)current.objc;
JSC::JSLockHolder locker(toJS(context));

JSPropertyNameArrayRef propertyNameArray = JSObjectCopyPropertyNames(context, js);
size_t length = JSPropertyNameArrayGetCount(propertyNameArray);

for (size_t i = 0; i < length; ++i) {
JSStringRef propertyName = JSPropertyNameArrayGetNameAtIndex(propertyNameArray, i);
if (id objc = convertor.convert(JSObjectGetProperty(context, js, propertyName, 0)))
dictionary[[(NSString *)JSStringCopyCFString(kCFAllocatorDefault, propertyName) autorelease]] = objc;
}

JSPropertyNameArrayRelease(propertyNameArray);
}

} while (!convertor.isWorkListEmpty());

return task.objc;
}

Helper Class: JSContainerConvertor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class JSContainerConvertor {
public:
struct Task {
JSValueRef js;
id objc;
ConversionType type;
};

JSContainerConvertor(JSGlobalContextRef context): m_context(context){}

id convert(JSValueRef property);
void add(Task);
Task take();
bool isWorkListEmpty() const { return !m_worklist.size(); }

private:
JSGlobalContextRef m_context;
HashMap<JSValueRef, id> m_objectMap;
Vector<Task> m_worklist;
Vector<JSC::Strong<JSC::Unknown>> m_jsValues;
};

JSManagedValue

Objective-C uses ARC, which cannot automatically solve retain cycles and requires manual handling by developers. JavaScript uses GC, where all references are strong references, but the garbage collector can resolve cyclic references. JavaScriptCore is the same: in most cases, we do not need to manually manage memory, but some cases need attention.

  • Do not hold a JSValue inside a native object exported to JavaScript. Every JSValue contains a JSContext, and this relationship can cause a retain cycle and memory leak.
1
2
3
4
JSValue *value = [JSValue valueWithObject:@"test" inContext:context];
context[@"block"] = ^(){
NSLog(@"%@", value);
};
JavaScriptCore Deep Dive 2 - API: JSManagedValue (figure 5)

Normally, we use weak for external references used inside a block to avoid retain cycles. But the memory of the JavaScript object corresponding to JSValue is managed and reclaimed by the virtual machine. This approach cannot accurately control the lifetime of the referenced JSValue inside the block. When the block needs to use it, the value may already have been reclaimed by the virtual machine.

JavaScriptCore Deep Dive 2 - API: JSManagedValue (figure 6)

Because the reference count of JSValue is zero, it is released too early and does not match our expectation.

Apple introduced conditional strong retention, or conditional retain, and the corresponding class is JSManagedValue.

A JSManagedValue object contains a JSValue. Its conditional-retain behavior allows it to manage memory automatically. The most basic use case is storing a JSValue inside a native object imported into JavaScript.

1
2
3
4
5
JSValue *value = [JSValue valueWithObject:@"test" inContext:context];
JSManagedValue *managedValue = [JSManagedValue managedValueWithValue:value andOwner:self];
context[@"block"] = ^(){
NSLog(@"%@", [managedValue value]);
};
  • “Conditional retain” means that the managed JSValue is guaranteed to be retained if either of the following two conditions is satisfied: the JSValue can be reached through the JavaScript object graph, or the JSManagedValue can be reached through the native object graph. The relationship can be recorded in the virtual machine through addManagedReference:withOwner:. Conversely, if neither condition is satisfied, JSManagedValue sets its value to nil and releases the JSValue.
JavaScriptCore Deep Dive 2 - API: JSManagedValue (figure 7)

Initialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@implementation JSManagedValue {
JSC::Weak<JSC::JSGlobalObject> m_globalObject;
RefPtr<JSC::JSLock> m_lock;
WeakValueRef m_weakValue;// Notice m_weakValue here.
NSMapTable *m_owners;
}


+ (JSManagedValue *)managedValueWithValue:(JSValue *)value andOwner:(id)owner
{
// JSManagedValue does not strongly retain JSValue here.
JSManagedValue *managedValue = [[self alloc] initWithValue:value];

// The virtualMachine corresponding to context strongly retains value.
[value.context.virtualMachine addManagedReference:managedValue withOwner:owner];
return [managedValue autorelease];
}
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
- (instancetype)initWithValue:(JSValue *)value
{
self = [super init];
if (!self)
return nil;

if (!value)
return self;

JSC::ExecState* exec = toJS([value.context JSGlobalContextRef]);
JSC::JSGlobalObject* globalObject = exec->lexicalGlobalObject();
JSC::Weak<JSC::JSGlobalObject> weak(globalObject, managedValueHandleOwner(), self);
m_globalObject.swap(weak);

m_lock = &exec->vm().apiLock();

NSPointerFunctionsOptions weakIDOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
NSPointerFunctionsOptions integerOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsIntegerPersonality;
m_owners = [[NSMapTable alloc] initWithKeyOptions:weakIDOptions valueOptions:integerOptions capacity:1];

// JSManagedValue does not strongly retain JSValue.
JSC::JSValue jsValue = toJS(exec, [value JSValueRef]);
if (jsValue.isObject())
m_weakValue.setObject(JSC::jsCast<JSC::JSObject*>(jsValue.asCell()), self);
else if (jsValue.isString())
m_weakValue.setString(JSC::jsCast<JSC::JSString*>(jsValue.asCell()), self);
else
m_weakValue.setPrimitive(jsValue);
return self;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)dealloc
{
JSVirtualMachine *virtualMachine = [[[self value] context] virtualMachine];
if (virtualMachine) {
NSMapTable *copy = [m_owners copy];
for (id owner in [copy keyEnumerator]) {
size_t count = reinterpret_cast<size_t>(NSMapGet(m_owners, owner));
while (count--)
[virtualMachine removeManagedReference:self withOwner:owner];
}
[copy release];
}

[self disconnectValue];
[m_owners release];
[super dealloc];
}

This part is easier to understand together with JSVirtualMachine, because the two are closely connected.

JSExport

The JSExport protocol provides a declarative way to export Objective-C instance classes and their instance methods, class methods, and properties to JavaScript code.

Usage Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@class MySize;

@protocol MySizeExports <JSExport>
@property double w;
@property double h;
- (NSString *)description;
- (instancetype)initWithW:(double)w h:(double)h;
+ (MySize *)makeSizeWithW:(double)w h:(double)h;
@end

@interface MySize : NSObject <MySizeExports>
// These two methods are not in MySizeExports, so they are invisible in JS code.
- (void)instanceTest;
+ (void)classTest;
@end

In JavaScript, it can be called like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Objective-C initializers can be called with constructor syntax. 
var size = MySize(1, 2);

// Objective-C properties become fields.
size.w;

size.h = 10;

// Objective-C instance methods become functions.
size.description();

// Objective-C class methods become functions on the constructor object.
var q = MySize.makeSizeWithWH(0, 0);

How JSExport Works

For every protocol implemented by a class, if the protocol inherits from JSExport, JavaScriptCore exports that protocol’s method and property list to JavaScript.

  • For every exported instance method, JavaScriptCore creates a corresponding method in prototype.
  • For every exported instance property, JavaScriptCore creates a corresponding accessor property in prototype.
  • For every exported class method, JavaScriptCore creates a corresponding JavaScript function on the constructor object.

JavaScript has always been a confusing language. It is dynamic and does not inherently have the concept of classes. Although ES6 introduced the class keyword, that syntax sugar still cannot change the fact that JavaScript is prototype-based. Understanding prototypes and the prototype chain is a very important step in advanced JavaScript.

Here is a classic diagram showing the relationship between the prototype chain and constructors:

JavaScriptCore Deep Dive 2 - API: How JSExport Works (figure 8)

This article will not dig deeply into JavaScript’s prototype chain. If you are interested, you can refer to:

A detailed understanding of JavaScript prototypes and prototype chains

JavaScript prototypes and prototype chains

Now let’s look at how JSExport is implemented in JavaScriptCore. Before the analysis, we need some groundwork, starting with JSWrapperMap, which exists as a member of JSContext:

1
JSWrapperMap *m_wrapperMap;

JSWrapperMap

As the name suggests, JSWrapperMap is a wrapper container. Its initialization method takes a JSContext, so it also depends on JSContext.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@interface JSWrapperMap : NSObject
- (id)initWithContext:(JSContext *)context;
- (JSValue *)jsWrapperForObject:(id)object;
- (JSValue *)objcWrapperForJSValueRef:(JSValueRef)value;
@end

@implementation JSWrapperMap {
JSContext *m_context;

// Class -> JSObjCClassInfo
NSMutableDictionary *m_classMap;

// Objective-C object -> JSObject
std::unique_ptr<JSC::WeakGCMap<id, JSC::JSObject>> m_cachedJSWrappers;

NSMapTable *m_cachedObjCWrappers;
}

For an Objective-C object, its JS wrapper is generated like this:

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
- (JSValue *)jsWrapperForObject:(id)object
{
// First look it up in m_cachedJSWrappers.
JSC::JSObject* jsWrapper = m_cachedJSWrappers->get(object);

// If found, wrap it as JSValue and return.
if (jsWrapper)
return [JSValue valueWithJSValueRef:toRef(jsWrapper) inContext:m_context];


if (class_isMetaClass(object_getClass(object)))
// If object's class is a metaclass, meaning object itself is a Class,
// build a prototype object.
jsWrapper = [[self classInfoForClass:(Class)object] constructor];
else {
// If object is an instance, first generate JSObjCClassInfo, then wrap the object.
JSObjCClassInfo* classInfo = [self classInfoForClass:[object class]];
jsWrapper = [classInfo wrapperForObject:object];
}

// Set key-value.
m_cachedJSWrappers->set(object, jsWrapper);

// Wrap the generated jsWrapper as JSValue and return.
return [JSValue valueWithJSValueRef:toRef(jsWrapper) inContext:m_context];
}

classInfoForClass

Now look at how JSObjCClassInfo is generated from a Class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (JSObjCClassInfo*)classInfoForClass:(Class)cls
{
if (!cls)
return nil;

// If cached JSObjCClassInfo already exists, return it directly.
if (JSObjCClassInfo* classInfo = (JSObjCClassInfo*)m_classMap[cls])
return classInfo;


// Skip some internal intermediate classes that start with underscore,
// and directly get superclass information.
if ('_' == *class_getName(cls))
return m_classMap[cls] = [self classInfoForClass:class_getSuperclass(cls)];

// Generate JSObjCClassInfo from cls and store it in m_classMap.
return m_classMap[cls] = [[[JSObjCClassInfo alloc] initWithContext:m_context forClass:cls] autorelease];
}

JSObjCClassInfo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@interface JSObjCClassInfo : NSObject {
JSContext *m_context;
Class m_class;
bool m_block;
JSClassRef m_classRef;
JSC::Weak<JSC::JSObject> m_prototype;
JSC::Weak<JSC::JSObject> m_constructor;
}

- (id)initWithContext:(JSContext *)context forClass:(Class)cls;
- (JSC::JSObject *)wrapperForObject:(id)object;
- (JSC::JSObject *)constructor;
- (JSC::JSObject *)prototype;

@end

Here come two very important JavaScript concepts: constructor and prototype.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (JSC::JSObject*)constructor
{
JSC::JSObject* constructor = m_constructor.get();
if (!constructor)
constructor = [self allocateConstructorAndPrototype].first;
ASSERT(!!constructor);
return constructor;
}

- (JSC::JSObject*)prototype
{
JSC::JSObject* prototype = m_prototype.get();
if (!prototype)
prototype = [self allocateConstructorAndPrototype].second;
ASSERT(!!prototype);
return prototype;
}

Both methods call allocateConstructorAndPrototype.

allocateConstructorAndPrototype

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
- (ConstructorPrototypePair)allocateConstructorAndPrototype
{
// Get JSObjCClassInfo for the superclass.
JSObjCClassInfo* superClassInfo = [m_context.wrapperMap classInfoForClass:class_getSuperclass(m_class)];

JSC::JSObject* jsPrototype = m_prototype.get();
JSC::JSObject* jsConstructor = m_constructor.get();

if (!superClassInfo) {
// If the superclass is nil, return the constructor and prototype
// of JavaScript's root Object.
JSContextRef cContext = [m_context JSGlobalContextRef];
JSValue *constructor = m_context[@"Object"];
if (!jsConstructor)
jsConstructor = toJS(JSValueToObject(cContext, valueInternalValue(constructor), 0));

if (!jsPrototype) {
JSValue *prototype = constructor[@"prototype"];
jsPrototype = toJS(JSValueToObject(cContext, valueInternalValue(prototype), 0));
}
}
else
{
// Get class name.
const char* className = class_getName(m_class);

// Generate prototype/constructor pair.
if (!jsPrototype)
// Generate JavaScript object prototype.
jsPrototype = objectWithCustomBrand(m_context, [NSString stringWithFormat:@"%sPrototype", className]);

if (!jsConstructor)
// Generate JavaScript object constructor.
jsConstructor = allocateConstructorForCustomClass(m_context, className, m_class);

// Type conversion.
JSValue* prototype = [JSValue valueWithJSValueRef:toRef(jsPrototype) inContext:m_context];
JSValue* constructor = [JSValue valueWithJSValueRef:toRef(jsConstructor) inContext:m_context];

// Define constructor and prototype on the JS objects.
putNonEnumerable(prototype, @"constructor", constructor);
putNonEnumerable(constructor, @"prototype", prototype);

// Iterate through protocols implemented by this class. If they contain
// methods from JSExport, copy them to JavaScript.
Protocol *exportProtocol = getJSExportProtocol();
forEachProtocolImplementingProtocol(m_class, exportProtocol, ^(Protocol *protocol){
// Copy properties and methods to the JS object prototype.
copyPrototypeProperties(m_context, m_class, protocol, prototype);
copyMethodsToObject(m_context, m_class, protocol, NO, constructor);
});

// Set prototype.
JSC::JSObject* superClassPrototype = [superClassInfo prototype];
JSObjectSetPrototype([m_context JSGlobalContextRef], toRef(jsPrototype), toRef(superClassPrototype));
}

m_prototype = jsPrototype;
m_constructor = jsConstructor;
return ConstructorPrototypePair(jsConstructor, jsPrototype);
}

Update

Seeing getJSExportProtocol, we should probably become alert:

1
2
3
4
5
Protocol *getJSExportProtocol()
{
static Protocol *protocol = objc_getProtocol("JSExport");
return protocol;
}

It only returns the JSExport protocol. The key is the traversal that follows:

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
inline void forEachProtocolImplementingProtocol(Class cls, Protocol *target, void (^callback)(Protocol *))
{
Vector<Protocol *> worklist;
HashSet<void*> visited;

// Initially fill the worklist with the Class's protocols.
unsigned protocolsCount;
Protocol ** protocols = class_copyProtocolList(cls, &protocolsCount);
worklist.append(protocols, protocolsCount);
free(protocols);

while (!worklist.isEmpty()) {
Protocol *protocol = worklist.last();
worklist.removeLast();

// Are we encountering this Protocol for the first time?
if (!visited.add(protocol).isNewEntry)
continue;

// If it implements the protocol, make the callback.
if (protocolImplementsProtocol(protocol, target))
callback(protocol);

// Add incorporated protocols to the worklist.
protocols = protocol_copyProtocolList(protocol, &protocolsCount);
worklist.append(protocols, protocolsCount);
free(protocols);
}
}

For every property and method declared in JSExport, classInfo stores the corresponding property and method in prototype and constructor. Later, through the generated method name and property-name setter/getter, it can obtain the real SEL. This allows methods and properties in JSExport to be accessed correctly.

In simple terms, JSExport marks those methods, uses methodName as the key and SEL as the value, and stores them in a map. prototype and constructor are essentially maps here. Later, JavaScript can use methodName to find the corresponding SEL and invoke it.

Generating prototype

1
2
3
4
5
6
7
8
9
10
11
12
13
// Make an object that is in all ways a completely vanilla JavaScript object,
// other than that it has a native brand set that will be displayed by the default
// Object.prototype.toString conversion.
static JSC::JSObject *objectWithCustomBrand(JSContext *context, NSString *brand, Class cls = 0)
{
JSClassDefinition definition;
definition = kJSClassDefinitionEmpty;
definition.className = [brand UTF8String];
JSClassRef classRef = JSClassCreate(&definition);
JSC::JSObject* result = makeWrapper([context JSGlobalContextRef], classRef, cls);
JSClassRelease(classRef);
return result;
}

Generating constructor

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
static JSC::JSObject* allocateConstructorForCustomClass(JSContext *context, const char* className, Class cls)
{
if (!supportsInitMethodConstructors())
return constructorWithCustomBrand(context, [NSString stringWithFormat:@"%sConstructor", className], cls);

// For each protocol implemented by the class and its superclasses,
// collect init methods into a hash table.
__block HashMap<String, Protocol *> initTable;
Protocol *exportProtocol = getJSExportProtocol();
for (Class currentClass = cls; currentClass; currentClass = class_getSuperclass(currentClass)) {
forEachProtocolImplementingProtocol(currentClass, exportProtocol, ^(Protocol *protocol) {
forEachMethodInProtocol(protocol, YES, YES, ^(SEL selector, const char*) {
const char* name = sel_getName(selector);
if (!isInitFamilyMethod(@(name)))return;
initTable.set(name, protocol);
});
});
}

// Iterate through the method lists of the class and its superclasses.
// If a method can be found in the hash table, mark it.
for (Class currentClass = cls; currentClass; currentClass = class_getSuperclass(currentClass)) {
__block unsigned numberOfInitsFound = 0;
__block SEL initMethod = 0;
__block Protocol *initProtocol = 0;
__block const char* types = 0;
forEachMethodInClass(currentClass, ^(Method method) {
SEL selector = method_getName(method);
const char* name = sel_getName(selector);
auto iter = initTable.find(name);

if (iter == initTable.end())
return;

numberOfInitsFound++;
initMethod = selector;
initProtocol = iter->value;
types = method_getTypeEncoding(method);
});

if (!numberOfInitsFound)
continue;

if (numberOfInitsFound > 1) {
break;
}

// Return once found.
JSObjectRef method = objCCallbackFunctionForInit(context, cls, initProtocol, initMethod, types);
return toJS(method);
}
return constructorWithCustomBrand(context, [NSString stringWithFormat:@"%sConstructor", className], cls);
}
1
2
3
4
5
6
7
8
9
10
11
static JSC::JSObject *constructorWithCustomBrand(JSContext *context, NSString *brand, Class cls)
{
JSClassDefinition definition;
definition = kJSClassDefinitionEmpty;
definition.className = [brand UTF8String];
definition.hasInstance = constructorHasInstance;
JSClassRef classRef = JSClassCreate(&definition);
JSC::JSObject* result = makeWrapper([context JSGlobalContextRef], classRef, cls);
JSClassRelease(classRef);
return result;
}

Summary

This article summarizes and analyzes JavaScriptCore’s Objective-C API. Because the source code is enormous, many parts are only touched lightly to avoid getting stuck in the mud. Later articles will gradually go deeper.

Overall, JavaScriptCore hides many implementation details, and its API surface is very concise.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:JavaScriptCore Deep Dive 2 - API

Author:lingyun

Published:2018-07-25 00:27

Updated:2026-10-08 00:23

Original link:https://tsuijunxi.github.io/en/2018/07/25/javascriptcore-deep-dive-2-api/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.