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 |
JavaScriptCore exposes several main header files to us. First, here is an overall relationship diagram:
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 | @interface JSVirtualMachine : NSObject |
And then the .mm file:
1 | @implementation JSVirtualMachine { |
1 | - (instancetype)init |
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 | // globalWrapperCache = [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:valueOptions capacity:0]; |
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 | - (void)testDemo |
The first parameter of addManagedReference is a
JSManagedValue, and the second parameter is a
JSValue.
1 | - (void)addManagedReference:(id)object withOwner:(id)owner |
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 | - (void)didAddOwner:(id)owner |
getInternalObjcObject
The next method, getInternalObjcObject, can be explained
in one word: unwrap.
1 | static id getInternalObjcObject(id object) |
removeManagedReference
1 | - (void)removeManagedReference:(id)object withOwner:(id)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 | - (void)didRemoveOwner:(id)owner |
Does this already feel messy? Let’s look at two diagrams first:
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.
1 | SValue *value = [context evaluateScript:@"var a = 1+2*3;"]; |
JSContext Initialization
1 | - (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine |
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 | - (JSValue *)globalObject |
1 | JSObjectRef JSContextGetGlobalObject(JSContextRef ctx) |
Executing Scripts
1 | - (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL |
The core logic is in JSEvaluateScript.
1 | JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception) |
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 | - (JSValue *)initWithValue:(JSValueRef)value inContext:(JSContext *)context |
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 | ProtectCountSet m_protectedValues; |
Type Conversion
The conversion relationship between Objective-C objects and JavaScript objects or values is:
1 | Objective-C type | JavaScript type |
Objective-C -> JavaScript
1 | // Convert an Objective-C object to JSValue. |
1 | JSValueRef objectToValue(JSContext *context, id object) |
1 | + (JSValue *)valueWithJSValueRef:(JSValueRef)value inContext:(JSContext *)context |
JavaScript -> Objective-C
1 | - (id)toObject |
1 | static id containerValueToObject(JSGlobalContextRef context, JSContainerConvertor::Task task) |
Helper Class: JSContainerConvertor
1 | class JSContainerConvertor { |
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
JSValueinside a native object exported to JavaScript. EveryJSValuecontains aJSContext, and this relationship can cause a retain cycle and memory leak.
1 | JSValue *value = [JSValue valueWithObject:@"test" inContext:context]; |
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.
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 | JSValue *value = [JSValue valueWithObject:@"test" inContext:context]; |
- “Conditional retain” means that the managed
JSValueis guaranteed to be retained if either of the following two conditions is satisfied: theJSValuecan be reached through the JavaScript object graph, or theJSManagedValuecan be reached through the native object graph. The relationship can be recorded in the virtual machine throughaddManagedReference:withOwner:. Conversely, if neither condition is satisfied,JSManagedValuesets itsvaluetoniland releases theJSValue.
Initialization
1 | @implementation JSManagedValue { |
1 | - (instancetype)initWithValue:(JSValue *)value |
1 | - (void)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 | @class MySize; |
In JavaScript, it can be called like this:
1 | // Objective-C initializers can be called with constructor syntax. |
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:
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 | @interface JSWrapperMap : NSObject |
For an Objective-C object, its JS wrapper is generated like this:
1 | - (JSValue *)jsWrapperForObject:(id)object |
classInfoForClass
Now look at how JSObjCClassInfo is generated from a
Class.
1 | - (JSObjCClassInfo*)classInfoForClass:(Class)cls |
JSObjCClassInfo
1 | @interface JSObjCClassInfo : NSObject { |
Here come two very important JavaScript concepts:
constructor and prototype.
1 | - (JSC::JSObject*)constructor |
Both methods call allocateConstructorAndPrototype.
allocateConstructorAndPrototype
1 | - (ConstructorPrototypePair)allocateConstructorAndPrototype |
Update
Seeing getJSExportProtocol, we should probably become
alert:
1 | Protocol *getJSExportProtocol() |
It only returns the JSExport protocol. The key is the
traversal that follows:
1 | inline void forEachProtocolImplementingProtocol(Class cls, Protocol *target, void (^callback)(Protocol *)) |
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 | // Make an object that is in all ways a completely vanilla JavaScript object, |
Generating constructor
1 | static JSC::JSObject* allocateConstructorForCustomClass(JSContext *context, const char* className, Class cls) |
1 | static JSC::JSObject *constructorWithCustomBrand(JSContext *context, NSString *brand, Class cls) |
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.