summaryrefslogtreecommitdiff
path: root/Source/JavaScriptCore/API
diff options
context:
space:
mode:
authorLorry Tar Creator <lorry-tar-importer@lorry>2015-10-15 09:45:50 +0000
committerLorry Tar Creator <lorry-tar-importer@lorry>2015-10-15 09:45:50 +0000
commite15dd966d523731101f70ccf768bba12435a0208 (patch)
treeae9cb828a24ded2585a41af3f21411523b47897d /Source/JavaScriptCore/API
downloadWebKitGtk-tarball-e15dd966d523731101f70ccf768bba12435a0208.tar.gz
webkitgtk-2.10.2webkitgtk-2.10.2
Diffstat (limited to 'Source/JavaScriptCore/API')
-rw-r--r--Source/JavaScriptCore/API/APICallbackFunction.h109
-rw-r--r--Source/JavaScriptCore/API/APICast.h171
-rw-r--r--Source/JavaScriptCore/API/JSAPIWrapperObject.h58
-rw-r--r--Source/JavaScriptCore/API/JSBase.cpp191
-rw-r--r--Source/JavaScriptCore/API/JSBase.h142
-rw-r--r--Source/JavaScriptCore/API/JSBasePrivate.h54
-rw-r--r--Source/JavaScriptCore/API/JSCTestRunnerUtils.cpp50
-rw-r--r--Source/JavaScriptCore/API/JSCTestRunnerUtils.h39
-rw-r--r--Source/JavaScriptCore/API/JSCallbackConstructor.cpp74
-rw-r--r--Source/JavaScriptCore/API/JSCallbackConstructor.h74
-rw-r--r--Source/JavaScriptCore/API/JSCallbackFunction.cpp72
-rw-r--r--Source/JavaScriptCore/API/JSCallbackFunction.h63
-rw-r--r--Source/JavaScriptCore/API/JSCallbackObject.cpp64
-rw-r--r--Source/JavaScriptCore/API/JSCallbackObject.h225
-rw-r--r--Source/JavaScriptCore/API/JSCallbackObjectFunctions.h662
-rw-r--r--Source/JavaScriptCore/API/JSClassRef.cpp212
-rw-r--r--Source/JavaScriptCore/API/JSClassRef.h127
-rw-r--r--Source/JavaScriptCore/API/JSContext.h250
-rw-r--r--Source/JavaScriptCore/API/JSContextInternal.h80
-rw-r--r--Source/JavaScriptCore/API/JSContextPrivate.h57
-rw-r--r--Source/JavaScriptCore/API/JSContextRef.cpp431
-rw-r--r--Source/JavaScriptCore/API/JSContextRef.h158
-rw-r--r--Source/JavaScriptCore/API/JSContextRefInspectorSupport.h43
-rw-r--r--Source/JavaScriptCore/API/JSContextRefInternal.h60
-rw-r--r--Source/JavaScriptCore/API/JSContextRefPrivate.h135
-rw-r--r--Source/JavaScriptCore/API/JSExport.h152
-rw-r--r--Source/JavaScriptCore/API/JSManagedValue.h85
-rw-r--r--Source/JavaScriptCore/API/JSManagedValueInternal.h42
-rw-r--r--Source/JavaScriptCore/API/JSObjectRef.cpp665
-rw-r--r--Source/JavaScriptCore/API/JSObjectRef.h694
-rw-r--r--Source/JavaScriptCore/API/JSObjectRefPrivate.h74
-rw-r--r--Source/JavaScriptCore/API/JSProfilerPrivate.cpp50
-rw-r--r--Source/JavaScriptCore/API/JSProfilerPrivate.h63
-rw-r--r--Source/JavaScriptCore/API/JSRemoteInspector.cpp78
-rw-r--r--Source/JavaScriptCore/API/JSRemoteInspector.h49
-rw-r--r--Source/JavaScriptCore/API/JSRetainPtr.h215
-rw-r--r--Source/JavaScriptCore/API/JSScriptRef.cpp158
-rw-r--r--Source/JavaScriptCore/API/JSScriptRefPrivate.h99
-rw-r--r--Source/JavaScriptCore/API/JSStringRef.cpp133
-rw-r--r--Source/JavaScriptCore/API/JSStringRef.h145
-rw-r--r--Source/JavaScriptCore/API/JSStringRefBSTR.cpp42
-rw-r--r--Source/JavaScriptCore/API/JSStringRefBSTR.h62
-rw-r--r--Source/JavaScriptCore/API/JSStringRefCF.cpp67
-rw-r--r--Source/JavaScriptCore/API/JSStringRefCF.h60
-rw-r--r--Source/JavaScriptCore/API/JSStringRefPrivate.h41
-rw-r--r--Source/JavaScriptCore/API/JSValue.h679
-rw-r--r--Source/JavaScriptCore/API/JSValueInternal.h58
-rw-r--r--Source/JavaScriptCore/API/JSValueRef.cpp471
-rw-r--r--Source/JavaScriptCore/API/JSValueRef.h319
-rw-r--r--Source/JavaScriptCore/API/JSVirtualMachine.h82
-rw-r--r--Source/JavaScriptCore/API/JSVirtualMachineInternal.h60
-rw-r--r--Source/JavaScriptCore/API/JSWeakObjectMapRefInternal.h69
-rw-r--r--Source/JavaScriptCore/API/JSWeakObjectMapRefPrivate.cpp103
-rw-r--r--Source/JavaScriptCore/API/JSWeakObjectMapRefPrivate.h92
-rw-r--r--Source/JavaScriptCore/API/JSWrapperMap.h48
-rw-r--r--Source/JavaScriptCore/API/JavaScript.h36
-rw-r--r--Source/JavaScriptCore/API/JavaScriptCore.h42
-rw-r--r--Source/JavaScriptCore/API/ObjCCallbackFunction.h83
-rw-r--r--Source/JavaScriptCore/API/ObjcRuntimeExtras.h242
-rw-r--r--Source/JavaScriptCore/API/OpaqueJSString.cpp109
-rw-r--r--Source/JavaScriptCore/API/OpaqueJSString.h102
-rw-r--r--Source/JavaScriptCore/API/WebKitAvailability.h71
-rw-r--r--Source/JavaScriptCore/API/tests/CompareAndSwapTest.cpp118
-rw-r--r--Source/JavaScriptCore/API/tests/CompareAndSwapTest.h40
-rw-r--r--Source/JavaScriptCore/API/tests/CurrentThisInsideBlockGetterTest.h38
-rw-r--r--Source/JavaScriptCore/API/tests/CustomGlobalObjectClassTest.c145
-rw-r--r--Source/JavaScriptCore/API/tests/CustomGlobalObjectClassTest.h33
-rw-r--r--Source/JavaScriptCore/API/tests/DateTests.h32
-rw-r--r--Source/JavaScriptCore/API/tests/ExecutionTimeLimitTest.cpp332
-rw-r--r--Source/JavaScriptCore/API/tests/ExecutionTimeLimitTest.h40
-rw-r--r--Source/JavaScriptCore/API/tests/GlobalContextWithFinalizerTest.cpp56
-rw-r--r--Source/JavaScriptCore/API/tests/GlobalContextWithFinalizerTest.h42
-rw-r--r--Source/JavaScriptCore/API/tests/JSExportTests.h34
-rw-r--r--Source/JavaScriptCore/API/tests/JSNode.c197
-rw-r--r--Source/JavaScriptCore/API/tests/JSNode.h37
-rw-r--r--Source/JavaScriptCore/API/tests/JSNodeList.c124
-rw-r--r--Source/JavaScriptCore/API/tests/JSNodeList.h34
-rw-r--r--Source/JavaScriptCore/API/tests/Node.c85
-rw-r--r--Source/JavaScriptCore/API/tests/Node.h50
-rw-r--r--Source/JavaScriptCore/API/tests/NodeList.c81
-rw-r--r--Source/JavaScriptCore/API/tests/NodeList.h42
-rw-r--r--Source/JavaScriptCore/API/tests/Regress141275.h34
-rw-r--r--Source/JavaScriptCore/API/tests/Regress141809.h34
-rw-r--r--Source/JavaScriptCore/API/tests/minidom.c128
-rw-r--r--Source/JavaScriptCore/API/tests/minidom.html9
-rw-r--r--Source/JavaScriptCore/API/tests/minidom.js110
-rw-r--r--Source/JavaScriptCore/API/tests/testapi.c1993
-rw-r--r--Source/JavaScriptCore/API/tests/testapi.js307
88 files changed, 13416 insertions, 0 deletions
diff --git a/Source/JavaScriptCore/API/APICallbackFunction.h b/Source/JavaScriptCore/API/APICallbackFunction.h
new file mode 100644
index 000000000..94b10c420
--- /dev/null
+++ b/Source/JavaScriptCore/API/APICallbackFunction.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef APICallbackFunction_h
+#define APICallbackFunction_h
+
+#include "APICast.h"
+#include "Error.h"
+#include "JSCallbackConstructor.h"
+#include "JSLock.h"
+#include <wtf/Vector.h>
+
+namespace JSC {
+
+struct APICallbackFunction {
+
+template <typename T> static EncodedJSValue JSC_HOST_CALL call(ExecState*);
+template <typename T> static EncodedJSValue JSC_HOST_CALL construct(ExecState*);
+
+};
+
+template <typename T>
+EncodedJSValue JSC_HOST_CALL APICallbackFunction::call(ExecState* exec)
+{
+ JSContextRef execRef = toRef(exec);
+ JSObjectRef functionRef = toRef(exec->callee());
+ JSObjectRef thisObjRef = toRef(jsCast<JSObject*>(exec->thisValue().toThis(exec, NotStrictMode)));
+
+ int argumentCount = static_cast<int>(exec->argumentCount());
+ Vector<JSValueRef, 16> arguments;
+ arguments.reserveInitialCapacity(argumentCount);
+ for (int i = 0; i < argumentCount; i++)
+ arguments.uncheckedAppend(toRef(exec, exec->uncheckedArgument(i)));
+
+ JSValueRef exception = 0;
+ JSValueRef result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = jsCast<T*>(toJS(functionRef))->functionCallback()(execRef, functionRef, thisObjRef, argumentCount, arguments.data(), &exception);
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+
+ // result must be a valid JSValue.
+ if (!result)
+ return JSValue::encode(jsUndefined());
+
+ return JSValue::encode(toJS(exec, result));
+}
+
+template <typename T>
+EncodedJSValue JSC_HOST_CALL APICallbackFunction::construct(ExecState* exec)
+{
+ JSObject* constructor = exec->callee();
+ JSContextRef ctx = toRef(exec);
+ JSObjectRef constructorRef = toRef(constructor);
+
+ JSObjectCallAsConstructorCallback callback = jsCast<T*>(constructor)->constructCallback();
+ if (callback) {
+ size_t argumentCount = exec->argumentCount();
+ Vector<JSValueRef, 16> arguments;
+ arguments.reserveInitialCapacity(argumentCount);
+ for (size_t i = 0; i < argumentCount; ++i)
+ arguments.uncheckedAppend(toRef(exec, exec->uncheckedArgument(i)));
+
+ JSValueRef exception = 0;
+ JSObjectRef result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = callback(ctx, constructorRef, argumentCount, arguments.data(), &exception);
+ }
+ if (exception) {
+ exec->vm().throwException(exec, toJS(exec, exception));
+ return JSValue::encode(toJS(exec, exception));
+ }
+ // result must be a valid JSValue.
+ if (!result)
+ return throwVMTypeError(exec);
+ return JSValue::encode(toJS(result));
+ }
+
+ return JSValue::encode(toJS(JSObjectMake(ctx, jsCast<JSCallbackConstructor*>(constructor)->classRef(), 0)));
+}
+
+} // namespace JSC
+
+#endif // APICallbackFunction_h
diff --git a/Source/JavaScriptCore/API/APICast.h b/Source/JavaScriptCore/API/APICast.h
new file mode 100644
index 000000000..8fe8d6034
--- /dev/null
+++ b/Source/JavaScriptCore/API/APICast.h
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef APICast_h
+#define APICast_h
+
+#include "JSAPIValueWrapper.h"
+#include "JSCJSValue.h"
+#include "JSCJSValueInlines.h"
+#include "JSGlobalObject.h"
+
+namespace JSC {
+ class ExecState;
+ class PropertyNameArray;
+ class VM;
+ class JSObject;
+ class JSValue;
+}
+
+typedef const struct OpaqueJSContextGroup* JSContextGroupRef;
+typedef const struct OpaqueJSContext* JSContextRef;
+typedef struct OpaqueJSContext* JSGlobalContextRef;
+typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef;
+typedef const struct OpaqueJSValue* JSValueRef;
+typedef struct OpaqueJSValue* JSObjectRef;
+
+/* Opaque typing convenience methods */
+
+inline JSC::ExecState* toJS(JSContextRef c)
+{
+ ASSERT(c);
+ return reinterpret_cast<JSC::ExecState*>(const_cast<OpaqueJSContext*>(c));
+}
+
+inline JSC::ExecState* toJS(JSGlobalContextRef c)
+{
+ ASSERT(c);
+ return reinterpret_cast<JSC::ExecState*>(c);
+}
+
+inline JSC::JSValue toJS(JSC::ExecState* exec, JSValueRef v)
+{
+ ASSERT_UNUSED(exec, exec);
+#if USE(JSVALUE32_64)
+ JSC::JSCell* jsCell = reinterpret_cast<JSC::JSCell*>(const_cast<OpaqueJSValue*>(v));
+ if (!jsCell)
+ return JSC::jsNull();
+ JSC::JSValue result;
+ if (jsCell->isAPIValueWrapper())
+ result = JSC::jsCast<JSC::JSAPIValueWrapper*>(jsCell)->value();
+ else
+ result = jsCell;
+#else
+ JSC::JSValue result = JSC::JSValue::decode(reinterpret_cast<JSC::EncodedJSValue>(const_cast<OpaqueJSValue*>(v)));
+#endif
+ if (!result)
+ return JSC::jsNull();
+ if (result.isCell())
+ RELEASE_ASSERT(result.asCell()->methodTable());
+ return result;
+}
+
+inline JSC::JSValue toJSForGC(JSC::ExecState* exec, JSValueRef v)
+{
+ ASSERT_UNUSED(exec, exec);
+#if USE(JSVALUE32_64)
+ JSC::JSCell* jsCell = reinterpret_cast<JSC::JSCell*>(const_cast<OpaqueJSValue*>(v));
+ if (!jsCell)
+ return JSC::JSValue();
+ JSC::JSValue result = jsCell;
+#else
+ JSC::JSValue result = JSC::JSValue::decode(reinterpret_cast<JSC::EncodedJSValue>(const_cast<OpaqueJSValue*>(v)));
+#endif
+ if (result && result.isCell())
+ RELEASE_ASSERT(result.asCell()->methodTable());
+ return result;
+}
+
+// Used in JSObjectGetPrivate as that may be called during finalization
+inline JSC::JSObject* uncheckedToJS(JSObjectRef o)
+{
+ return reinterpret_cast<JSC::JSObject*>(o);
+}
+
+inline JSC::JSObject* toJS(JSObjectRef o)
+{
+ JSC::JSObject* object = uncheckedToJS(o);
+ if (object)
+ RELEASE_ASSERT(object->methodTable());
+ return object;
+}
+
+inline JSC::PropertyNameArray* toJS(JSPropertyNameAccumulatorRef a)
+{
+ return reinterpret_cast<JSC::PropertyNameArray*>(a);
+}
+
+inline JSC::VM* toJS(JSContextGroupRef g)
+{
+ return reinterpret_cast<JSC::VM*>(const_cast<OpaqueJSContextGroup*>(g));
+}
+
+inline JSValueRef toRef(JSC::ExecState* exec, JSC::JSValue v)
+{
+ ASSERT(exec->vm().currentThreadIsHoldingAPILock());
+#if USE(JSVALUE32_64)
+ if (!v)
+ return 0;
+ if (!v.isCell())
+ return reinterpret_cast<JSValueRef>(JSC::jsAPIValueWrapper(exec, v).asCell());
+ return reinterpret_cast<JSValueRef>(v.asCell());
+#else
+ UNUSED_PARAM(exec);
+ return reinterpret_cast<JSValueRef>(JSC::JSValue::encode(v));
+#endif
+}
+
+inline JSObjectRef toRef(JSC::JSObject* o)
+{
+ return reinterpret_cast<JSObjectRef>(o);
+}
+
+inline JSObjectRef toRef(const JSC::JSObject* o)
+{
+ return reinterpret_cast<JSObjectRef>(const_cast<JSC::JSObject*>(o));
+}
+
+inline JSContextRef toRef(JSC::ExecState* e)
+{
+ return reinterpret_cast<JSContextRef>(e);
+}
+
+inline JSGlobalContextRef toGlobalRef(JSC::ExecState* e)
+{
+ ASSERT(e == e->lexicalGlobalObject()->globalExec());
+ return reinterpret_cast<JSGlobalContextRef>(e);
+}
+
+inline JSPropertyNameAccumulatorRef toRef(JSC::PropertyNameArray* l)
+{
+ return reinterpret_cast<JSPropertyNameAccumulatorRef>(l);
+}
+
+inline JSContextGroupRef toRef(JSC::VM* g)
+{
+ return reinterpret_cast<JSContextGroupRef>(g);
+}
+
+#endif // APICast_h
diff --git a/Source/JavaScriptCore/API/JSAPIWrapperObject.h b/Source/JavaScriptCore/API/JSAPIWrapperObject.h
new file mode 100644
index 000000000..14194b6f9
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSAPIWrapperObject.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSAPIWrapperObject_h
+#define JSAPIWrapperObject_h
+
+#include "JSBase.h"
+#include "JSDestructibleObject.h"
+#include "WeakReferenceHarvester.h"
+
+#if JSC_OBJC_API_ENABLED
+
+namespace JSC {
+
+class JSAPIWrapperObject : public JSDestructibleObject {
+public:
+ typedef JSDestructibleObject Base;
+
+ void finishCreation(VM&);
+ static void visitChildren(JSCell*, JSC::SlotVisitor&);
+
+ void* wrappedObject() { return m_wrappedObject; }
+ void setWrappedObject(void*);
+
+protected:
+ JSAPIWrapperObject(VM&, Structure*);
+
+private:
+ void* m_wrappedObject;
+};
+
+} // namespace JSC
+
+#endif // JSC_OBJC_API_ENABLED
+
+#endif // JSAPIWrapperObject_h
diff --git a/Source/JavaScriptCore/API/JSBase.cpp b/Source/JavaScriptCore/API/JSBase.cpp
new file mode 100644
index 000000000..3c5594b67
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSBase.cpp
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2006, 2007, 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSBase.h"
+#include "JSBasePrivate.h"
+
+#include "APICast.h"
+#include "CallFrame.h"
+#include "Completion.h"
+#include "Exception.h"
+#include "GCActivityCallback.h"
+#include "InitializeThreading.h"
+#include "JSGlobalObject.h"
+#include "JSLock.h"
+#include "JSObject.h"
+#include "OpaqueJSString.h"
+#include "JSCInlines.h"
+#include "SourceCode.h"
+#include <wtf/text/StringHash.h>
+
+#if ENABLE(REMOTE_INSPECTOR)
+#include "JSGlobalObjectInspectorController.h"
+#endif
+
+using namespace JSC;
+
+JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ 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();
+ SourceCode source = makeSource(script->string(), sourceURL ? sourceURL->string() : String(), TextPosition(OrdinalNumber::fromOneBasedInt(startingLineNumber), OrdinalNumber::first()));
+
+ NakedPtr<Exception> evaluationException;
+ JSValue returnValue = evaluate(globalObject->globalExec(), source, jsThisObject, evaluationException);
+
+ if (evaluationException) {
+ if (exception)
+ *exception = toRef(exec, evaluationException->value());
+#if ENABLE(REMOTE_INSPECTOR)
+ // FIXME: If we have a debugger attached we could learn about ParseError exceptions through
+ // ScriptDebugServer::sourceParsed and this path could produce a duplicate warning. The
+ // Debugger path is currently ignored by inspector.
+ // NOTE: If we don't have a debugger, this SourceCode will be forever lost to the inspector.
+ // We could stash it in the inspector in case an inspector is ever opened.
+ globalObject->inspectorController().reportAPIException(exec, evaluationException);
+#endif
+ return 0;
+ }
+
+ if (returnValue)
+ return toRef(exec, returnValue);
+
+ // happens, for example, when the only statement is an empty (';') statement
+ return toRef(exec, jsUndefined());
+}
+
+bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ startingLineNumber = std::max(1, startingLineNumber);
+
+ SourceCode source = makeSource(script->string(), sourceURL ? sourceURL->string() : String(), TextPosition(OrdinalNumber::fromOneBasedInt(startingLineNumber), OrdinalNumber::first()));
+
+ JSValue syntaxException;
+ bool isValidSyntax = checkSyntax(exec->vmEntryGlobalObject()->globalExec(), source, &syntaxException);
+
+ if (!isValidSyntax) {
+ if (exception)
+ *exception = toRef(exec, syntaxException);
+#if ENABLE(REMOTE_INSPECTOR)
+ Exception* exception = Exception::create(exec->vm(), syntaxException);
+ exec->vmEntryGlobalObject()->inspectorController().reportAPIException(exec, exception);
+#endif
+ return false;
+ }
+
+ return true;
+}
+
+void JSGarbageCollect(JSContextRef ctx)
+{
+ // We used to recommend passing NULL as an argument here, which caused the only heap to be collected.
+ // As there is no longer a shared heap, the previously recommended usage became a no-op (but the GC
+ // will happen when the context group is destroyed).
+ // Because the function argument was originally ignored, some clients may pass their released context here,
+ // in which case there is a risk of crashing if another thread performs GC on the same heap in between.
+ if (!ctx)
+ return;
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ exec->vm().heap.reportAbandonedObjectGraph();
+}
+
+void JSReportExtraMemoryCost(JSContextRef ctx, size_t size)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ exec->vm().heap.deprecatedReportExtraMemory(size);
+}
+
+extern "C" JS_EXPORT void JSSynchronousGarbageCollectForDebugging(JSContextRef);
+extern "C" JS_EXPORT void JSSynchronousEdenCollectForDebugging(JSContextRef);
+
+void JSSynchronousGarbageCollectForDebugging(JSContextRef ctx)
+{
+ if (!ctx)
+ return;
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ exec->vm().heap.collectAllGarbage();
+}
+
+void JSSynchronousEdenCollectForDebugging(JSContextRef ctx)
+{
+ if (!ctx)
+ return;
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ exec->vm().heap.collect(EdenCollection);
+}
+
+void JSDisableGCTimer(void)
+{
+ GCActivityCallback::s_shouldCreateGCTimer = false;
+}
+
+#if PLATFORM(IOS)
+// FIXME: Expose symbols to tell dyld where to find JavaScriptCore on older versions of
+// iOS (< 7.0). We should remove these symbols once we no longer need to support such
+// versions of iOS. See <rdar://problem/13696872> for more details.
+JS_EXPORT extern const char iosInstallName43 __asm("$ld$install_name$os4.3$/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore");
+JS_EXPORT extern const char iosInstallName50 __asm("$ld$install_name$os5.0$/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore");
+JS_EXPORT extern const char iosInstallName51 __asm("$ld$install_name$os5.1$/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore");
+JS_EXPORT extern const char iosInstallName60 __asm("$ld$install_name$os6.0$/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore");
+JS_EXPORT extern const char iosInstallName61 __asm("$ld$install_name$os6.1$/System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore");
+
+const char iosInstallName43 = 0;
+const char iosInstallName50 = 0;
+const char iosInstallName51 = 0;
+const char iosInstallName60 = 0;
+const char iosInstallName61 = 0;
+#endif
diff --git a/Source/JavaScriptCore/API/JSBase.h b/Source/JavaScriptCore/API/JSBase.h
new file mode 100644
index 000000000..4c9608828
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSBase.h
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSBase_h
+#define JSBase_h
+
+#ifndef __cplusplus
+#include <stdbool.h>
+#endif
+
+#ifdef __OBJC__
+#import <Foundation/Foundation.h>
+#endif
+
+/* JavaScript engine interface */
+
+/*! @typedef JSContextGroupRef A group that associates JavaScript contexts with one another. Contexts in the same group may share and exchange JavaScript objects. */
+typedef const struct OpaqueJSContextGroup* JSContextGroupRef;
+
+/*! @typedef JSContextRef A JavaScript execution context. Holds the global object and other execution state. */
+typedef const struct OpaqueJSContext* JSContextRef;
+
+/*! @typedef JSGlobalContextRef A global JavaScript execution context. A JSGlobalContext is a JSContext. */
+typedef struct OpaqueJSContext* JSGlobalContextRef;
+
+/*! @typedef JSStringRef A UTF16 character buffer. The fundamental string representation in JavaScript. */
+typedef struct OpaqueJSString* JSStringRef;
+
+/*! @typedef JSClassRef A JavaScript class. Used with JSObjectMake to construct objects with custom behavior. */
+typedef struct OpaqueJSClass* JSClassRef;
+
+/*! @typedef JSPropertyNameArrayRef An array of JavaScript property names. */
+typedef struct OpaqueJSPropertyNameArray* JSPropertyNameArrayRef;
+
+/*! @typedef JSPropertyNameAccumulatorRef An ordered set used to collect the names of a JavaScript object's properties. */
+typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef;
+
+
+/* JavaScript data types */
+
+/*! @typedef JSValueRef A JavaScript value. The base type for all JavaScript values, and polymorphic functions on them. */
+typedef const struct OpaqueJSValue* JSValueRef;
+
+/*! @typedef JSObjectRef A JavaScript object. A JSObject is a JSValue. */
+typedef struct OpaqueJSValue* JSObjectRef;
+
+/* JavaScript symbol exports */
+/* These rules should stay the same as in WebKit2/Shared/API/c/WKBase.h */
+
+#undef JS_EXPORT
+#if defined(JS_NO_EXPORT)
+#define JS_EXPORT
+#elif defined(__GNUC__) && !defined(__CC_ARM) && !defined(__ARMCC__)
+#define JS_EXPORT __attribute__((visibility("default")))
+#elif defined(WIN32) || defined(_WIN32) || defined(_WIN32_WCE) || defined(__CC_ARM) || defined(__ARMCC__)
+#if defined(BUILDING_JavaScriptCore) || defined(STATICALLY_LINKED_WITH_JavaScriptCore)
+#define JS_EXPORT __declspec(dllexport)
+#else
+#define JS_EXPORT __declspec(dllimport)
+#endif
+#else /* !defined(JS_NO_EXPORT) */
+#define JS_EXPORT
+#endif /* defined(JS_NO_EXPORT) */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Script Evaluation */
+
+/*!
+@function JSEvaluateScript
+@abstract Evaluates a string of JavaScript.
+@param ctx The execution context to use.
+@param script A JSString containing the script to evaluate.
+@param thisObject The object to use as "this," or NULL to use the global object as "this."
+@param sourceURL A JSString containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information.
+@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result The JSValue that results from evaluating script, or NULL if an exception is thrown.
+*/
+JS_EXPORT JSValueRef JSEvaluateScript(JSContextRef ctx, JSStringRef script, JSObjectRef thisObject, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
+
+/*!
+@function JSCheckScriptSyntax
+@abstract Checks for syntax errors in a string of JavaScript.
+@param ctx The execution context to use.
+@param script A JSString containing the script to check for syntax errors.
+@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions.
+@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
+@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception.
+@result true if the script is syntactically correct, otherwise false.
+*/
+JS_EXPORT bool JSCheckScriptSyntax(JSContextRef ctx, JSStringRef script, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
+
+/*!
+@function JSGarbageCollect
+@abstract Performs a JavaScript garbage collection.
+@param ctx The execution context to use.
+@discussion JavaScript values that are on the machine stack, in a register,
+ protected by JSValueProtect, set as the global object of an execution context,
+ or reachable from any such value will not be collected.
+
+ During JavaScript execution, you are not required to call this function; the
+ JavaScript engine will garbage collect as needed. JavaScript values created
+ within a context group are automatically destroyed when the last reference
+ to the context group is released.
+*/
+JS_EXPORT void JSGarbageCollect(JSContextRef ctx);
+
+#ifdef __cplusplus
+}
+#endif
+
+/* Enable the Objective-C API for platforms with a modern runtime. */
+#if !defined(JSC_OBJC_API_ENABLED)
+#define JSC_OBJC_API_ENABLED (defined(__clang__) && defined(__APPLE__) && ((defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 && !defined(__i386__)) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)))
+#endif
+
+#endif /* JSBase_h */
diff --git a/Source/JavaScriptCore/API/JSBasePrivate.h b/Source/JavaScriptCore/API/JSBasePrivate.h
new file mode 100644
index 000000000..137594972
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSBasePrivate.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSBasePrivate_h
+#define JSBasePrivate_h
+
+#include <JavaScriptCore/JSBase.h>
+#include <JavaScriptCore/WebKitAvailability.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+@function
+@abstract Reports an object's non-GC memory payload to the garbage collector.
+@param ctx The execution context to use.
+@param size The payload's size, in bytes.
+@discussion Use this function to notify the garbage collector that a GC object
+owns a large non-GC memory region. Calling this function will encourage the
+garbage collector to collect soon, hoping to reclaim that large non-GC memory
+region.
+*/
+JS_EXPORT void JSReportExtraMemoryCost(JSContextRef ctx, size_t size) CF_AVAILABLE(10_6, 7_0);
+
+JS_EXPORT void JSDisableGCTimer(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSBasePrivate_h */
diff --git a/Source/JavaScriptCore/API/JSCTestRunnerUtils.cpp b/Source/JavaScriptCore/API/JSCTestRunnerUtils.cpp
new file mode 100644
index 000000000..27f822eb3
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCTestRunnerUtils.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSCTestRunnerUtils.h"
+
+#include "APICast.h"
+#include "JSCInlines.h"
+#include "TestRunnerUtils.h"
+
+namespace JSC {
+
+JSValueRef numberOfDFGCompiles(JSContextRef context, JSValueRef theFunctionValueRef)
+{
+ ExecState* exec= toJS(context);
+ JSLockHolder holder(exec);
+ return toRef(exec, numberOfDFGCompiles(toJS(exec, theFunctionValueRef)));
+}
+
+JSValueRef setNeverInline(JSContextRef context, JSValueRef theFunctionValueRef)
+{
+ ExecState* exec= toJS(context);
+ JSLockHolder holder(exec);
+ return toRef(exec, setNeverInline(toJS(exec, theFunctionValueRef)));
+}
+
+} // namespace JSC
+
diff --git a/Source/JavaScriptCore/API/JSCTestRunnerUtils.h b/Source/JavaScriptCore/API/JSCTestRunnerUtils.h
new file mode 100644
index 000000000..aaecdd5c9
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCTestRunnerUtils.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSCTestRunnerUtils_h
+#define JSCTestRunnerUtils_h
+
+#include <JavaScriptCore/JSContextRef.h>
+#include <JavaScriptCore/JSValueRef.h>
+
+namespace JSC {
+
+JS_EXPORT_PRIVATE JSValueRef numberOfDFGCompiles(JSContextRef, JSValueRef theFunction);
+JS_EXPORT_PRIVATE JSValueRef setNeverInline(JSContextRef, JSValueRef theFunction);
+
+} // namespace JSC
+
+#endif // JSCTestRunnerUtils_h
diff --git a/Source/JavaScriptCore/API/JSCallbackConstructor.cpp b/Source/JavaScriptCore/API/JSCallbackConstructor.cpp
new file mode 100644
index 000000000..65e66dc13
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCallbackConstructor.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSCallbackConstructor.h"
+
+#include "APICallbackFunction.h"
+#include "APICast.h"
+#include "Error.h"
+#include "JSGlobalObject.h"
+#include "JSLock.h"
+#include "ObjectPrototype.h"
+#include "JSCInlines.h"
+#include <wtf/Vector.h>
+
+namespace JSC {
+
+const ClassInfo JSCallbackConstructor::s_info = { "CallbackConstructor", &Base::s_info, 0, CREATE_METHOD_TABLE(JSCallbackConstructor) };
+
+JSCallbackConstructor::JSCallbackConstructor(JSGlobalObject* globalObject, Structure* structure, JSClassRef jsClass, JSObjectCallAsConstructorCallback callback)
+ : JSDestructibleObject(globalObject->vm(), structure)
+ , m_class(jsClass)
+ , m_callback(callback)
+{
+}
+
+void JSCallbackConstructor::finishCreation(JSGlobalObject* globalObject, JSClassRef jsClass)
+{
+ Base::finishCreation(globalObject->vm());
+ ASSERT(inherits(info()));
+ if (m_class)
+ JSClassRetain(jsClass);
+}
+
+JSCallbackConstructor::~JSCallbackConstructor()
+{
+ if (m_class)
+ JSClassRelease(m_class);
+}
+
+void JSCallbackConstructor::destroy(JSCell* cell)
+{
+ static_cast<JSCallbackConstructor*>(cell)->JSCallbackConstructor::~JSCallbackConstructor();
+}
+
+ConstructType JSCallbackConstructor::getConstructData(JSCell*, ConstructData& constructData)
+{
+ constructData.native.function = APICallbackFunction::construct<JSCallbackConstructor>;
+ return ConstructTypeHost;
+}
+
+} // namespace JSC
diff --git a/Source/JavaScriptCore/API/JSCallbackConstructor.h b/Source/JavaScriptCore/API/JSCallbackConstructor.h
new file mode 100644
index 000000000..f178936e0
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCallbackConstructor.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSCallbackConstructor_h
+#define JSCallbackConstructor_h
+
+#include "JSObjectRef.h"
+#include "runtime/JSDestructibleObject.h"
+
+namespace JSC {
+
+class JSCallbackConstructor : public JSDestructibleObject {
+public:
+ typedef JSDestructibleObject Base;
+ static const unsigned StructureFlags = Base::StructureFlags | ImplementsHasInstance;
+
+ static JSCallbackConstructor* create(ExecState* exec, JSGlobalObject* globalObject, Structure* structure, JSClassRef classRef, JSObjectCallAsConstructorCallback callback)
+ {
+ JSCallbackConstructor* constructor = new (NotNull, allocateCell<JSCallbackConstructor>(*exec->heap())) JSCallbackConstructor(globalObject, structure, classRef, callback);
+ constructor->finishCreation(globalObject, classRef);
+ return constructor;
+ }
+
+ ~JSCallbackConstructor();
+ static void destroy(JSCell*);
+ JSClassRef classRef() const { return m_class; }
+ JSObjectCallAsConstructorCallback callback() const { return m_callback; }
+ DECLARE_INFO;
+
+ static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto)
+ {
+ return Structure::create(vm, globalObject, proto, TypeInfo(ObjectType, StructureFlags), info());
+ }
+
+protected:
+ JSCallbackConstructor(JSGlobalObject*, Structure*, JSClassRef, JSObjectCallAsConstructorCallback);
+ void finishCreation(JSGlobalObject*, JSClassRef);
+
+private:
+ friend struct APICallbackFunction;
+
+ static ConstructType getConstructData(JSCell*, ConstructData&);
+
+ JSObjectCallAsConstructorCallback constructCallback() { return m_callback; }
+
+ JSClassRef m_class;
+ JSObjectCallAsConstructorCallback m_callback;
+};
+
+} // namespace JSC
+
+#endif // JSCallbackConstructor_h
diff --git a/Source/JavaScriptCore/API/JSCallbackFunction.cpp b/Source/JavaScriptCore/API/JSCallbackFunction.cpp
new file mode 100644
index 000000000..047fcd01c
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCallbackFunction.cpp
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSCallbackFunction.h"
+
+#include "APICallbackFunction.h"
+#include "APICast.h"
+#include "CodeBlock.h"
+#include "Error.h"
+#include "ExceptionHelpers.h"
+#include "FunctionPrototype.h"
+#include "JSFunction.h"
+#include "JSGlobalObject.h"
+#include "JSLock.h"
+#include "JSCInlines.h"
+#include <wtf/Vector.h>
+
+namespace JSC {
+
+STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(JSCallbackFunction);
+
+const ClassInfo JSCallbackFunction::s_info = { "CallbackFunction", &InternalFunction::s_info, 0, CREATE_METHOD_TABLE(JSCallbackFunction) };
+
+JSCallbackFunction::JSCallbackFunction(VM& vm, Structure* structure, JSObjectCallAsFunctionCallback callback)
+ : InternalFunction(vm, structure)
+ , m_callback(callback)
+{
+}
+
+void JSCallbackFunction::finishCreation(VM& vm, const String& name)
+{
+ Base::finishCreation(vm, name);
+ ASSERT(inherits(info()));
+}
+
+JSCallbackFunction* JSCallbackFunction::create(VM& vm, JSGlobalObject* globalObject, JSObjectCallAsFunctionCallback callback, const String& name)
+{
+ JSCallbackFunction* function = new (NotNull, allocateCell<JSCallbackFunction>(vm.heap)) JSCallbackFunction(vm, globalObject->callbackFunctionStructure(), callback);
+ function->finishCreation(vm, name);
+ return function;
+}
+
+CallType JSCallbackFunction::getCallData(JSCell*, CallData& callData)
+{
+ callData.native.function = APICallbackFunction::call<JSCallbackFunction>;
+ return CallTypeHost;
+}
+
+} // namespace JSC
diff --git a/Source/JavaScriptCore/API/JSCallbackFunction.h b/Source/JavaScriptCore/API/JSCallbackFunction.h
new file mode 100644
index 000000000..a4fdd068f
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCallbackFunction.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSCallbackFunction_h
+#define JSCallbackFunction_h
+
+#include "InternalFunction.h"
+#include "JSObjectRef.h"
+
+namespace JSC {
+
+class JSCallbackFunction : public InternalFunction {
+ friend struct APICallbackFunction;
+public:
+ typedef InternalFunction Base;
+
+ static JSCallbackFunction* create(VM&, JSGlobalObject*, JSObjectCallAsFunctionCallback, const String& name);
+
+ DECLARE_INFO;
+
+ // InternalFunction mish-mashes constructor and function behavior -- we should
+ // refactor the code so this override isn't necessary
+ static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto)
+ {
+ return Structure::create(vm, globalObject, proto, TypeInfo(ObjectType, StructureFlags), info());
+ }
+
+private:
+ JSCallbackFunction(VM&, Structure*, JSObjectCallAsFunctionCallback);
+ void finishCreation(VM&, const String& name);
+
+ static CallType getCallData(JSCell*, CallData&);
+
+ JSObjectCallAsFunctionCallback functionCallback() { return m_callback; }
+
+ JSObjectCallAsFunctionCallback m_callback;
+};
+
+} // namespace JSC
+
+#endif // JSCallbackFunction_h
diff --git a/Source/JavaScriptCore/API/JSCallbackObject.cpp b/Source/JavaScriptCore/API/JSCallbackObject.cpp
new file mode 100644
index 000000000..02b38fde7
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCallbackObject.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSCallbackObject.h"
+
+#include "Heap.h"
+#include "JSCInlines.h"
+#include <wtf/text/StringHash.h>
+
+namespace JSC {
+
+// Define the two types of JSCallbackObjects we support.
+template <> const ClassInfo JSCallbackObject<JSDestructibleObject>::s_info = { "CallbackObject", &Base::s_info, 0, CREATE_METHOD_TABLE(JSCallbackObject) };
+template <> const ClassInfo JSCallbackObject<JSGlobalObject>::s_info = { "CallbackGlobalObject", &Base::s_info, 0, CREATE_METHOD_TABLE(JSCallbackObject) };
+
+template<> const bool JSCallbackObject<JSDestructibleObject>::needsDestruction = true;
+template<> const bool JSCallbackObject<JSGlobalObject>::needsDestruction = false;
+
+template<>
+JSCallbackObject<JSGlobalObject>* JSCallbackObject<JSGlobalObject>::create(VM& vm, JSClassRef classRef, Structure* structure)
+{
+ JSCallbackObject<JSGlobalObject>* callbackObject = new (NotNull, allocateCell<JSCallbackObject<JSGlobalObject>>(vm.heap)) JSCallbackObject(vm, classRef, structure);
+ callbackObject->finishCreation(vm);
+ vm.heap.addFinalizer(callbackObject, destroy);
+ return callbackObject;
+}
+
+template <>
+Structure* JSCallbackObject<JSDestructibleObject>::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto)
+{
+ return Structure::create(vm, globalObject, proto, TypeInfo(ObjectType, StructureFlags), info());
+}
+
+template <>
+Structure* JSCallbackObject<JSGlobalObject>::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto)
+{
+ return Structure::create(vm, globalObject, proto, TypeInfo(GlobalObjectType, StructureFlags), info());
+}
+
+} // namespace JSC
diff --git a/Source/JavaScriptCore/API/JSCallbackObject.h b/Source/JavaScriptCore/API/JSCallbackObject.h
new file mode 100644
index 000000000..a1a77fd88
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCallbackObject.h
@@ -0,0 +1,225 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSCallbackObject_h
+#define JSCallbackObject_h
+
+#include "JSObjectRef.h"
+#include "JSValueRef.h"
+#include "JSObject.h"
+
+namespace JSC {
+
+struct JSCallbackObjectData {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ JSCallbackObjectData(void* privateData, JSClassRef jsClass)
+ : privateData(privateData)
+ , jsClass(jsClass)
+ {
+ JSClassRetain(jsClass);
+ }
+
+ ~JSCallbackObjectData()
+ {
+ JSClassRelease(jsClass);
+ }
+
+ JSValue getPrivateProperty(const Identifier& propertyName) const
+ {
+ if (!m_privateProperties)
+ return JSValue();
+ return m_privateProperties->getPrivateProperty(propertyName);
+ }
+
+ void setPrivateProperty(VM& vm, JSCell* owner, const Identifier& propertyName, JSValue value)
+ {
+ if (!m_privateProperties)
+ m_privateProperties = std::make_unique<JSPrivatePropertyMap>();
+ m_privateProperties->setPrivateProperty(vm, owner, propertyName, value);
+ }
+
+ void deletePrivateProperty(const Identifier& propertyName)
+ {
+ if (!m_privateProperties)
+ return;
+ m_privateProperties->deletePrivateProperty(propertyName);
+ }
+
+ void visitChildren(SlotVisitor& visitor)
+ {
+ if (!m_privateProperties)
+ return;
+ m_privateProperties->visitChildren(visitor);
+ }
+
+ void* privateData;
+ JSClassRef jsClass;
+ struct JSPrivatePropertyMap {
+ WTF_MAKE_FAST_ALLOCATED;
+ public:
+ JSValue getPrivateProperty(const Identifier& propertyName) const
+ {
+ PrivatePropertyMap::const_iterator location = m_propertyMap.find(propertyName.impl());
+ if (location == m_propertyMap.end())
+ return JSValue();
+ return location->value.get();
+ }
+
+ void setPrivateProperty(VM& vm, JSCell* owner, const Identifier& propertyName, JSValue value)
+ {
+ WriteBarrier<Unknown> empty;
+ m_propertyMap.add(propertyName.impl(), empty).iterator->value.set(vm, owner, value);
+ }
+
+ void deletePrivateProperty(const Identifier& propertyName)
+ {
+ m_propertyMap.remove(propertyName.impl());
+ }
+
+ void visitChildren(SlotVisitor& visitor)
+ {
+ for (PrivatePropertyMap::iterator ptr = m_propertyMap.begin(); ptr != m_propertyMap.end(); ++ptr) {
+ if (ptr->value)
+ visitor.append(&ptr->value);
+ }
+ }
+
+ private:
+ typedef HashMap<RefPtr<UniquedStringImpl>, WriteBarrier<Unknown>, IdentifierRepHash> PrivatePropertyMap;
+ PrivatePropertyMap m_propertyMap;
+ };
+ std::unique_ptr<JSPrivatePropertyMap> m_privateProperties;
+};
+
+
+template <class Parent>
+class JSCallbackObject : public Parent {
+protected:
+ JSCallbackObject(ExecState*, Structure*, JSClassRef, void* data);
+ JSCallbackObject(VM&, JSClassRef, Structure*);
+
+ void finishCreation(ExecState*);
+ void finishCreation(VM&);
+
+public:
+ typedef Parent Base;
+ static const unsigned StructureFlags = Base::StructureFlags | ProhibitsPropertyCaching | OverridesGetOwnPropertySlot | InterceptsGetOwnPropertySlotByIndexEvenWhenLengthIsNotZero | ImplementsHasInstance | OverridesHasInstance | OverridesGetPropertyNames | TypeOfShouldCallGetCallData;
+
+ ~JSCallbackObject();
+
+ static JSCallbackObject* create(ExecState* exec, JSGlobalObject* globalObject, Structure* structure, JSClassRef classRef, void* data)
+ {
+ ASSERT_UNUSED(globalObject, !structure->globalObject() || structure->globalObject() == globalObject);
+ JSCallbackObject* callbackObject = new (NotNull, allocateCell<JSCallbackObject>(*exec->heap())) JSCallbackObject(exec, structure, classRef, data);
+ callbackObject->finishCreation(exec);
+ return callbackObject;
+ }
+ static JSCallbackObject<Parent>* create(VM&, JSClassRef, Structure*);
+
+ static const bool needsDestruction;
+ static void destroy(JSCell* cell)
+ {
+ static_cast<JSCallbackObject*>(cell)->JSCallbackObject::~JSCallbackObject();
+ }
+
+ void setPrivate(void* data);
+ void* getPrivate();
+
+ DECLARE_INFO;
+
+ JSClassRef classRef() const { return m_callbackObjectData->jsClass; }
+ bool inherits(JSClassRef) const;
+
+ static Structure* createStructure(VM&, JSGlobalObject*, JSValue);
+
+ JSValue getPrivateProperty(const Identifier& propertyName) const
+ {
+ return m_callbackObjectData->getPrivateProperty(propertyName);
+ }
+
+ void setPrivateProperty(VM& vm, const Identifier& propertyName, JSValue value)
+ {
+ m_callbackObjectData->setPrivateProperty(vm, this, propertyName, value);
+ }
+
+ void deletePrivateProperty(const Identifier& propertyName)
+ {
+ m_callbackObjectData->deletePrivateProperty(propertyName);
+ }
+
+ using Parent::methodTable;
+
+private:
+ static String className(const JSObject*);
+
+ static JSValue defaultValue(const JSObject*, ExecState*, PreferredPrimitiveType);
+
+ static bool getOwnPropertySlot(JSObject*, ExecState*, PropertyName, PropertySlot&);
+ static bool getOwnPropertySlotByIndex(JSObject*, ExecState*, unsigned propertyName, PropertySlot&);
+
+ static void put(JSCell*, ExecState*, PropertyName, JSValue, PutPropertySlot&);
+ static void putByIndex(JSCell*, ExecState*, unsigned, JSValue, bool shouldThrow);
+
+ static bool deleteProperty(JSCell*, ExecState*, PropertyName);
+ static bool deletePropertyByIndex(JSCell*, ExecState*, unsigned);
+
+ static bool customHasInstance(JSObject*, ExecState*, JSValue);
+
+ static void getOwnNonIndexPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode);
+
+ static ConstructType getConstructData(JSCell*, ConstructData&);
+ static CallType getCallData(JSCell*, CallData&);
+
+ static void visitChildren(JSCell* cell, SlotVisitor& visitor)
+ {
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
+ ASSERT_GC_OBJECT_INHERITS((static_cast<Parent*>(thisObject)), JSCallbackObject<Parent>::info());
+ Parent::visitChildren(thisObject, visitor);
+ thisObject->m_callbackObjectData->visitChildren(visitor);
+ }
+
+ void init(ExecState*);
+
+ static JSCallbackObject* asCallbackObject(JSValue);
+ static JSCallbackObject* asCallbackObject(EncodedJSValue);
+
+ static EncodedJSValue JSC_HOST_CALL call(ExecState*);
+ static EncodedJSValue JSC_HOST_CALL construct(ExecState*);
+
+ JSValue getStaticValue(ExecState*, PropertyName);
+ static EncodedJSValue staticFunctionGetter(ExecState*, JSObject*, EncodedJSValue, PropertyName);
+ static EncodedJSValue callbackGetter(ExecState*, JSObject*, EncodedJSValue, PropertyName);
+
+ std::unique_ptr<JSCallbackObjectData> m_callbackObjectData;
+};
+
+} // namespace JSC
+
+// include the actual template class implementation
+#include "JSCallbackObjectFunctions.h"
+
+#endif // JSCallbackObject_h
diff --git a/Source/JavaScriptCore/API/JSCallbackObjectFunctions.h b/Source/JavaScriptCore/API/JSCallbackObjectFunctions.h
new file mode 100644
index 000000000..585aab194
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSCallbackObjectFunctions.h
@@ -0,0 +1,662 @@
+/*
+ * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "APICast.h"
+#include "Error.h"
+#include "ExceptionHelpers.h"
+#include "JSCallbackFunction.h"
+#include "JSClassRef.h"
+#include "JSFunction.h"
+#include "JSGlobalObject.h"
+#include "JSLock.h"
+#include "JSObjectRef.h"
+#include "JSString.h"
+#include "JSStringRef.h"
+#include "OpaqueJSString.h"
+#include "PropertyNameArray.h"
+#include <wtf/Vector.h>
+
+namespace JSC {
+
+template <class Parent>
+inline JSCallbackObject<Parent>* JSCallbackObject<Parent>::asCallbackObject(JSValue value)
+{
+ ASSERT(asObject(value)->inherits(info()));
+ return jsCast<JSCallbackObject*>(asObject(value));
+}
+
+template <class Parent>
+inline JSCallbackObject<Parent>* JSCallbackObject<Parent>::asCallbackObject(EncodedJSValue value)
+{
+ ASSERT(asObject(JSValue::decode(value))->inherits(info()));
+ return jsCast<JSCallbackObject*>(asObject(JSValue::decode(value)));
+}
+
+template <class Parent>
+JSCallbackObject<Parent>::JSCallbackObject(ExecState* exec, Structure* structure, JSClassRef jsClass, void* data)
+ : Parent(exec->vm(), structure)
+ , m_callbackObjectData(std::make_unique<JSCallbackObjectData>(data, jsClass))
+{
+}
+
+// Global object constructor.
+// FIXME: Move this into a separate JSGlobalCallbackObject class derived from this one.
+template <class Parent>
+JSCallbackObject<Parent>::JSCallbackObject(VM& vm, JSClassRef jsClass, Structure* structure)
+ : Parent(vm, structure)
+ , m_callbackObjectData(std::make_unique<JSCallbackObjectData>(nullptr, jsClass))
+{
+}
+
+template <class Parent>
+JSCallbackObject<Parent>::~JSCallbackObject()
+{
+ JSObjectRef thisRef = toRef(static_cast<JSObject*>(this));
+ for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectFinalizeCallback finalize = jsClass->finalize)
+ finalize(thisRef);
+ }
+}
+
+template <class Parent>
+void JSCallbackObject<Parent>::finishCreation(ExecState* exec)
+{
+ Base::finishCreation(exec->vm());
+ ASSERT(Parent::inherits(info()));
+ init(exec);
+}
+
+// This is just for Global object, so we can assume that Base::finishCreation is JSGlobalObject::finishCreation.
+template <class Parent>
+void JSCallbackObject<Parent>::finishCreation(VM& vm)
+{
+ ASSERT(Parent::inherits(info()));
+ ASSERT(Parent::isGlobalObject());
+ Base::finishCreation(vm);
+ init(jsCast<JSGlobalObject*>(this)->globalExec());
+}
+
+template <class Parent>
+void JSCallbackObject<Parent>::init(ExecState* exec)
+{
+ ASSERT(exec);
+
+ Vector<JSObjectInitializeCallback, 16> initRoutines;
+ JSClassRef jsClass = classRef();
+ do {
+ if (JSObjectInitializeCallback initialize = jsClass->initialize)
+ initRoutines.append(initialize);
+ } while ((jsClass = jsClass->parentClass));
+
+ // initialize from base to derived
+ for (int i = static_cast<int>(initRoutines.size()) - 1; i >= 0; i--) {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ JSObjectInitializeCallback initialize = initRoutines[i];
+ initialize(toRef(exec), toRef(this));
+ }
+}
+
+template <class Parent>
+String JSCallbackObject<Parent>::className(const JSObject* object)
+{
+ const JSCallbackObject* thisObject = jsCast<const JSCallbackObject*>(object);
+ String thisClassName = thisObject->classRef()->className();
+ if (!thisClassName.isEmpty())
+ return thisClassName;
+
+ return Parent::className(object);
+}
+
+template <class Parent>
+bool JSCallbackObject<Parent>::getOwnPropertySlot(JSObject* object, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(object);
+ JSContextRef ctx = toRef(exec);
+ JSObjectRef thisRef = toRef(thisObject);
+ RefPtr<OpaqueJSString> propertyNameRef;
+
+ if (StringImpl* name = propertyName.uid()) {
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ // optional optimization to bypass getProperty in cases when we only need to know if the property exists
+ if (JSObjectHasPropertyCallback hasProperty = jsClass->hasProperty) {
+ if (!propertyNameRef)
+ propertyNameRef = OpaqueJSString::create(name);
+ JSLock::DropAllLocks dropAllLocks(exec);
+ if (hasProperty(ctx, thisRef, propertyNameRef.get())) {
+ slot.setCustom(thisObject, ReadOnly | DontEnum, callbackGetter);
+ return true;
+ }
+ } else if (JSObjectGetPropertyCallback getProperty = jsClass->getProperty) {
+ if (!propertyNameRef)
+ propertyNameRef = OpaqueJSString::create(name);
+ JSValueRef exception = 0;
+ JSValueRef value;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ value = getProperty(ctx, thisRef, propertyNameRef.get(), &exception);
+ }
+ if (exception) {
+ exec->vm().throwException(exec, toJS(exec, exception));
+ slot.setValue(thisObject, ReadOnly | DontEnum, jsUndefined());
+ return true;
+ }
+ if (value) {
+ slot.setValue(thisObject, ReadOnly | DontEnum, toJS(exec, value));
+ return true;
+ }
+ }
+
+ if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
+ if (staticValues->contains(name)) {
+ JSValue value = thisObject->getStaticValue(exec, propertyName);
+ if (value) {
+ slot.setValue(thisObject, ReadOnly | DontEnum, value);
+ return true;
+ }
+ }
+ }
+
+ if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
+ if (staticFunctions->contains(name)) {
+ slot.setCustom(thisObject, ReadOnly | DontEnum, staticFunctionGetter);
+ return true;
+ }
+ }
+ }
+ }
+
+ return Parent::getOwnPropertySlot(thisObject, exec, propertyName, slot);
+}
+
+template <class Parent>
+bool JSCallbackObject<Parent>::getOwnPropertySlotByIndex(JSObject* object, ExecState* exec, unsigned propertyName, PropertySlot& slot)
+{
+ return object->methodTable()->getOwnPropertySlot(object, exec, Identifier::from(exec, propertyName), slot);
+}
+
+template <class Parent>
+JSValue JSCallbackObject<Parent>::defaultValue(const JSObject* object, ExecState* exec, PreferredPrimitiveType hint)
+{
+ const JSCallbackObject* thisObject = jsCast<const JSCallbackObject*>(object);
+ JSContextRef ctx = toRef(exec);
+ JSObjectRef thisRef = toRef(thisObject);
+ ::JSType jsHint = hint == PreferString ? kJSTypeString : kJSTypeNumber;
+
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectConvertToTypeCallback convertToType = jsClass->convertToType) {
+ JSValueRef exception = 0;
+ JSValueRef result = convertToType(ctx, thisRef, jsHint, &exception);
+ if (exception) {
+ exec->vm().throwException(exec, toJS(exec, exception));
+ return jsUndefined();
+ }
+ if (result)
+ return toJS(exec, result);
+ }
+ }
+
+ return Parent::defaultValue(object, exec, hint);
+}
+
+template <class Parent>
+void JSCallbackObject<Parent>::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
+ JSContextRef ctx = toRef(exec);
+ JSObjectRef thisRef = toRef(thisObject);
+ RefPtr<OpaqueJSString> propertyNameRef;
+ JSValueRef valueRef = toRef(exec, value);
+
+ if (StringImpl* name = propertyName.uid()) {
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectSetPropertyCallback setProperty = jsClass->setProperty) {
+ if (!propertyNameRef)
+ propertyNameRef = OpaqueJSString::create(name);
+ JSValueRef exception = 0;
+ bool result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = setProperty(ctx, thisRef, propertyNameRef.get(), valueRef, &exception);
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+ if (result || exception)
+ return;
+ }
+
+ if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
+ if (StaticValueEntry* entry = staticValues->get(name)) {
+ if (entry->attributes & kJSPropertyAttributeReadOnly)
+ return;
+ if (JSObjectSetPropertyCallback setProperty = entry->setProperty) {
+ JSValueRef exception = 0;
+ bool result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = setProperty(ctx, thisRef, entry->propertyNameRef.get(), valueRef, &exception);
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+ if (result || exception)
+ return;
+ }
+ }
+ }
+
+ if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
+ if (StaticFunctionEntry* entry = staticFunctions->get(name)) {
+ PropertySlot getSlot(thisObject);
+ if (Parent::getOwnPropertySlot(thisObject, exec, propertyName, getSlot))
+ return Parent::put(thisObject, exec, propertyName, value, slot);
+ if (entry->attributes & kJSPropertyAttributeReadOnly)
+ return;
+ thisObject->JSCallbackObject<Parent>::putDirect(exec->vm(), propertyName, value); // put as override property
+ return;
+ }
+ }
+ }
+ }
+
+ return Parent::put(thisObject, exec, propertyName, value, slot);
+}
+
+template <class Parent>
+void JSCallbackObject<Parent>::putByIndex(JSCell* cell, ExecState* exec, unsigned propertyIndex, JSValue value, bool shouldThrow)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
+ JSContextRef ctx = toRef(exec);
+ JSObjectRef thisRef = toRef(thisObject);
+ RefPtr<OpaqueJSString> propertyNameRef;
+ JSValueRef valueRef = toRef(exec, value);
+ Identifier propertyName = Identifier::from(exec, propertyIndex);
+
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectSetPropertyCallback setProperty = jsClass->setProperty) {
+ if (!propertyNameRef)
+ propertyNameRef = OpaqueJSString::create(propertyName.impl());
+ JSValueRef exception = 0;
+ bool result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = setProperty(ctx, thisRef, propertyNameRef.get(), valueRef, &exception);
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+ if (result || exception)
+ return;
+ }
+
+ if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
+ if (StaticValueEntry* entry = staticValues->get(propertyName.impl())) {
+ if (entry->attributes & kJSPropertyAttributeReadOnly)
+ return;
+ if (JSObjectSetPropertyCallback setProperty = entry->setProperty) {
+ JSValueRef exception = 0;
+ bool result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = setProperty(ctx, thisRef, entry->propertyNameRef.get(), valueRef, &exception);
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+ if (result || exception)
+ return;
+ }
+ }
+ }
+
+ if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
+ if (StaticFunctionEntry* entry = staticFunctions->get(propertyName.impl())) {
+ if (entry->attributes & kJSPropertyAttributeReadOnly)
+ return;
+ break;
+ }
+ }
+ }
+
+ return Parent::putByIndex(thisObject, exec, propertyIndex, value, shouldThrow);
+}
+
+template <class Parent>
+bool JSCallbackObject<Parent>::deleteProperty(JSCell* cell, ExecState* exec, PropertyName propertyName)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
+ JSContextRef ctx = toRef(exec);
+ JSObjectRef thisRef = toRef(thisObject);
+ RefPtr<OpaqueJSString> propertyNameRef;
+
+ if (StringImpl* name = propertyName.uid()) {
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectDeletePropertyCallback deleteProperty = jsClass->deleteProperty) {
+ if (!propertyNameRef)
+ propertyNameRef = OpaqueJSString::create(name);
+ JSValueRef exception = 0;
+ bool result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = deleteProperty(ctx, thisRef, propertyNameRef.get(), &exception);
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+ if (result || exception)
+ return true;
+ }
+
+ if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
+ if (StaticValueEntry* entry = staticValues->get(name)) {
+ if (entry->attributes & kJSPropertyAttributeDontDelete)
+ return false;
+ return true;
+ }
+ }
+
+ if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
+ if (StaticFunctionEntry* entry = staticFunctions->get(name)) {
+ if (entry->attributes & kJSPropertyAttributeDontDelete)
+ return false;
+ return true;
+ }
+ }
+ }
+ }
+
+ return Parent::deleteProperty(thisObject, exec, propertyName);
+}
+
+template <class Parent>
+bool JSCallbackObject<Parent>::deletePropertyByIndex(JSCell* cell, ExecState* exec, unsigned propertyName)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
+ return thisObject->methodTable()->deleteProperty(thisObject, exec, Identifier::from(exec, propertyName));
+}
+
+template <class Parent>
+ConstructType JSCallbackObject<Parent>::getConstructData(JSCell* cell, ConstructData& constructData)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (jsClass->callAsConstructor) {
+ constructData.native.function = construct;
+ return ConstructTypeHost;
+ }
+ }
+ return ConstructTypeNone;
+}
+
+template <class Parent>
+EncodedJSValue JSCallbackObject<Parent>::construct(ExecState* exec)
+{
+ JSObject* constructor = exec->callee();
+ JSContextRef execRef = toRef(exec);
+ JSObjectRef constructorRef = toRef(constructor);
+
+ for (JSClassRef jsClass = jsCast<JSCallbackObject<Parent>*>(constructor)->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectCallAsConstructorCallback callAsConstructor = jsClass->callAsConstructor) {
+ size_t argumentCount = exec->argumentCount();
+ Vector<JSValueRef, 16> arguments;
+ arguments.reserveInitialCapacity(argumentCount);
+ for (size_t i = 0; i < argumentCount; ++i)
+ arguments.uncheckedAppend(toRef(exec, exec->uncheckedArgument(i)));
+ JSValueRef exception = 0;
+ JSObject* result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = toJS(callAsConstructor(execRef, constructorRef, argumentCount, arguments.data(), &exception));
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+ return JSValue::encode(result);
+ }
+ }
+
+ RELEASE_ASSERT_NOT_REACHED(); // getConstructData should prevent us from reaching here
+ return JSValue::encode(JSValue());
+}
+
+template <class Parent>
+bool JSCallbackObject<Parent>::customHasInstance(JSObject* object, ExecState* exec, JSValue value)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(object);
+ JSContextRef execRef = toRef(exec);
+ JSObjectRef thisRef = toRef(thisObject);
+
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectHasInstanceCallback hasInstance = jsClass->hasInstance) {
+ JSValueRef valueRef = toRef(exec, value);
+ JSValueRef exception = 0;
+ bool result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = hasInstance(execRef, thisRef, valueRef, &exception);
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+ return result;
+ }
+ }
+ return false;
+}
+
+template <class Parent>
+CallType JSCallbackObject<Parent>::getCallData(JSCell* cell, CallData& callData)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(cell);
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (jsClass->callAsFunction) {
+ callData.native.function = call;
+ return CallTypeHost;
+ }
+ }
+ return CallTypeNone;
+}
+
+template <class Parent>
+EncodedJSValue JSCallbackObject<Parent>::call(ExecState* exec)
+{
+ JSContextRef execRef = toRef(exec);
+ JSObjectRef functionRef = toRef(exec->callee());
+ JSObjectRef thisObjRef = toRef(jsCast<JSObject*>(exec->thisValue().toThis(exec, NotStrictMode)));
+
+ for (JSClassRef jsClass = jsCast<JSCallbackObject<Parent>*>(toJS(functionRef))->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectCallAsFunctionCallback callAsFunction = jsClass->callAsFunction) {
+ size_t argumentCount = exec->argumentCount();
+ Vector<JSValueRef, 16> arguments;
+ arguments.reserveInitialCapacity(argumentCount);
+ for (size_t i = 0; i < argumentCount; ++i)
+ arguments.uncheckedAppend(toRef(exec, exec->uncheckedArgument(i)));
+ JSValueRef exception = 0;
+ JSValue result;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ result = toJS(exec, callAsFunction(execRef, functionRef, thisObjRef, argumentCount, arguments.data(), &exception));
+ }
+ if (exception)
+ exec->vm().throwException(exec, toJS(exec, exception));
+ return JSValue::encode(result);
+ }
+ }
+
+ RELEASE_ASSERT_NOT_REACHED(); // getCallData should prevent us from reaching here
+ return JSValue::encode(JSValue());
+}
+
+template <class Parent>
+void JSCallbackObject<Parent>::getOwnNonIndexPropertyNames(JSObject* object, ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
+{
+ JSCallbackObject* thisObject = jsCast<JSCallbackObject*>(object);
+ JSContextRef execRef = toRef(exec);
+ JSObjectRef thisRef = toRef(thisObject);
+
+ for (JSClassRef jsClass = thisObject->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectGetPropertyNamesCallback getPropertyNames = jsClass->getPropertyNames) {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ getPropertyNames(execRef, thisRef, toRef(&propertyNames));
+ }
+
+ if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
+ typedef OpaqueJSClassStaticValuesTable::const_iterator iterator;
+ iterator end = staticValues->end();
+ for (iterator it = staticValues->begin(); it != end; ++it) {
+ StringImpl* name = it->key.get();
+ StaticValueEntry* entry = it->value.get();
+ if (entry->getProperty && (!(entry->attributes & kJSPropertyAttributeDontEnum) || mode.includeDontEnumProperties())) {
+ ASSERT(!name->isSymbol());
+ propertyNames.add(Identifier::fromString(exec, String(name)));
+ }
+ }
+ }
+
+ if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
+ typedef OpaqueJSClassStaticFunctionsTable::const_iterator iterator;
+ iterator end = staticFunctions->end();
+ for (iterator it = staticFunctions->begin(); it != end; ++it) {
+ StringImpl* name = it->key.get();
+ StaticFunctionEntry* entry = it->value.get();
+ if (!(entry->attributes & kJSPropertyAttributeDontEnum) || mode.includeDontEnumProperties()) {
+ ASSERT(!name->isSymbol());
+ propertyNames.add(Identifier::fromString(exec, String(name)));
+ }
+ }
+ }
+ }
+
+ Parent::getOwnNonIndexPropertyNames(thisObject, exec, propertyNames, mode);
+}
+
+template <class Parent>
+void JSCallbackObject<Parent>::setPrivate(void* data)
+{
+ m_callbackObjectData->privateData = data;
+}
+
+template <class Parent>
+void* JSCallbackObject<Parent>::getPrivate()
+{
+ return m_callbackObjectData->privateData;
+}
+
+template <class Parent>
+bool JSCallbackObject<Parent>::inherits(JSClassRef c) const
+{
+ for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (jsClass == c)
+ return true;
+ }
+ return false;
+}
+
+template <class Parent>
+JSValue JSCallbackObject<Parent>::getStaticValue(ExecState* exec, PropertyName propertyName)
+{
+ JSObjectRef thisRef = toRef(this);
+
+ if (StringImpl* name = propertyName.uid()) {
+ for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
+ if (StaticValueEntry* entry = staticValues->get(name)) {
+ if (JSObjectGetPropertyCallback getProperty = entry->getProperty) {
+ JSValueRef exception = 0;
+ JSValueRef value;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ value = getProperty(toRef(exec), thisRef, entry->propertyNameRef.get(), &exception);
+ }
+ if (exception) {
+ exec->vm().throwException(exec, toJS(exec, exception));
+ return jsUndefined();
+ }
+ if (value)
+ return toJS(exec, value);
+ }
+ }
+ }
+ }
+ }
+
+ return JSValue();
+}
+
+template <class Parent>
+EncodedJSValue JSCallbackObject<Parent>::staticFunctionGetter(ExecState* exec, JSObject* slotParent, EncodedJSValue, PropertyName propertyName)
+{
+ JSCallbackObject* thisObj = asCallbackObject(slotParent);
+
+ // Check for cached or override property.
+ PropertySlot slot2(thisObj);
+ if (Parent::getOwnPropertySlot(thisObj, exec, propertyName, slot2))
+ return JSValue::encode(slot2.getValue(exec, propertyName));
+
+ if (StringImpl* name = propertyName.uid()) {
+ for (JSClassRef jsClass = thisObj->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
+ if (StaticFunctionEntry* entry = staticFunctions->get(name)) {
+ if (JSObjectCallAsFunctionCallback callAsFunction = entry->callAsFunction) {
+ VM& vm = exec->vm();
+ JSObject* o = JSCallbackFunction::create(vm, thisObj->globalObject(), callAsFunction, name);
+ thisObj->putDirect(vm, propertyName, o, entry->attributes);
+ return JSValue::encode(o);
+ }
+ }
+ }
+ }
+ }
+
+ return JSValue::encode(exec->vm().throwException(exec, createReferenceError(exec, ASCIILiteral("Static function property defined with NULL callAsFunction callback."))));
+}
+
+template <class Parent>
+EncodedJSValue JSCallbackObject<Parent>::callbackGetter(ExecState* exec, JSObject* slotParent, EncodedJSValue, PropertyName propertyName)
+{
+ JSCallbackObject* thisObj = asCallbackObject(slotParent);
+
+ JSObjectRef thisRef = toRef(thisObj);
+ RefPtr<OpaqueJSString> propertyNameRef;
+
+ if (StringImpl* name = propertyName.uid()) {
+ for (JSClassRef jsClass = thisObj->classRef(); jsClass; jsClass = jsClass->parentClass) {
+ if (JSObjectGetPropertyCallback getProperty = jsClass->getProperty) {
+ if (!propertyNameRef)
+ propertyNameRef = OpaqueJSString::create(name);
+ JSValueRef exception = 0;
+ JSValueRef value;
+ {
+ JSLock::DropAllLocks dropAllLocks(exec);
+ value = getProperty(toRef(exec), thisRef, propertyNameRef.get(), &exception);
+ }
+ if (exception) {
+ exec->vm().throwException(exec, toJS(exec, exception));
+ return JSValue::encode(jsUndefined());
+ }
+ if (value)
+ return JSValue::encode(toJS(exec, value));
+ }
+ }
+ }
+
+ return JSValue::encode(exec->vm().throwException(exec, createReferenceError(exec, ASCIILiteral("hasProperty callback returned true for a property that doesn't exist."))));
+}
+
+} // namespace JSC
diff --git a/Source/JavaScriptCore/API/JSClassRef.cpp b/Source/JavaScriptCore/API/JSClassRef.cpp
new file mode 100644
index 000000000..e0dbe6043
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSClassRef.cpp
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSClassRef.h"
+
+#include "APICast.h"
+#include "Identifier.h"
+#include "InitializeThreading.h"
+#include "JSCallbackObject.h"
+#include "JSGlobalObject.h"
+#include "JSObjectRef.h"
+#include "ObjectPrototype.h"
+#include "JSCInlines.h"
+#include <wtf/text/StringHash.h>
+#include <wtf/unicode/UTF8.h>
+
+using namespace std;
+using namespace JSC;
+using namespace WTF::Unicode;
+
+const JSClassDefinition kJSClassDefinitionEmpty = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+
+OpaqueJSClass::OpaqueJSClass(const JSClassDefinition* definition, OpaqueJSClass* protoClass)
+ : parentClass(definition->parentClass)
+ , prototypeClass(0)
+ , initialize(definition->initialize)
+ , finalize(definition->finalize)
+ , hasProperty(definition->hasProperty)
+ , getProperty(definition->getProperty)
+ , setProperty(definition->setProperty)
+ , deleteProperty(definition->deleteProperty)
+ , getPropertyNames(definition->getPropertyNames)
+ , callAsFunction(definition->callAsFunction)
+ , callAsConstructor(definition->callAsConstructor)
+ , hasInstance(definition->hasInstance)
+ , convertToType(definition->convertToType)
+ , m_className(String::fromUTF8(definition->className))
+{
+ initializeThreading();
+
+ if (const JSStaticValue* staticValue = definition->staticValues) {
+ m_staticValues = std::make_unique<OpaqueJSClassStaticValuesTable>();
+ while (staticValue->name) {
+ String valueName = String::fromUTF8(staticValue->name);
+ if (!valueName.isNull())
+ m_staticValues->set(valueName.impl(), std::make_unique<StaticValueEntry>(staticValue->getProperty, staticValue->setProperty, staticValue->attributes, valueName));
+ ++staticValue;
+ }
+ }
+
+ if (const JSStaticFunction* staticFunction = definition->staticFunctions) {
+ m_staticFunctions = std::make_unique<OpaqueJSClassStaticFunctionsTable>();
+ while (staticFunction->name) {
+ String functionName = String::fromUTF8(staticFunction->name);
+ if (!functionName.isNull())
+ m_staticFunctions->set(functionName.impl(), std::make_unique<StaticFunctionEntry>(staticFunction->callAsFunction, staticFunction->attributes));
+ ++staticFunction;
+ }
+ }
+
+ if (protoClass)
+ prototypeClass = JSClassRetain(protoClass);
+}
+
+OpaqueJSClass::~OpaqueJSClass()
+{
+ // The empty string is shared across threads & is an identifier, in all other cases we should have done a deep copy in className(), below.
+ ASSERT(!m_className.length() || !m_className.impl()->isAtomic());
+
+#ifndef NDEBUG
+ if (m_staticValues) {
+ OpaqueJSClassStaticValuesTable::const_iterator end = m_staticValues->end();
+ for (OpaqueJSClassStaticValuesTable::const_iterator it = m_staticValues->begin(); it != end; ++it)
+ ASSERT(!it->key->isAtomic());
+ }
+
+ if (m_staticFunctions) {
+ OpaqueJSClassStaticFunctionsTable::const_iterator end = m_staticFunctions->end();
+ for (OpaqueJSClassStaticFunctionsTable::const_iterator it = m_staticFunctions->begin(); it != end; ++it)
+ ASSERT(!it->key->isAtomic());
+ }
+#endif
+
+ if (prototypeClass)
+ JSClassRelease(prototypeClass);
+}
+
+Ref<OpaqueJSClass> OpaqueJSClass::createNoAutomaticPrototype(const JSClassDefinition* definition)
+{
+ return adoptRef(*new OpaqueJSClass(definition, 0));
+}
+
+Ref<OpaqueJSClass> OpaqueJSClass::create(const JSClassDefinition* clientDefinition)
+{
+ JSClassDefinition definition = *clientDefinition; // Avoid modifying client copy.
+
+ JSClassDefinition protoDefinition = kJSClassDefinitionEmpty;
+ protoDefinition.finalize = 0;
+ swap(definition.staticFunctions, protoDefinition.staticFunctions); // Move static functions to the prototype.
+
+ // We are supposed to use JSClassRetain/Release but since we know that we currently have
+ // the only reference to this class object we cheat and use a RefPtr instead.
+ RefPtr<OpaqueJSClass> protoClass = adoptRef(new OpaqueJSClass(&protoDefinition, 0));
+ return adoptRef(*new OpaqueJSClass(&definition, protoClass.get()));
+}
+
+OpaqueJSClassContextData::OpaqueJSClassContextData(JSC::VM&, OpaqueJSClass* jsClass)
+ : m_class(jsClass)
+{
+ if (jsClass->m_staticValues) {
+ staticValues = std::make_unique<OpaqueJSClassStaticValuesTable>();
+ OpaqueJSClassStaticValuesTable::const_iterator end = jsClass->m_staticValues->end();
+ for (OpaqueJSClassStaticValuesTable::const_iterator it = jsClass->m_staticValues->begin(); it != end; ++it) {
+ ASSERT(!it->key->isAtomic());
+ String valueName = it->key->isolatedCopy();
+ staticValues->add(valueName.impl(), std::make_unique<StaticValueEntry>(it->value->getProperty, it->value->setProperty, it->value->attributes, valueName));
+ }
+ }
+
+ if (jsClass->m_staticFunctions) {
+ staticFunctions = std::make_unique<OpaqueJSClassStaticFunctionsTable>();
+ OpaqueJSClassStaticFunctionsTable::const_iterator end = jsClass->m_staticFunctions->end();
+ for (OpaqueJSClassStaticFunctionsTable::const_iterator it = jsClass->m_staticFunctions->begin(); it != end; ++it) {
+ ASSERT(!it->key->isAtomic());
+ staticFunctions->add(it->key->isolatedCopy(), std::make_unique<StaticFunctionEntry>(it->value->callAsFunction, it->value->attributes));
+ }
+ }
+}
+
+OpaqueJSClassContextData& OpaqueJSClass::contextData(ExecState* exec)
+{
+ std::unique_ptr<OpaqueJSClassContextData>& contextData = exec->lexicalGlobalObject()->opaqueJSClassData().add(this, nullptr).iterator->value;
+ if (!contextData)
+ contextData = std::make_unique<OpaqueJSClassContextData>(exec->vm(), this);
+ return *contextData;
+}
+
+String OpaqueJSClass::className()
+{
+ // Make a deep copy, so that the caller has no chance to put the original into AtomicStringTable.
+ return m_className.isolatedCopy();
+}
+
+OpaqueJSClassStaticValuesTable* OpaqueJSClass::staticValues(JSC::ExecState* exec)
+{
+ return contextData(exec).staticValues.get();
+}
+
+OpaqueJSClassStaticFunctionsTable* OpaqueJSClass::staticFunctions(JSC::ExecState* exec)
+{
+ return contextData(exec).staticFunctions.get();
+}
+
+/*!
+// Doc here in case we make this public. (Hopefully we won't.)
+@function
+ @abstract Returns the prototype that will be used when constructing an object with a given class.
+ @param ctx The execution context to use.
+ @param jsClass A JSClass whose prototype you want to get.
+ @result The JSObject prototype that was automatically generated for jsClass, or NULL if no prototype was automatically generated. This is the prototype that will be used when constructing an object using jsClass.
+*/
+JSObject* OpaqueJSClass::prototype(ExecState* exec)
+{
+ /* Class (C++) and prototype (JS) inheritance are parallel, so:
+ * (C++) | (JS)
+ * ParentClass | ParentClassPrototype
+ * ^ | ^
+ * | | |
+ * DerivedClass | DerivedClassPrototype
+ */
+
+ if (!prototypeClass)
+ return 0;
+
+ OpaqueJSClassContextData& jsClassData = contextData(exec);
+
+ if (JSObject* prototype = jsClassData.cachedPrototype.get())
+ return prototype;
+
+ // Recursive, but should be good enough for our purposes
+ JSObject* prototype = JSCallbackObject<JSDestructibleObject>::create(exec, exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->callbackObjectStructure(), prototypeClass, &jsClassData); // set jsClassData as the object's private data, so it can clear our reference on destruction
+ if (parentClass) {
+ if (JSObject* parentPrototype = parentClass->prototype(exec))
+ prototype->setPrototype(exec->vm(), parentPrototype);
+ }
+
+ jsClassData.cachedPrototype = Weak<JSObject>(prototype);
+ return prototype;
+}
diff --git a/Source/JavaScriptCore/API/JSClassRef.h b/Source/JavaScriptCore/API/JSClassRef.h
new file mode 100644
index 000000000..fa024d344
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSClassRef.h
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSClassRef_h
+#define JSClassRef_h
+
+#include "OpaqueJSString.h"
+#include "Protect.h"
+#include "Weak.h"
+#include <JavaScriptCore/JSObjectRef.h>
+#include <wtf/HashMap.h>
+#include <wtf/text/WTFString.h>
+
+struct StaticValueEntry {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ StaticValueEntry(JSObjectGetPropertyCallback _getProperty, JSObjectSetPropertyCallback _setProperty, JSPropertyAttributes _attributes, String& propertyName)
+ : getProperty(_getProperty), setProperty(_setProperty), attributes(_attributes), propertyNameRef(OpaqueJSString::create(propertyName))
+ {
+ }
+
+ JSObjectGetPropertyCallback getProperty;
+ JSObjectSetPropertyCallback setProperty;
+ JSPropertyAttributes attributes;
+ RefPtr<OpaqueJSString> propertyNameRef;
+};
+
+struct StaticFunctionEntry {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ StaticFunctionEntry(JSObjectCallAsFunctionCallback _callAsFunction, JSPropertyAttributes _attributes)
+ : callAsFunction(_callAsFunction), attributes(_attributes)
+ {
+ }
+
+ JSObjectCallAsFunctionCallback callAsFunction;
+ JSPropertyAttributes attributes;
+};
+
+typedef HashMap<RefPtr<StringImpl>, std::unique_ptr<StaticValueEntry>> OpaqueJSClassStaticValuesTable;
+typedef HashMap<RefPtr<StringImpl>, std::unique_ptr<StaticFunctionEntry>> OpaqueJSClassStaticFunctionsTable;
+
+struct OpaqueJSClass;
+
+// An OpaqueJSClass (JSClass) is created without a context, so it can be used with any context, even across context groups.
+// This structure holds data members that vary across context groups.
+struct OpaqueJSClassContextData {
+ WTF_MAKE_NONCOPYABLE(OpaqueJSClassContextData); WTF_MAKE_FAST_ALLOCATED;
+public:
+ OpaqueJSClassContextData(JSC::VM&, OpaqueJSClass*);
+
+ // It is necessary to keep OpaqueJSClass alive because of the following rare scenario:
+ // 1. A class is created and used, so its context data is stored in VM hash map.
+ // 2. The class is released, and when all JS objects that use it are collected, OpaqueJSClass
+ // is deleted (that's the part prevented by this RefPtr).
+ // 3. Another class is created at the same address.
+ // 4. When it is used, the old context data is found in VM and used.
+ RefPtr<OpaqueJSClass> m_class;
+
+ std::unique_ptr<OpaqueJSClassStaticValuesTable> staticValues;
+ std::unique_ptr<OpaqueJSClassStaticFunctionsTable> staticFunctions;
+ JSC::Weak<JSC::JSObject> cachedPrototype;
+};
+
+struct OpaqueJSClass : public ThreadSafeRefCounted<OpaqueJSClass> {
+ static Ref<OpaqueJSClass> create(const JSClassDefinition*);
+ static Ref<OpaqueJSClass> createNoAutomaticPrototype(const JSClassDefinition*);
+ JS_EXPORT_PRIVATE ~OpaqueJSClass();
+
+ String className();
+ OpaqueJSClassStaticValuesTable* staticValues(JSC::ExecState*);
+ OpaqueJSClassStaticFunctionsTable* staticFunctions(JSC::ExecState*);
+ JSC::JSObject* prototype(JSC::ExecState*);
+
+ OpaqueJSClass* parentClass;
+ OpaqueJSClass* prototypeClass;
+
+ JSObjectInitializeCallback initialize;
+ JSObjectFinalizeCallback finalize;
+ JSObjectHasPropertyCallback hasProperty;
+ JSObjectGetPropertyCallback getProperty;
+ JSObjectSetPropertyCallback setProperty;
+ JSObjectDeletePropertyCallback deleteProperty;
+ JSObjectGetPropertyNamesCallback getPropertyNames;
+ JSObjectCallAsFunctionCallback callAsFunction;
+ JSObjectCallAsConstructorCallback callAsConstructor;
+ JSObjectHasInstanceCallback hasInstance;
+ JSObjectConvertToTypeCallback convertToType;
+
+private:
+ friend struct OpaqueJSClassContextData;
+
+ OpaqueJSClass();
+ OpaqueJSClass(const OpaqueJSClass&);
+ OpaqueJSClass(const JSClassDefinition*, OpaqueJSClass* protoClass);
+
+ OpaqueJSClassContextData& contextData(JSC::ExecState*);
+
+ // Strings in these data members should not be put into any AtomicStringTable.
+ String m_className;
+ std::unique_ptr<OpaqueJSClassStaticValuesTable> m_staticValues;
+ std::unique_ptr<OpaqueJSClassStaticFunctionsTable> m_staticFunctions;
+};
+
+#endif // JSClassRef_h
diff --git a/Source/JavaScriptCore/API/JSContext.h b/Source/JavaScriptCore/API/JSContext.h
new file mode 100644
index 000000000..7095f91bb
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSContext.h
@@ -0,0 +1,250 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSContext_h
+#define JSContext_h
+
+#include <JavaScriptCore/JavaScript.h>
+#include <JavaScriptCore/WebKitAvailability.h>
+
+#if JSC_OBJC_API_ENABLED
+
+@class JSVirtualMachine, JSValue;
+
+/*!
+@interface
+@discussion An instance of JSContext represents a JavaScript execution environment. All
+ JavaScript execution takes place within a context.
+ JSContext is also used to manage the life-cycle of objects within the
+ JavaScript virtual machine. Every instance of JSValue is associated with a
+ JSContext via a strong reference. The JSValue will keep the JSContext it
+ references alive so long as the JSValue remains alive. When all of the JSValues
+ that reference a particular JSContext have been deallocated the JSContext
+ will be deallocated unless it has been previously retained.
+*/
+NS_CLASS_AVAILABLE(10_9, 7_0)
+@interface JSContext : NSObject
+
+/*!
+@methodgroup Creating New JSContexts
+*/
+/*!
+@method
+@abstract Create a JSContext.
+@result The new context.
+*/
+- (instancetype)init;
+
+/*!
+@method
+@abstract Create a JSContext in the specified virtual machine.
+@param virtualMachine The JSVirtualMachine in which the context will be created.
+@result The new context.
+*/
+- (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine;
+
+/*!
+@methodgroup Evaluating Scripts
+*/
+/*!
+@method
+@abstract Evaluate a string of JavaScript code.
+@param script A string containing the JavaScript code to evaluate.
+@result The last value generated by the script.
+*/
+- (JSValue *)evaluateScript:(NSString *)script;
+
+/*!
+@method
+@abstract Evaluate a string of JavaScript code, with a URL for the script's source file.
+@param script A string containing the JavaScript code to evaluate.
+@param sourceURL A URL for the script's source file. Used by debuggers and when reporting exceptions. This parameter is informative only: it does not change the behavior of the script.
+@result The last value generated by the script.
+*/
+- (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL NS_AVAILABLE(10_10, 8_0);
+
+/*!
+@methodgroup Callback Accessors
+*/
+/*!
+@method
+@abstract Get the JSContext that is currently executing.
+@discussion This method may be called from within an Objective-C block or method invoked
+ as a callback from JavaScript to retrieve the callback's context. Outside of
+ a callback from JavaScript this method will return nil.
+@result The currently executing JSContext or nil if there isn't one.
+*/
++ (JSContext *)currentContext;
+
+/*!
+@method
+@abstract Get the JavaScript function that is currently executing.
+@discussion This method may be called from within an Objective-C block or method invoked
+ as a callback from JavaScript to retrieve the callback's context. Outside of
+ a callback from JavaScript this method will return nil.
+@result The currently executing JavaScript function or nil if there isn't one.
+*/
++ (JSValue *)currentCallee NS_AVAILABLE(10_10, 8_0);
+
+/*!
+@method
+@abstract Get the <code>this</code> value of the currently executing method.
+@discussion This method may be called from within an Objective-C block or method invoked
+ as a callback from JavaScript to retrieve the callback's this value. Outside
+ of a callback from JavaScript this method will return nil.
+@result The current <code>this</code> value or nil if there isn't one.
+*/
++ (JSValue *)currentThis;
+
+/*!
+@method
+@abstract Get the arguments to the current callback.
+@discussion This method may be called from within an Objective-C block or method invoked
+ as a callback from JavaScript to retrieve the callback's arguments, objects
+ in the returned array are instances of JSValue. Outside of a callback from
+ JavaScript this method will return nil.
+@result An NSArray of the arguments nil if there is no current callback.
+*/
++ (NSArray *)currentArguments;
+
+/*!
+@methodgroup Global Properties
+*/
+/*!
+@property
+@abstract Get the global object of the context.
+@discussion This method retrieves the global object of the JavaScript execution context.
+ Instances of JSContext originating from WebKit will return a reference to the
+ WindowProxy object.
+@result The global object.
+*/
+@property (readonly, strong) JSValue *globalObject;
+
+/*!
+@property
+@discussion The <code>exception</code> property may be used to throw an exception to JavaScript.
+
+ Before a callback is made from JavaScript to an Objective-C block or method,
+ the prior value of the exception property will be preserved and the property
+ will be set to nil. After the callback has completed the new value of the
+ exception property will be read, and prior value restored. If the new value
+ of exception is not nil, the callback will result in that value being thrown.
+
+ This property may also be used to check for uncaught exceptions arising from
+ API function calls (since the default behaviour of <code>exceptionHandler</code> is to
+ assign an uncaught exception to this property).
+
+ If a JSValue originating from a different JSVirtualMachine than this context
+ is assigned to this property, an Objective-C exception will be raised.
+*/
+@property (strong) JSValue *exception;
+
+/*!
+@property
+@discussion If a call to an API function results in an uncaught JavaScript exception, the
+ <code>exceptionHandler</code> block will be invoked. The default implementation for the
+ exception handler will store the exception to the exception property on
+ context. As a consequence the default behaviour is for unhandled exceptions
+ occurring within a callback from JavaScript to be rethrown upon return.
+ Setting this value to nil will result in all uncaught exceptions thrown from
+ the API being silently consumed.
+*/
+@property (copy) void(^exceptionHandler)(JSContext *context, JSValue *exception);
+
+/*!
+@property
+@discussion All instances of JSContext are associated with a single JSVirtualMachine. The
+ virtual machine provides an "object space" or set of execution resources.
+*/
+@property (readonly, strong) JSVirtualMachine *virtualMachine;
+
+/*!
+@property
+@discussion Name of the JSContext. Exposed when remote debugging the context.
+*/
+@property (copy) NSString *name NS_AVAILABLE(10_10, 8_0);
+
+@end
+
+/*!
+@category
+@discussion Instances of JSContext implement the following methods in order to enable
+ support for subscript access by key and index, for example:
+
+@textblock
+ JSContext *context;
+ JSValue *v = context[@"X"]; // Get value for "X" from the global object.
+ context[@"Y"] = v; // Assign 'v' to "Y" on the global object.
+@/textblock
+
+ An object key passed as a subscript will be converted to a JavaScript value,
+ and then the value converted to a string used to resolve a property of the
+ global object.
+*/
+@interface JSContext (SubscriptSupport)
+
+/*!
+method
+@abstract Get a particular property on the global object.
+@param key
+@result The JSValue for the global object's property.
+*/
+- (JSValue *)objectForKeyedSubscript:(id)key;
+
+/*!
+method
+@abstract Set a particular property on the global object.
+@param object
+@param key
+*/
+- (void)setObject:(id)object forKeyedSubscript:(NSObject <NSCopying> *)key;
+
+@end
+
+/*!
+@category
+@discussion These functions are for bridging between the C API and the Objective-C API.
+*/
+@interface JSContext (JSContextRefSupport)
+
+/*!
+@method
+@abstract Create a JSContext, wrapping its C API counterpart.
+@param jsGlobalContextRef
+@result The JSContext equivalent of the provided JSGlobalContextRef.
+*/
++ (JSContext *)contextWithJSGlobalContextRef:(JSGlobalContextRef)jsGlobalContextRef;
+
+/*!
+@property
+@abstract Get the C API counterpart wrapped by a JSContext.
+@result The C API equivalent of this JSContext.
+*/
+@property (readonly) JSGlobalContextRef JSGlobalContextRef;
+@end
+
+#endif
+
+#endif // JSContext_h
diff --git a/Source/JavaScriptCore/API/JSContextInternal.h b/Source/JavaScriptCore/API/JSContextInternal.h
new file mode 100644
index 000000000..5308fbb92
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSContextInternal.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSContextInternal_h
+#define JSContextInternal_h
+
+#import <JavaScriptCore/JavaScriptCore.h>
+
+#if JSC_OBJC_API_ENABLED
+
+#import <JavaScriptCore/JSContext.h>
+
+struct CallbackData {
+ CallbackData *next;
+ JSContext *context;
+ JSValue *preservedException;
+ JSValueRef calleeValue;
+ JSValueRef thisValue;
+ size_t argumentCount;
+ const JSValueRef *arguments;
+ NSArray *currentArguments;
+};
+
+class WeakContextRef {
+public:
+ WeakContextRef(JSContext * = nil);
+ ~WeakContextRef();
+
+ JSContext * get();
+ void set(JSContext *);
+
+private:
+ JSContext *m_weakContext;
+};
+
+@class JSWrapperMap;
+
+@interface JSContext(Internal)
+
+- (id)initWithGlobalContextRef:(JSGlobalContextRef)context;
+
+- (void)notifyException:(JSValueRef)exception;
+- (JSValue *)valueFromNotifyException:(JSValueRef)exception;
+- (BOOL)boolFromNotifyException:(JSValueRef)exception;
+
+- (void)beginCallbackWithData:(CallbackData *)callbackData calleeValue:(JSValueRef)calleeValue thisValue:(JSValueRef)thisValue argumentCount:(size_t)argumentCount arguments:(const JSValueRef *)arguments;
+- (void)endCallbackWithData:(CallbackData *)callbackData;
+
+- (JSValue *)wrapperForObjCObject:(id)object;
+- (JSValue *)wrapperForJSObject:(JSValueRef)value;
+
+@property (readonly, retain) JSWrapperMap *wrapperMap;
+
+@end
+
+#endif
+
+#endif // JSContextInternal_h
diff --git a/Source/JavaScriptCore/API/JSContextPrivate.h b/Source/JavaScriptCore/API/JSContextPrivate.h
new file mode 100644
index 000000000..7d1d0cbdb
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSContextPrivate.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2014 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSContextPrivate_h
+#define JSContextPrivate_h
+
+#if JSC_OBJC_API_ENABLED
+
+#import <JavaScriptCore/JSContext.h>
+
+@interface JSContext(Private)
+
+/*!
+@property
+@discussion Remote inspection setting of the JSContext. Default value is YES.
+*/
+@property (setter=_setRemoteInspectionEnabled:) BOOL _remoteInspectionEnabled NS_AVAILABLE(10_10, 8_0);
+
+/*!
+@property
+@discussion Set whether or not the native call stack is included when reporting exceptions. Default value is YES.
+*/
+@property (setter=_setIncludesNativeCallStackWhenReportingExceptions:) BOOL _includesNativeCallStackWhenReportingExceptions NS_AVAILABLE(10_10, 8_0);
+
+/*!
+@property
+@discussion Set the run loop the Web Inspector debugger should use when evaluating JavaScript in the JSContext.
+*/
+@property (setter=_setDebuggerRunLoop:) CFRunLoopRef _debuggerRunLoop NS_AVAILABLE(10_10, 8_0);
+
+@end
+
+#endif
+
+#endif // JSContextInternal_h
diff --git a/Source/JavaScriptCore/API/JSContextRef.cpp b/Source/JavaScriptCore/API/JSContextRef.cpp
new file mode 100644
index 000000000..886754a03
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSContextRef.cpp
@@ -0,0 +1,431 @@
+/*
+ * Copyright (C) 2006, 2007, 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSContextRef.h"
+#include "JSContextRefInternal.h"
+
+#include "APICast.h"
+#include "CallFrame.h"
+#include "InitializeThreading.h"
+#include "JSCallbackObject.h"
+#include "JSClassRef.h"
+#include "JSGlobalObject.h"
+#include "JSObject.h"
+#include "JSCInlines.h"
+#include "SourceProvider.h"
+#include "StackVisitor.h"
+#include "Watchdog.h"
+#include <wtf/text/StringBuilder.h>
+#include <wtf/text/StringHash.h>
+
+#if ENABLE(REMOTE_INSPECTOR)
+#include "JSGlobalObjectDebuggable.h"
+#include "JSGlobalObjectInspectorController.h"
+#include "JSRemoteInspector.h"
+#endif
+
+#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS)
+#include "JSContextRefInspectorSupport.h"
+#endif
+
+#if OS(DARWIN)
+#include <mach-o/dyld.h>
+
+static const int32_t webkitFirstVersionWithConcurrentGlobalContexts = 0x2100500; // 528.5.0
+#endif
+
+using namespace JSC;
+
+// From the API's perspective, a context group remains alive iff
+// (a) it has been JSContextGroupRetained
+// OR
+// (b) one of its contexts has been JSContextRetained
+
+JSContextGroupRef JSContextGroupCreate()
+{
+ initializeThreading();
+ return toRef(&VM::createContextGroup().leakRef());
+}
+
+JSContextGroupRef JSContextGroupRetain(JSContextGroupRef group)
+{
+ toJS(group)->ref();
+ return group;
+}
+
+void JSContextGroupRelease(JSContextGroupRef group)
+{
+ VM& vm = *toJS(group);
+
+ JSLockHolder locker(&vm);
+ vm.deref();
+}
+
+static bool internalScriptTimeoutCallback(ExecState* exec, void* callbackPtr, void* callbackData)
+{
+ JSShouldTerminateCallback callback = reinterpret_cast<JSShouldTerminateCallback>(callbackPtr);
+ JSContextRef contextRef = toRef(exec);
+ ASSERT(callback);
+ return callback(contextRef, callbackData);
+}
+
+void JSContextGroupSetExecutionTimeLimit(JSContextGroupRef group, double limit, JSShouldTerminateCallback callback, void* callbackData)
+{
+ VM& vm = *toJS(group);
+ JSLockHolder locker(&vm);
+ Watchdog& watchdog = vm.ensureWatchdog();
+ if (callback) {
+ void* callbackPtr = reinterpret_cast<void*>(callback);
+ watchdog.setTimeLimit(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::duration<double>(limit)), internalScriptTimeoutCallback, callbackPtr, callbackData);
+ } else
+ watchdog.setTimeLimit(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::duration<double>(limit)));
+}
+
+void JSContextGroupClearExecutionTimeLimit(JSContextGroupRef group)
+{
+ VM& vm = *toJS(group);
+ JSLockHolder locker(&vm);
+ if (vm.watchdog)
+ vm.watchdog->setTimeLimit(Watchdog::noTimeLimit);
+}
+
+// From the API's perspective, a global context remains alive iff it has been JSGlobalContextRetained.
+
+JSGlobalContextRef JSGlobalContextCreate(JSClassRef globalObjectClass)
+{
+ initializeThreading();
+
+#if OS(DARWIN)
+ // If the application was linked before JSGlobalContextCreate was changed to use a unique VM,
+ // we use a shared one for backwards compatibility.
+ if (NSVersionOfLinkTimeLibrary("JavaScriptCore") <= webkitFirstVersionWithConcurrentGlobalContexts) {
+ return JSGlobalContextCreateInGroup(toRef(&VM::sharedInstance()), globalObjectClass);
+ }
+#endif // OS(DARWIN)
+
+ return JSGlobalContextCreateInGroup(0, globalObjectClass);
+}
+
+JSGlobalContextRef JSGlobalContextCreateInGroup(JSContextGroupRef group, JSClassRef globalObjectClass)
+{
+ initializeThreading();
+
+ RefPtr<VM> vm = group ? PassRefPtr<VM>(toJS(group)) : VM::createContextGroup();
+
+ JSLockHolder locker(vm.get());
+
+ if (!globalObjectClass) {
+ JSGlobalObject* globalObject = JSGlobalObject::create(*vm, JSGlobalObject::createStructure(*vm, jsNull()));
+#if ENABLE(REMOTE_INSPECTOR)
+ if (JSRemoteInspectorGetInspectionEnabledByDefault())
+ globalObject->setRemoteDebuggingEnabled(true);
+#endif
+ return JSGlobalContextRetain(toGlobalRef(globalObject->globalExec()));
+ }
+
+ JSGlobalObject* globalObject = JSCallbackObject<JSGlobalObject>::create(*vm, globalObjectClass, JSCallbackObject<JSGlobalObject>::createStructure(*vm, 0, jsNull()));
+ ExecState* exec = globalObject->globalExec();
+ JSValue prototype = globalObjectClass->prototype(exec);
+ if (!prototype)
+ prototype = jsNull();
+ globalObject->resetPrototype(*vm, prototype);
+#if ENABLE(REMOTE_INSPECTOR)
+ if (JSRemoteInspectorGetInspectionEnabledByDefault())
+ globalObject->setRemoteDebuggingEnabled(true);
+#endif
+ return JSGlobalContextRetain(toGlobalRef(exec));
+}
+
+JSGlobalContextRef JSGlobalContextRetain(JSGlobalContextRef ctx)
+{
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ VM& vm = exec->vm();
+ gcProtect(exec->vmEntryGlobalObject());
+ vm.ref();
+ return ctx;
+}
+
+void JSGlobalContextRelease(JSGlobalContextRef ctx)
+{
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ VM& vm = exec->vm();
+ bool protectCountIsZero = Heap::heap(exec->vmEntryGlobalObject())->unprotect(exec->vmEntryGlobalObject());
+ if (protectCountIsZero)
+ vm.heap.reportAbandonedObjectGraph();
+ vm.deref();
+}
+
+JSObjectRef JSContextGetGlobalObject(JSContextRef ctx)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toRef(jsCast<JSObject*>(exec->lexicalGlobalObject()->methodTable()->toThis(exec->lexicalGlobalObject(), exec, NotStrictMode)));
+}
+
+JSContextGroupRef JSContextGetGroup(JSContextRef ctx)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ return toRef(&exec->vm());
+}
+
+JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toGlobalRef(exec->lexicalGlobalObject()->globalExec());
+}
+
+JSStringRef JSGlobalContextCopyName(JSGlobalContextRef ctx)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ String name = exec->vmEntryGlobalObject()->name();
+ if (name.isNull())
+ return 0;
+
+ return OpaqueJSString::create(name).leakRef();
+}
+
+void JSGlobalContextSetName(JSGlobalContextRef ctx, JSStringRef name)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ exec->vmEntryGlobalObject()->setName(name ? name->string() : String());
+}
+
+
+class BacktraceFunctor {
+public:
+ BacktraceFunctor(StringBuilder& builder, unsigned remainingCapacityForFrameCapture)
+ : m_builder(builder)
+ , m_remainingCapacityForFrameCapture(remainingCapacityForFrameCapture)
+ {
+ }
+
+ StackVisitor::Status operator()(StackVisitor& visitor)
+ {
+ if (m_remainingCapacityForFrameCapture) {
+ // If callee is unknown, but we've not added any frame yet, we should
+ // still add the frame, because something called us, and gave us arguments.
+ JSObject* callee = visitor->callee();
+ if (!callee && visitor->index())
+ return StackVisitor::Done;
+
+ StringBuilder& builder = m_builder;
+ if (!builder.isEmpty())
+ builder.append('\n');
+ builder.append('#');
+ builder.appendNumber(visitor->index());
+ builder.append(' ');
+ builder.append(visitor->functionName());
+ builder.appendLiteral("() at ");
+ builder.append(visitor->sourceURL());
+ if (visitor->isJSFrame()) {
+ builder.append(':');
+ unsigned lineNumber;
+ unsigned unusedColumn;
+ visitor->computeLineAndColumn(lineNumber, unusedColumn);
+ builder.appendNumber(lineNumber);
+ }
+
+ if (!callee)
+ return StackVisitor::Done;
+
+ m_remainingCapacityForFrameCapture--;
+ return StackVisitor::Continue;
+ }
+ return StackVisitor::Done;
+ }
+
+private:
+ StringBuilder& m_builder;
+ unsigned m_remainingCapacityForFrameCapture;
+};
+
+JSStringRef JSContextCreateBacktrace(JSContextRef ctx, unsigned maxStackSize)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder lock(exec);
+ StringBuilder builder;
+ CallFrame* frame = exec->vm().topCallFrame;
+
+ ASSERT(maxStackSize);
+ BacktraceFunctor functor(builder, maxStackSize);
+ frame->iterate(functor);
+
+ return OpaqueJSString::create(builder.toString()).leakRef();
+}
+
+bool JSGlobalContextGetRemoteInspectionEnabled(JSGlobalContextRef ctx)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder lock(exec);
+
+ return exec->vmEntryGlobalObject()->remoteDebuggingEnabled();
+}
+
+void JSGlobalContextSetRemoteInspectionEnabled(JSGlobalContextRef ctx, bool enabled)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder lock(exec);
+
+ exec->vmEntryGlobalObject()->setRemoteDebuggingEnabled(enabled);
+}
+
+bool JSGlobalContextGetIncludesNativeCallStackWhenReportingExceptions(JSGlobalContextRef ctx)
+{
+#if ENABLE(REMOTE_INSPECTOR)
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder lock(exec);
+
+ JSGlobalObject* globalObject = exec->vmEntryGlobalObject();
+ return globalObject->inspectorController().includesNativeCallStackWhenReportingExceptions();
+#else
+ UNUSED_PARAM(ctx);
+ return false;
+#endif
+}
+
+void JSGlobalContextSetIncludesNativeCallStackWhenReportingExceptions(JSGlobalContextRef ctx, bool includesNativeCallStack)
+{
+#if ENABLE(REMOTE_INSPECTOR)
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder lock(exec);
+
+ JSGlobalObject* globalObject = exec->vmEntryGlobalObject();
+ globalObject->inspectorController().setIncludesNativeCallStackWhenReportingExceptions(includesNativeCallStack);
+#else
+ UNUSED_PARAM(ctx);
+ UNUSED_PARAM(includesNativeCallStack);
+#endif
+}
+
+#if USE(CF)
+CFRunLoopRef JSGlobalContextGetDebuggerRunLoop(JSGlobalContextRef ctx)
+{
+#if ENABLE(REMOTE_INSPECTOR)
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return nullptr;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder lock(exec);
+
+ return exec->vmEntryGlobalObject()->inspectorDebuggable().debuggerRunLoop();
+#else
+ UNUSED_PARAM(ctx);
+ return nullptr;
+#endif
+}
+
+void JSGlobalContextSetDebuggerRunLoop(JSGlobalContextRef ctx, CFRunLoopRef runLoop)
+{
+#if ENABLE(REMOTE_INSPECTOR)
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder lock(exec);
+
+ exec->vmEntryGlobalObject()->inspectorDebuggable().setDebuggerRunLoop(runLoop);
+#else
+ UNUSED_PARAM(ctx);
+ UNUSED_PARAM(runLoop);
+#endif
+}
+#endif // USE(CF)
+
+#if ENABLE(INSPECTOR_ALTERNATE_DISPATCHERS)
+Inspector::AugmentableInspectorController* JSGlobalContextGetAugmentableInspectorController(JSGlobalContextRef ctx)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return nullptr;
+ }
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder lock(exec);
+
+ return &exec->vmEntryGlobalObject()->inspectorController();
+}
+#endif
diff --git a/Source/JavaScriptCore/API/JSContextRef.h b/Source/JavaScriptCore/API/JSContextRef.h
new file mode 100644
index 000000000..0c800bced
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSContextRef.h
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSContextRef_h
+#define JSContextRef_h
+
+#include <JavaScriptCore/JSObjectRef.h>
+#include <JavaScriptCore/JSValueRef.h>
+#include <JavaScriptCore/WebKitAvailability.h>
+
+#ifndef __cplusplus
+#include <stdbool.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+@function
+@abstract Creates a JavaScript context group.
+@discussion A JSContextGroup associates JavaScript contexts with one another.
+ Contexts in the same group may share and exchange JavaScript objects. Sharing and/or exchanging
+ JavaScript objects between contexts in different groups will produce undefined behavior.
+ When objects from the same context group are used in multiple threads, explicit
+ synchronization is required.
+@result The created JSContextGroup.
+*/
+JS_EXPORT JSContextGroupRef JSContextGroupCreate(void) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+@function
+@abstract Retains a JavaScript context group.
+@param group The JSContextGroup to retain.
+@result A JSContextGroup that is the same as group.
+*/
+JS_EXPORT JSContextGroupRef JSContextGroupRetain(JSContextGroupRef group) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+@function
+@abstract Releases a JavaScript context group.
+@param group The JSContextGroup to release.
+*/
+JS_EXPORT void JSContextGroupRelease(JSContextGroupRef group) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+@function
+@abstract Creates a global JavaScript execution context.
+@discussion JSGlobalContextCreate allocates a global object and populates it with all the
+ built-in JavaScript objects, such as Object, Function, String, and Array.
+
+ In WebKit version 4.0 and later, the context is created in a unique context group.
+ Therefore, scripts may execute in it concurrently with scripts executing in other contexts.
+ However, you may not use values created in the context in other contexts.
+@param globalObjectClass The class to use when creating the global object. Pass
+ NULL to use the default object class.
+@result A JSGlobalContext with a global object of class globalObjectClass.
+*/
+JS_EXPORT JSGlobalContextRef JSGlobalContextCreate(JSClassRef globalObjectClass) CF_AVAILABLE(10_5, 7_0);
+
+/*!
+@function
+@abstract Creates a global JavaScript execution context in the context group provided.
+@discussion JSGlobalContextCreateInGroup allocates a global object and populates it with
+ all the built-in JavaScript objects, such as Object, Function, String, and Array.
+@param globalObjectClass The class to use when creating the global object. Pass
+ NULL to use the default object class.
+@param group The context group to use. The created global context retains the group.
+ Pass NULL to create a unique group for the context.
+@result A JSGlobalContext with a global object of class globalObjectClass and a context
+ group equal to group.
+*/
+JS_EXPORT JSGlobalContextRef JSGlobalContextCreateInGroup(JSContextGroupRef group, JSClassRef globalObjectClass) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+@function
+@abstract Retains a global JavaScript execution context.
+@param ctx The JSGlobalContext to retain.
+@result A JSGlobalContext that is the same as ctx.
+*/
+JS_EXPORT JSGlobalContextRef JSGlobalContextRetain(JSGlobalContextRef ctx);
+
+/*!
+@function
+@abstract Releases a global JavaScript execution context.
+@param ctx The JSGlobalContext to release.
+*/
+JS_EXPORT void JSGlobalContextRelease(JSGlobalContextRef ctx);
+
+/*!
+@function
+@abstract Gets the global object of a JavaScript execution context.
+@param ctx The JSContext whose global object you want to get.
+@result ctx's global object.
+*/
+JS_EXPORT JSObjectRef JSContextGetGlobalObject(JSContextRef ctx);
+
+/*!
+@function
+@abstract Gets the context group to which a JavaScript execution context belongs.
+@param ctx The JSContext whose group you want to get.
+@result ctx's group.
+*/
+JS_EXPORT JSContextGroupRef JSContextGetGroup(JSContextRef ctx) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+@function
+@abstract Gets the global context of a JavaScript execution context.
+@param ctx The JSContext whose global context you want to get.
+@result ctx's global context.
+*/
+JS_EXPORT JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx) CF_AVAILABLE(10_7, 7_0);
+
+/*!
+@function
+@abstract Gets a copy of the name of a context.
+@param ctx The JSGlobalContext whose name you want to get.
+@result The name for ctx.
+@discussion A JSGlobalContext's name is exposed for remote debugging to make it
+easier to identify the context you would like to attach to.
+*/
+JS_EXPORT JSStringRef JSGlobalContextCopyName(JSGlobalContextRef ctx) CF_AVAILABLE(10_10, 8_0);
+
+/*!
+@function
+@abstract Sets the remote debugging name for a context.
+@param ctx The JSGlobalContext that you want to name.
+@param name The remote debugging name to set on ctx.
+*/
+JS_EXPORT void JSGlobalContextSetName(JSGlobalContextRef ctx, JSStringRef name) CF_AVAILABLE(10_10, 8_0);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSContextRef_h */
diff --git a/Source/JavaScriptCore/API/JSContextRefInspectorSupport.h b/Source/JavaScriptCore/API/JSContextRefInspectorSupport.h
new file mode 100644
index 000000000..a09d828bd
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSContextRefInspectorSupport.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2014 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSContextRefInspectorSupport_h
+#define JSContextRefInspectorSupport_h
+
+#ifndef __cplusplus
+#error Requires C++ Support.
+#endif
+
+#include <JavaScriptCore/JSContextRefPrivate.h>
+
+namespace Inspector {
+class AugmentableInspectorController;
+}
+
+extern "C" {
+JS_EXPORT Inspector::AugmentableInspectorController* JSGlobalContextGetAugmentableInspectorController(JSGlobalContextRef);
+}
+
+#endif // JSContextRefInspectorSupport_h
diff --git a/Source/JavaScriptCore/API/JSContextRefInternal.h b/Source/JavaScriptCore/API/JSContextRefInternal.h
new file mode 100644
index 000000000..85632b8c7
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSContextRefInternal.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2014 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSContextRefInternal_h
+#define JSContextRefInternal_h
+
+#include "JSContextRefPrivate.h"
+
+#if USE(CF)
+#include <CoreFoundation/CFRunLoop.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if USE(CF)
+/*!
+@function
+@abstract Gets the run loop used by the Web Inspector debugger when evaluating JavaScript in this context.
+@param ctx The JSGlobalContext whose setting you want to get.
+*/
+JS_EXPORT CFRunLoopRef JSGlobalContextGetDebuggerRunLoop(JSGlobalContextRef ctx) CF_AVAILABLE(10_10, 8_0);
+
+/*!
+@function
+@abstract Sets the run loop used by the Web Inspector debugger when evaluating JavaScript in this context.
+@param ctx The JSGlobalContext that you want to change.
+@param runLoop The new value of the setting for the context.
+*/
+JS_EXPORT void JSGlobalContextSetDebuggerRunLoop(JSGlobalContextRef ctx, CFRunLoopRef) CF_AVAILABLE(10_10, 8_0);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // JSContextRefInternal_h
diff --git a/Source/JavaScriptCore/API/JSContextRefPrivate.h b/Source/JavaScriptCore/API/JSContextRefPrivate.h
new file mode 100644
index 000000000..5a5bebd42
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSContextRefPrivate.h
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSContextRefPrivate_h
+#define JSContextRefPrivate_h
+
+#include <JavaScriptCore/JSObjectRef.h>
+#include <JavaScriptCore/JSValueRef.h>
+#include <JavaScriptCore/WebKitAvailability.h>
+
+#ifndef __cplusplus
+#include <stdbool.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+@function
+@abstract Gets a Backtrace for the existing context
+@param ctx The JSContext whose backtrace you want to get
+@result A string containing the backtrace
+*/
+JS_EXPORT JSStringRef JSContextCreateBacktrace(JSContextRef ctx, unsigned maxStackSize) CF_AVAILABLE(10_6, 7_0);
+
+
+/*!
+@typedef JSShouldTerminateCallback
+@abstract The callback invoked when script execution has exceeded the allowed
+ time limit previously specified via JSContextGroupSetExecutionTimeLimit.
+@param ctx The execution context to use.
+@param context User specified context data previously passed to
+ JSContextGroupSetExecutionTimeLimit.
+@discussion If you named your function Callback, you would declare it like this:
+
+ bool Callback(JSContextRef ctx, void* context);
+
+ If you return true, the timed out script will terminate.
+ If you return false, the script will run for another period of the allowed
+ time limit specified via JSContextGroupSetExecutionTimeLimit.
+
+ Within this callback function, you may call JSContextGroupSetExecutionTimeLimit
+ to set a new time limit, or JSContextGroupClearExecutionTimeLimit to cancel the
+ timeout.
+*/
+typedef bool
+(*JSShouldTerminateCallback) (JSContextRef ctx, void* context);
+
+/*!
+@function
+@abstract Sets the script execution time limit.
+@param group The JavaScript context group that this time limit applies to.
+@param limit The time limit of allowed script execution time in seconds.
+@param callback The callback function that will be invoked when the time limit
+ has been reached. This will give you a chance to decide if you want to
+ terminate the script or not. If you pass a NULL callback, the script will be
+ terminated unconditionally when the time limit has been reached.
+@param context User data that you can provide to be passed back to you
+ in your callback.
+
+ In order to guarantee that the execution time limit will take effect, you will
+ need to call JSContextGroupSetExecutionTimeLimit before you start executing
+ any scripts.
+*/
+JS_EXPORT void JSContextGroupSetExecutionTimeLimit(JSContextGroupRef, double limit, JSShouldTerminateCallback, void* context) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+@function
+@abstract Clears the script execution time limit.
+@param group The JavaScript context group that the time limit is cleared on.
+*/
+JS_EXPORT void JSContextGroupClearExecutionTimeLimit(JSContextGroupRef) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+@function
+@abstract Gets a whether or not remote inspection is enabled on the context.
+@param ctx The JSGlobalContext whose setting you want to get.
+@result The value of the setting, true if remote inspection is enabled, otherwise false.
+@discussion Remote inspection is true by default.
+*/
+JS_EXPORT bool JSGlobalContextGetRemoteInspectionEnabled(JSGlobalContextRef ctx) CF_AVAILABLE(10_10, 8_0);
+
+/*!
+@function
+@abstract Sets the remote inspection setting for a context.
+@param ctx The JSGlobalContext that you want to change.
+@param enabled The new remote inspection enabled setting for the context.
+*/
+JS_EXPORT void JSGlobalContextSetRemoteInspectionEnabled(JSGlobalContextRef ctx, bool enabled) CF_AVAILABLE(10_10, 8_0);
+
+/*!
+@function
+@abstract Gets the include native call stack when reporting exceptions setting for a context.
+@param ctx The JSGlobalContext whose setting you want to get.
+@result The value of the setting, true if remote inspection is enabled, otherwise false.
+@discussion This setting is true by default.
+*/
+JS_EXPORT bool JSGlobalContextGetIncludesNativeCallStackWhenReportingExceptions(JSGlobalContextRef ctx) CF_AVAILABLE(10_10, 8_0);
+
+/*!
+@function
+@abstract Sets the include native call stack when reporting exceptions setting for a context.
+@param ctx The JSGlobalContext that you want to change.
+@param includeNativeCallStack The new value of the setting for the context.
+*/
+JS_EXPORT void JSGlobalContextSetIncludesNativeCallStackWhenReportingExceptions(JSGlobalContextRef ctx, bool includesNativeCallStack) CF_AVAILABLE(10_10, 8_0);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSContextRefPrivate_h */
diff --git a/Source/JavaScriptCore/API/JSExport.h b/Source/JavaScriptCore/API/JSExport.h
new file mode 100644
index 000000000..2d78dcc7a
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSExport.h
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <JavaScriptCore/JavaScriptCore.h>
+
+#if JSC_OBJC_API_ENABLED
+
+/*!
+@protocol
+@abstract JSExport provides a declarative way to export Objective-C instance methods,
+ class methods, and properties to JavaScript code.
+
+@discussion When a JavaScript value is created from an instance of an Objective-C class
+ for which no copying conversion is specified a JavaScript wrapper object will
+ be created.
+
+ In JavaScript, inheritance is supported via a chain of prototype objects, and
+ for each Objective-C class (and per JSContext) an object appropriate for use
+ as a prototype will be provided. For the class NSObject the prototype object
+ will be the JavaScript context's Object Prototype. For all other Objective-C
+ classes a Prototype object will be created. The Prototype object for a given
+ Objective-C class will have its internal [Prototype] property set to point to
+ the Prototype object of the Objective-C class's superclass. As such the
+ prototype chain for a JavaScript wrapper object will reflect the wrapped
+ Objective-C type's inheritance hierarchy.
+
+ In addition to the Prototype object a JavaScript Constructor object will also
+ be produced for each Objective-C class. The Constructor object has a property
+ named 'prototype' that references the Prototype object, and the Prototype
+ object has a property named 'constructor' that references the Constructor.
+ The Constructor object is not callable.
+
+ By default no methods or properties of the Objective-C class will be exposed
+ to JavaScript; however methods and properties may explicitly be exported.
+ For each protocol that a class conforms to, if the protocol incorporates the
+ protocol JSExport, then the protocol will be interpreted as a list of methods
+ and properties to be exported to JavaScript.
+
+ For each instance method being exported a corresponding JavaScript function
+ will be assigned as a property of the Prototype object. For each Objective-C
+ property being exported a JavaScript accessor property will be created on the
+ Prototype. For each class method exported a JavaScript function will be
+ created on the Constructor object. For example:
+
+<pre>
+@textblock
+ @protocol MyClassJavaScriptMethods <JSExport>
+ - (void)foo;
+ @end
+
+ @interface MyClass : NSObject <MyClassJavaScriptMethods>
+ - (void)foo;
+ - (void)bar;
+ @end
+@/textblock
+</pre>
+
+ Data properties that are created on the prototype or constructor objects have
+ the attributes: <code>writable:true</code>, <code>enumerable:false</code>, <code>configurable:true</code>.
+ Accessor properties have the attributes: <code>enumerable:false</code> and <code>configurable:true</code>.
+
+ If an instance of <code>MyClass</code> is converted to a JavaScript value, the resulting
+ wrapper object will (via its prototype) export the method <code>foo</code> to JavaScript,
+ since the class conforms to the <code>MyClassJavaScriptMethods</code> protocol, and this
+ protocol incorporates <code>JSExport</code>. <code>bar</code> will not be exported.
+
+ Properties, arguments, and return values of the following types are
+ supported:
+
+ Primitive numbers: signed values of up to 32-bits are converted in a manner
+ consistent with valueWithInt32/toInt32, unsigned values of up to 32-bits
+ are converted in a manner consistent with valueWithUInt32/toUInt32, all
+ other numeric values are converted consistently with valueWithDouble/
+ toDouble.
+
+ BOOL: values are converted consistently with valueWithBool/toBool.
+
+ id: values are converted consistently with valueWithObject/toObject.
+
+ Objective-C Class: - where the type is a pointer to a specified Objective-C
+ class, conversion is consistent with valueWithObjectOfClass/toObject.
+
+ struct types: C struct types are supported, where JSValue provides support
+ for the given type. Support is built in for CGPoint, NSRange, CGRect, and
+ CGSize.
+
+ block types: Blocks can only be passed if they had been converted
+ successfully by valueWithObject/toObject previously.
+
+ For any interface that conforms to JSExport the normal copying conversion for
+ built in types will be inhibited - so, for example, if an instance that
+ derives from NSString but conforms to JSExport is passed to valueWithObject:
+ then a wrapper object for the Objective-C object will be returned rather than
+ a JavaScript string primitive.
+*/
+@protocol JSExport
+@end
+
+/*!
+@define
+@abstract Rename a selector when it's exported to JavaScript.
+@discussion When a selector that takes one or more arguments is converted to a JavaScript
+ property name, by default a property name will be generated by performing the
+ following conversion:
+
+ - All colons are removed from the selector
+
+ - Any lowercase letter that had followed a colon will be capitalized.
+
+ Under the default conversion a selector <code>doFoo:withBar:</code> will be exported as
+ <code>doFooWithBar</code>. The default conversion may be overriden using the JSExportAs
+ macro, for example to export a method <code>doFoo:withBar:</code> as <code>doFoo</code>:
+
+<pre>
+@textblock
+ @protocol MyClassJavaScriptMethods <JSExport>
+ JSExportAs(doFoo,
+ - (void)doFoo:(id)foo withBar:(id)bar
+ );
+ @end
+@/textblock
+</pre>
+
+ Note that the JSExport macro may only be applied to a selector that takes one
+ or more argument.
+*/
+#define JSExportAs(PropertyName, Selector) \
+ @optional Selector __JS_EXPORT_AS__##PropertyName:(id)argument; @required Selector
+
+#endif
diff --git a/Source/JavaScriptCore/API/JSManagedValue.h b/Source/JavaScriptCore/API/JSManagedValue.h
new file mode 100644
index 000000000..97764eead
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSManagedValue.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSManagedValue_h
+#define JSManagedValue_h
+
+#import <JavaScriptCore/JSBase.h>
+#import <JavaScriptCore/WebKitAvailability.h>
+
+#if JSC_OBJC_API_ENABLED
+
+@class JSValue;
+@class JSContext;
+
+/*!
+@interface
+@discussion JSManagedValue represents a "conditionally retained" JSValue.
+ "Conditionally retained" means that as long as either the JSManagedValue's
+ JavaScript value is reachable through the JavaScript object graph
+ or the JSManagedValue object is reachable through the external Objective-C
+ object graph as reported to the JSVirtualMachine using
+ addManagedReference:withOwner:, the corresponding JavaScript value will
+ be retained. However, if neither of these conditions are true, the
+ corresponding JSValue will be released and set to nil.
+
+ The primary use case for JSManagedValue is for safely referencing JSValues
+ from the Objective-C heap. It is incorrect to store a JSValue into an
+ Objective-C heap object, as this can very easily create a reference cycle,
+ keeping the entire JSContext alive.
+*/
+NS_CLASS_AVAILABLE(10_9, 7_0)
+@interface JSManagedValue : NSObject
+
+/*!
+@method
+@abstract Create a JSManagedValue from a JSValue.
+@param value
+@result The new JSManagedValue.
+*/
++ (JSManagedValue *)managedValueWithValue:(JSValue *)value;
++ (JSManagedValue *)managedValueWithValue:(JSValue *)value andOwner:(id)owner NS_AVAILABLE(10_10, 8_0);
+
+/*!
+@method
+@abstract Create a JSManagedValue.
+@param value
+@result The new JSManagedValue.
+*/
+- (instancetype)initWithValue:(JSValue *)value;
+
+/*!
+@property
+@abstract Get the JSValue from the JSManagedValue.
+@result The corresponding JSValue for this JSManagedValue or
+ nil if the JSValue has been collected.
+*/
+@property (readonly, strong) JSValue *value;
+
+@end
+
+#endif // JSC_OBJC_API_ENABLED
+
+#endif // JSManagedValue_h
diff --git a/Source/JavaScriptCore/API/JSManagedValueInternal.h b/Source/JavaScriptCore/API/JSManagedValueInternal.h
new file mode 100644
index 000000000..2443fe5a9
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSManagedValueInternal.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSManagedValueInternal_h
+#define JSManagedValueInternal_h
+
+#import <JavaScriptCore/JSBase.h>
+
+#if JSC_OBJC_API_ENABLED
+
+@interface JSManagedValue(Internal)
+
+- (void)didAddOwner:(id)owner;
+- (void)didRemoveOwner:(id)owner;
+
+@end
+
+#endif // JSC_OBJC_API_ENABLED
+
+#endif // JSManagedValueInternal_h
diff --git a/Source/JavaScriptCore/API/JSObjectRef.cpp b/Source/JavaScriptCore/API/JSObjectRef.cpp
new file mode 100644
index 000000000..e05fbbbdd
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSObjectRef.cpp
@@ -0,0 +1,665 @@
+/*
+ * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Kelvin W Sherlock (ksherlock@gmail.com)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSObjectRef.h"
+#include "JSObjectRefPrivate.h"
+
+#include "APICast.h"
+#include "ButterflyInlines.h"
+#include "CodeBlock.h"
+#include "CopiedSpaceInlines.h"
+#include "DateConstructor.h"
+#include "ErrorConstructor.h"
+#include "Exception.h"
+#include "FunctionConstructor.h"
+#include "Identifier.h"
+#include "InitializeThreading.h"
+#include "JSAPIWrapperObject.h"
+#include "JSArray.h"
+#include "JSCallbackConstructor.h"
+#include "JSCallbackFunction.h"
+#include "JSCallbackObject.h"
+#include "JSClassRef.h"
+#include "JSFunction.h"
+#include "JSGlobalObject.h"
+#include "JSObject.h"
+#include "JSRetainPtr.h"
+#include "JSString.h"
+#include "JSValueRef.h"
+#include "ObjectConstructor.h"
+#include "ObjectPrototype.h"
+#include "JSCInlines.h"
+#include "PropertyNameArray.h"
+#include "RegExpConstructor.h"
+
+#if ENABLE(REMOTE_INSPECTOR)
+#include "JSGlobalObjectInspectorController.h"
+#endif
+
+using namespace JSC;
+
+enum class ExceptionStatus {
+ DidThrow,
+ DidNotThrow
+};
+
+static ExceptionStatus handleExceptionIfNeeded(ExecState* exec, JSValueRef* returnedExceptionRef)
+{
+ if (exec->hadException()) {
+ Exception* exception = exec->exception();
+ if (returnedExceptionRef)
+ *returnedExceptionRef = toRef(exec, exception->value());
+ exec->clearException();
+#if ENABLE(REMOTE_INSPECTOR)
+ exec->vmEntryGlobalObject()->inspectorController().reportAPIException(exec, exception);
+#endif
+ return ExceptionStatus::DidThrow;
+ }
+ return ExceptionStatus::DidNotThrow;
+}
+
+JSClassRef JSClassCreate(const JSClassDefinition* definition)
+{
+ initializeThreading();
+ RefPtr<OpaqueJSClass> jsClass = (definition->attributes & kJSClassAttributeNoAutomaticPrototype)
+ ? OpaqueJSClass::createNoAutomaticPrototype(definition)
+ : OpaqueJSClass::create(definition);
+
+ return jsClass.release().leakRef();
+}
+
+JSClassRef JSClassRetain(JSClassRef jsClass)
+{
+ jsClass->ref();
+ return jsClass;
+}
+
+void JSClassRelease(JSClassRef jsClass)
+{
+ jsClass->deref();
+}
+
+JSObjectRef JSObjectMake(JSContextRef ctx, JSClassRef jsClass, void* data)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ if (!jsClass)
+ return toRef(constructEmptyObject(exec));
+
+ JSCallbackObject<JSDestructibleObject>* object = JSCallbackObject<JSDestructibleObject>::create(exec, exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->callbackObjectStructure(), jsClass, data);
+ if (JSObject* prototype = jsClass->prototype(exec))
+ object->setPrototype(exec->vm(), prototype);
+
+ return toRef(object);
+}
+
+JSObjectRef JSObjectMakeFunctionWithCallback(JSContextRef ctx, JSStringRef name, JSObjectCallAsFunctionCallback callAsFunction)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ return toRef(JSCallbackFunction::create(exec->vm(), exec->lexicalGlobalObject(), callAsFunction, name ? name->string() : ASCIILiteral("anonymous")));
+}
+
+JSObjectRef JSObjectMakeConstructor(JSContextRef ctx, JSClassRef jsClass, JSObjectCallAsConstructorCallback callAsConstructor)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsPrototype = jsClass ? jsClass->prototype(exec) : 0;
+ if (!jsPrototype)
+ jsPrototype = exec->lexicalGlobalObject()->objectPrototype();
+
+ JSCallbackConstructor* constructor = JSCallbackConstructor::create(exec, exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->callbackConstructorStructure(), jsClass, callAsConstructor);
+ constructor->putDirect(exec->vm(), exec->propertyNames().prototype, jsPrototype, DontEnum | DontDelete | ReadOnly);
+ return toRef(constructor);
+}
+
+JSObjectRef JSObjectMakeFunction(JSContextRef ctx, JSStringRef name, unsigned parameterCount, const JSStringRef parameterNames[], JSStringRef body, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ startingLineNumber = std::max(1, startingLineNumber);
+ Identifier nameID = name ? name->identifier(&exec->vm()) : Identifier::fromString(exec, "anonymous");
+
+ MarkedArgumentBuffer args;
+ for (unsigned i = 0; i < parameterCount; i++)
+ args.append(jsString(exec, parameterNames[i]->string()));
+ args.append(jsString(exec, body->string()));
+
+ JSObject* result = constructFunction(exec, exec->lexicalGlobalObject(), args, nameID, sourceURL ? sourceURL->string() : String(), TextPosition(OrdinalNumber::fromOneBasedInt(startingLineNumber), OrdinalNumber::first()));
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ result = 0;
+ return toRef(result);
+}
+
+JSObjectRef JSObjectMakeArray(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* result;
+ if (argumentCount) {
+ MarkedArgumentBuffer argList;
+ for (size_t i = 0; i < argumentCount; ++i)
+ argList.append(toJS(exec, arguments[i]));
+
+ result = constructArray(exec, static_cast<ArrayAllocationProfile*>(0), argList);
+ } else
+ result = constructEmptyArray(exec, 0);
+
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ result = 0;
+
+ return toRef(result);
+}
+
+JSObjectRef JSObjectMakeDate(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ MarkedArgumentBuffer argList;
+ for (size_t i = 0; i < argumentCount; ++i)
+ argList.append(toJS(exec, arguments[i]));
+
+ JSObject* result = constructDate(exec, exec->lexicalGlobalObject(), argList);
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ result = 0;
+
+ return toRef(result);
+}
+
+JSObjectRef JSObjectMakeError(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue message = argumentCount ? toJS(exec, arguments[0]) : jsUndefined();
+ Structure* errorStructure = exec->lexicalGlobalObject()->errorStructure();
+ JSObject* result = ErrorInstance::create(exec, errorStructure, message);
+
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ result = 0;
+
+ return toRef(result);
+}
+
+JSObjectRef JSObjectMakeRegExp(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ MarkedArgumentBuffer argList;
+ for (size_t i = 0; i < argumentCount; ++i)
+ argList.append(toJS(exec, arguments[i]));
+
+ JSObject* result = constructRegExp(exec, exec->lexicalGlobalObject(), argList);
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ result = 0;
+
+ return toRef(result);
+}
+
+JSValueRef JSObjectGetPrototype(JSContextRef ctx, JSObjectRef object)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* jsObject = toJS(object);
+ return toRef(exec, jsObject->prototype());
+}
+
+void JSObjectSetPrototype(JSContextRef ctx, JSObjectRef object, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* jsObject = toJS(object);
+ JSValue jsValue = toJS(exec, value);
+
+ if (JSProxy* proxy = jsDynamicCast<JSProxy*>(jsObject)) {
+ if (JSGlobalObject* globalObject = jsDynamicCast<JSGlobalObject*>(proxy->target())) {
+ globalObject->resetPrototype(exec->vm(), jsValue.isObject() ? jsValue : jsNull());
+ return;
+ }
+ // Someday we might use proxies for something other than JSGlobalObjects, but today is not that day.
+ RELEASE_ASSERT_NOT_REACHED();
+ }
+ jsObject->setPrototypeWithCycleCheck(exec, jsValue.isObject() ? jsValue : jsNull());
+}
+
+bool JSObjectHasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* jsObject = toJS(object);
+
+ return jsObject->hasProperty(exec, propertyName->identifier(&exec->vm()));
+}
+
+JSValueRef JSObjectGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* jsObject = toJS(object);
+
+ JSValue jsValue = jsObject->get(exec, propertyName->identifier(&exec->vm()));
+ handleExceptionIfNeeded(exec, exception);
+ return toRef(exec, jsValue);
+}
+
+void JSObjectSetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* jsObject = toJS(object);
+ Identifier name(propertyName->identifier(&exec->vm()));
+ JSValue jsValue = toJS(exec, value);
+
+ if (attributes && !jsObject->hasProperty(exec, name)) {
+ PropertyDescriptor desc(jsValue, attributes);
+ jsObject->methodTable()->defineOwnProperty(jsObject, exec, name, desc, false);
+ } else {
+ PutPropertySlot slot(jsObject);
+ jsObject->methodTable()->put(jsObject, exec, name, jsValue, slot);
+ }
+
+ handleExceptionIfNeeded(exec, exception);
+}
+
+JSValueRef JSObjectGetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* jsObject = toJS(object);
+
+ JSValue jsValue = jsObject->get(exec, propertyIndex);
+ handleExceptionIfNeeded(exec, exception);
+ return toRef(exec, jsValue);
+}
+
+
+void JSObjectSetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef value, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* jsObject = toJS(object);
+ JSValue jsValue = toJS(exec, value);
+
+ jsObject->methodTable()->putByIndex(jsObject, exec, propertyIndex, jsValue, false);
+ handleExceptionIfNeeded(exec, exception);
+}
+
+bool JSObjectDeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSObject* jsObject = toJS(object);
+
+ bool result = jsObject->methodTable()->deleteProperty(jsObject, exec, propertyName->identifier(&exec->vm()));
+ handleExceptionIfNeeded(exec, exception);
+ return result;
+}
+
+void* JSObjectGetPrivate(JSObjectRef object)
+{
+ JSObject* jsObject = uncheckedToJS(object);
+
+ // Get wrapped object if proxied
+ if (jsObject->inherits(JSProxy::info()))
+ jsObject = jsCast<JSProxy*>(jsObject)->target();
+
+ if (jsObject->inherits(JSCallbackObject<JSGlobalObject>::info()))
+ return jsCast<JSCallbackObject<JSGlobalObject>*>(jsObject)->getPrivate();
+ if (jsObject->inherits(JSCallbackObject<JSDestructibleObject>::info()))
+ return jsCast<JSCallbackObject<JSDestructibleObject>*>(jsObject)->getPrivate();
+#if JSC_OBJC_API_ENABLED
+ if (jsObject->inherits(JSCallbackObject<JSAPIWrapperObject>::info()))
+ return jsCast<JSCallbackObject<JSAPIWrapperObject>*>(jsObject)->getPrivate();
+#endif
+
+ return 0;
+}
+
+bool JSObjectSetPrivate(JSObjectRef object, void* data)
+{
+ JSObject* jsObject = uncheckedToJS(object);
+
+ // Get wrapped object if proxied
+ if (jsObject->inherits(JSProxy::info()))
+ jsObject = jsCast<JSProxy*>(jsObject)->target();
+
+ if (jsObject->inherits(JSCallbackObject<JSGlobalObject>::info())) {
+ jsCast<JSCallbackObject<JSGlobalObject>*>(jsObject)->setPrivate(data);
+ return true;
+ }
+ if (jsObject->inherits(JSCallbackObject<JSDestructibleObject>::info())) {
+ jsCast<JSCallbackObject<JSDestructibleObject>*>(jsObject)->setPrivate(data);
+ return true;
+ }
+#if JSC_OBJC_API_ENABLED
+ if (jsObject->inherits(JSCallbackObject<JSAPIWrapperObject>::info())) {
+ jsCast<JSCallbackObject<JSAPIWrapperObject>*>(jsObject)->setPrivate(data);
+ return true;
+ }
+#endif
+
+ return false;
+}
+
+JSValueRef JSObjectGetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName)
+{
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ JSObject* jsObject = toJS(object);
+ JSValue result;
+ Identifier name(propertyName->identifier(&exec->vm()));
+
+ // Get wrapped object if proxied
+ if (jsObject->inherits(JSProxy::info()))
+ jsObject = jsCast<JSProxy*>(jsObject)->target();
+
+ if (jsObject->inherits(JSCallbackObject<JSGlobalObject>::info()))
+ result = jsCast<JSCallbackObject<JSGlobalObject>*>(jsObject)->getPrivateProperty(name);
+ else if (jsObject->inherits(JSCallbackObject<JSDestructibleObject>::info()))
+ result = jsCast<JSCallbackObject<JSDestructibleObject>*>(jsObject)->getPrivateProperty(name);
+#if JSC_OBJC_API_ENABLED
+ else if (jsObject->inherits(JSCallbackObject<JSAPIWrapperObject>::info()))
+ result = jsCast<JSCallbackObject<JSAPIWrapperObject>*>(jsObject)->getPrivateProperty(name);
+#endif
+ return toRef(exec, result);
+}
+
+bool JSObjectSetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value)
+{
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ JSObject* jsObject = toJS(object);
+ JSValue jsValue = value ? toJS(exec, value) : JSValue();
+ Identifier name(propertyName->identifier(&exec->vm()));
+
+ // Get wrapped object if proxied
+ if (jsObject->inherits(JSProxy::info()))
+ jsObject = jsCast<JSProxy*>(jsObject)->target();
+
+ if (jsObject->inherits(JSCallbackObject<JSGlobalObject>::info())) {
+ jsCast<JSCallbackObject<JSGlobalObject>*>(jsObject)->setPrivateProperty(exec->vm(), name, jsValue);
+ return true;
+ }
+ if (jsObject->inherits(JSCallbackObject<JSDestructibleObject>::info())) {
+ jsCast<JSCallbackObject<JSDestructibleObject>*>(jsObject)->setPrivateProperty(exec->vm(), name, jsValue);
+ return true;
+ }
+#if JSC_OBJC_API_ENABLED
+ if (jsObject->inherits(JSCallbackObject<JSAPIWrapperObject>::info())) {
+ jsCast<JSCallbackObject<JSAPIWrapperObject>*>(jsObject)->setPrivateProperty(exec->vm(), name, jsValue);
+ return true;
+ }
+#endif
+ return false;
+}
+
+bool JSObjectDeletePrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName)
+{
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ JSObject* jsObject = toJS(object);
+ Identifier name(propertyName->identifier(&exec->vm()));
+
+ // Get wrapped object if proxied
+ if (jsObject->inherits(JSProxy::info()))
+ jsObject = jsCast<JSProxy*>(jsObject)->target();
+
+ if (jsObject->inherits(JSCallbackObject<JSGlobalObject>::info())) {
+ jsCast<JSCallbackObject<JSGlobalObject>*>(jsObject)->deletePrivateProperty(name);
+ return true;
+ }
+ if (jsObject->inherits(JSCallbackObject<JSDestructibleObject>::info())) {
+ jsCast<JSCallbackObject<JSDestructibleObject>*>(jsObject)->deletePrivateProperty(name);
+ return true;
+ }
+#if JSC_OBJC_API_ENABLED
+ if (jsObject->inherits(JSCallbackObject<JSAPIWrapperObject>::info())) {
+ jsCast<JSCallbackObject<JSAPIWrapperObject>*>(jsObject)->deletePrivateProperty(name);
+ return true;
+ }
+#endif
+ return false;
+}
+
+bool JSObjectIsFunction(JSContextRef ctx, JSObjectRef object)
+{
+ if (!object)
+ return false;
+ JSLockHolder locker(toJS(ctx));
+ CallData callData;
+ JSCell* cell = toJS(object);
+ return cell->methodTable()->getCallData(cell, callData) != CallTypeNone;
+}
+
+JSValueRef JSObjectCallAsFunction(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ if (!object)
+ return 0;
+
+ JSObject* jsObject = toJS(object);
+ JSObject* jsThisObject = toJS(thisObject);
+
+ if (!jsThisObject)
+ jsThisObject = exec->globalThisValue();
+
+ MarkedArgumentBuffer argList;
+ for (size_t i = 0; i < argumentCount; i++)
+ argList.append(toJS(exec, arguments[i]));
+
+ CallData callData;
+ CallType callType = jsObject->methodTable()->getCallData(jsObject, callData);
+ if (callType == CallTypeNone)
+ return 0;
+
+ JSValueRef result = toRef(exec, call(exec, jsObject, callType, callData, jsThisObject, argList));
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ result = 0;
+ return result;
+}
+
+bool JSObjectIsConstructor(JSContextRef, JSObjectRef object)
+{
+ if (!object)
+ return false;
+ JSObject* jsObject = toJS(object);
+ ConstructData constructData;
+ return jsObject->methodTable()->getConstructData(jsObject, constructData) != ConstructTypeNone;
+}
+
+JSObjectRef JSObjectCallAsConstructor(JSContextRef ctx, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ if (!object)
+ return 0;
+
+ JSObject* jsObject = toJS(object);
+
+ ConstructData constructData;
+ ConstructType constructType = jsObject->methodTable()->getConstructData(jsObject, constructData);
+ if (constructType == ConstructTypeNone)
+ return 0;
+
+ MarkedArgumentBuffer argList;
+ for (size_t i = 0; i < argumentCount; i++)
+ argList.append(toJS(exec, arguments[i]));
+ JSObjectRef result = toRef(construct(exec, jsObject, constructType, constructData, argList));
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ result = 0;
+ return result;
+}
+
+struct OpaqueJSPropertyNameArray {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ OpaqueJSPropertyNameArray(VM* vm)
+ : refCount(0)
+ , vm(vm)
+ {
+ }
+
+ unsigned refCount;
+ VM* vm;
+ Vector<JSRetainPtr<JSStringRef>> array;
+};
+
+JSPropertyNameArrayRef JSObjectCopyPropertyNames(JSContextRef ctx, JSObjectRef object)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ VM* vm = &exec->vm();
+
+ JSObject* jsObject = toJS(object);
+ JSPropertyNameArrayRef propertyNames = new OpaqueJSPropertyNameArray(vm);
+ PropertyNameArray array(vm, PropertyNameMode::Strings);
+ jsObject->methodTable()->getPropertyNames(jsObject, exec, array, EnumerationMode());
+
+ size_t size = array.size();
+ propertyNames->array.reserveInitialCapacity(size);
+ for (size_t i = 0; i < size; ++i)
+ propertyNames->array.uncheckedAppend(JSRetainPtr<JSStringRef>(Adopt, OpaqueJSString::create(array[i].string()).leakRef()));
+
+ return JSPropertyNameArrayRetain(propertyNames);
+}
+
+JSPropertyNameArrayRef JSPropertyNameArrayRetain(JSPropertyNameArrayRef array)
+{
+ ++array->refCount;
+ return array;
+}
+
+void JSPropertyNameArrayRelease(JSPropertyNameArrayRef array)
+{
+ if (--array->refCount == 0) {
+ JSLockHolder locker(array->vm);
+ delete array;
+ }
+}
+
+size_t JSPropertyNameArrayGetCount(JSPropertyNameArrayRef array)
+{
+ return array->array.size();
+}
+
+JSStringRef JSPropertyNameArrayGetNameAtIndex(JSPropertyNameArrayRef array, size_t index)
+{
+ return array->array[static_cast<unsigned>(index)].get();
+}
+
+void JSPropertyNameAccumulatorAddName(JSPropertyNameAccumulatorRef array, JSStringRef propertyName)
+{
+ PropertyNameArray* propertyNames = toJS(array);
+ JSLockHolder locker(propertyNames->vm());
+ propertyNames->add(propertyName->identifier(propertyNames->vm()));
+}
diff --git a/Source/JavaScriptCore/API/JSObjectRef.h b/Source/JavaScriptCore/API/JSObjectRef.h
new file mode 100644
index 000000000..754dff363
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSObjectRef.h
@@ -0,0 +1,694 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Kelvin W Sherlock (ksherlock@gmail.com)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSObjectRef_h
+#define JSObjectRef_h
+
+#include <JavaScriptCore/JSBase.h>
+#include <JavaScriptCore/JSValueRef.h>
+#include <JavaScriptCore/WebKitAvailability.h>
+
+#ifndef __cplusplus
+#include <stdbool.h>
+#endif
+#include <stddef.h> /* for size_t */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+@enum JSPropertyAttribute
+@constant kJSPropertyAttributeNone Specifies that a property has no special attributes.
+@constant kJSPropertyAttributeReadOnly Specifies that a property is read-only.
+@constant kJSPropertyAttributeDontEnum Specifies that a property should not be enumerated by JSPropertyEnumerators and JavaScript for...in loops.
+@constant kJSPropertyAttributeDontDelete Specifies that the delete operation should fail on a property.
+*/
+enum {
+ kJSPropertyAttributeNone = 0,
+ kJSPropertyAttributeReadOnly = 1 << 1,
+ kJSPropertyAttributeDontEnum = 1 << 2,
+ kJSPropertyAttributeDontDelete = 1 << 3
+};
+
+/*!
+@typedef JSPropertyAttributes
+@abstract A set of JSPropertyAttributes. Combine multiple attributes by logically ORing them together.
+*/
+typedef unsigned JSPropertyAttributes;
+
+/*!
+@enum JSClassAttribute
+@constant kJSClassAttributeNone Specifies that a class has no special attributes.
+@constant kJSClassAttributeNoAutomaticPrototype Specifies that a class should not automatically generate a shared prototype for its instance objects. Use kJSClassAttributeNoAutomaticPrototype in combination with JSObjectSetPrototype to manage prototypes manually.
+*/
+enum {
+ kJSClassAttributeNone = 0,
+ kJSClassAttributeNoAutomaticPrototype = 1 << 1
+};
+
+/*!
+@typedef JSClassAttributes
+@abstract A set of JSClassAttributes. Combine multiple attributes by logically ORing them together.
+*/
+typedef unsigned JSClassAttributes;
+
+/*!
+@typedef JSObjectInitializeCallback
+@abstract The callback invoked when an object is first created.
+@param ctx The execution context to use.
+@param object The JSObject being created.
+@discussion If you named your function Initialize, you would declare it like this:
+
+void Initialize(JSContextRef ctx, JSObjectRef object);
+
+Unlike the other object callbacks, the initialize callback is called on the least
+derived class (the parent class) first, and the most derived class last.
+*/
+typedef void
+(*JSObjectInitializeCallback) (JSContextRef ctx, JSObjectRef object);
+
+/*!
+@typedef JSObjectFinalizeCallback
+@abstract The callback invoked when an object is finalized (prepared for garbage collection). An object may be finalized on any thread.
+@param object The JSObject being finalized.
+@discussion If you named your function Finalize, you would declare it like this:
+
+void Finalize(JSObjectRef object);
+
+The finalize callback is called on the most derived class first, and the least
+derived class (the parent class) last.
+
+You must not call any function that may cause a garbage collection or an allocation
+of a garbage collected object from within a JSObjectFinalizeCallback. This includes
+all functions that have a JSContextRef parameter.
+*/
+typedef void
+(*JSObjectFinalizeCallback) (JSObjectRef object);
+
+/*!
+@typedef JSObjectHasPropertyCallback
+@abstract The callback invoked when determining whether an object has a property.
+@param ctx The execution context to use.
+@param object The JSObject to search for the property.
+@param propertyName A JSString containing the name of the property look up.
+@result true if object has the property, otherwise false.
+@discussion If you named your function HasProperty, you would declare it like this:
+
+bool HasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
+
+If this function returns false, the hasProperty request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain.
+
+This callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value would be expensive.
+
+If this callback is NULL, the getProperty callback will be used to service hasProperty requests.
+*/
+typedef bool
+(*JSObjectHasPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
+
+/*!
+@typedef JSObjectGetPropertyCallback
+@abstract The callback invoked when getting a property's value.
+@param ctx The execution context to use.
+@param object The JSObject to search for the property.
+@param propertyName A JSString containing the name of the property to get.
+@param exception A pointer to a JSValueRef in which to return an exception, if any.
+@result The property's value if object has the property, otherwise NULL.
+@discussion If you named your function GetProperty, you would declare it like this:
+
+JSValueRef GetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
+
+If this function returns NULL, the get request forwards to object's statically declared properties, then its parent class chain (which includes the default object class), then its prototype chain.
+*/
+typedef JSValueRef
+(*JSObjectGetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
+
+/*!
+@typedef JSObjectSetPropertyCallback
+@abstract The callback invoked when setting a property's value.
+@param ctx The execution context to use.
+@param object The JSObject on which to set the property's value.
+@param propertyName A JSString containing the name of the property to set.
+@param value A JSValue to use as the property's value.
+@param exception A pointer to a JSValueRef in which to return an exception, if any.
+@result true if the property was set, otherwise false.
+@discussion If you named your function SetProperty, you would declare it like this:
+
+bool SetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
+
+If this function returns false, the set request forwards to object's statically declared properties, then its parent class chain (which includes the default object class).
+*/
+typedef bool
+(*JSObjectSetPropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception);
+
+/*!
+@typedef JSObjectDeletePropertyCallback
+@abstract The callback invoked when deleting a property.
+@param ctx The execution context to use.
+@param object The JSObject in which to delete the property.
+@param propertyName A JSString containing the name of the property to delete.
+@param exception A pointer to a JSValueRef in which to return an exception, if any.
+@result true if propertyName was successfully deleted, otherwise false.
+@discussion If you named your function DeleteProperty, you would declare it like this:
+
+bool DeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
+
+If this function returns false, the delete request forwards to object's statically declared properties, then its parent class chain (which includes the default object class).
+*/
+typedef bool
+(*JSObjectDeletePropertyCallback) (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
+
+/*!
+@typedef JSObjectGetPropertyNamesCallback
+@abstract The callback invoked when collecting the names of an object's properties.
+@param ctx The execution context to use.
+@param object The JSObject whose property names are being collected.
+@param accumulator A JavaScript property name accumulator in which to accumulate the names of object's properties.
+@discussion If you named your function GetPropertyNames, you would declare it like this:
+
+void GetPropertyNames(JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
+
+Property name accumulators are used by JSObjectCopyPropertyNames and JavaScript for...in loops.
+
+Use JSPropertyNameAccumulatorAddName to add property names to accumulator. A class's getPropertyNames callback only needs to provide the names of properties that the class vends through a custom getProperty or setProperty callback. Other properties, including statically declared properties, properties vended by other classes, and properties belonging to object's prototype, are added independently.
+*/
+typedef void
+(*JSObjectGetPropertyNamesCallback) (JSContextRef ctx, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames);
+
+/*!
+@typedef JSObjectCallAsFunctionCallback
+@abstract The callback invoked when an object is called as a function.
+@param ctx The execution context to use.
+@param function A JSObject that is the function being called.
+@param thisObject A JSObject that is the 'this' variable in the function's scope.
+@param argumentCount An integer count of the number of arguments in arguments.
+@param arguments A JSValue array of the arguments passed to the function.
+@param exception A pointer to a JSValueRef in which to return an exception, if any.
+@result A JSValue that is the function's return value.
+@discussion If you named your function CallAsFunction, you would declare it like this:
+
+JSValueRef CallAsFunction(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
+
+If your callback were invoked by the JavaScript expression 'myObject.myFunction()', function would be set to myFunction, and thisObject would be set to myObject.
+
+If this callback is NULL, calling your object as a function will throw an exception.
+*/
+typedef JSValueRef
+(*JSObjectCallAsFunctionCallback) (JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
+
+/*!
+@typedef JSObjectCallAsConstructorCallback
+@abstract The callback invoked when an object is used as a constructor in a 'new' expression.
+@param ctx The execution context to use.
+@param constructor A JSObject that is the constructor being called.
+@param argumentCount An integer count of the number of arguments in arguments.
+@param arguments A JSValue array of the arguments passed to the function.
+@param exception A pointer to a JSValueRef in which to return an exception, if any.
+@result A JSObject that is the constructor's return value.
+@discussion If you named your function CallAsConstructor, you would declare it like this:
+
+JSObjectRef CallAsConstructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
+
+If your callback were invoked by the JavaScript expression 'new myConstructor()', constructor would be set to myConstructor.
+
+If this callback is NULL, using your object as a constructor in a 'new' expression will throw an exception.
+*/
+typedef JSObjectRef
+(*JSObjectCallAsConstructorCallback) (JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
+
+/*!
+@typedef JSObjectHasInstanceCallback
+@abstract hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression.
+@param ctx The execution context to use.
+@param constructor The JSObject that is the target of the 'instanceof' expression.
+@param possibleInstance The JSValue being tested to determine if it is an instance of constructor.
+@param exception A pointer to a JSValueRef in which to return an exception, if any.
+@result true if possibleInstance is an instance of constructor, otherwise false.
+@discussion If you named your function HasInstance, you would declare it like this:
+
+bool HasInstance(JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
+
+If your callback were invoked by the JavaScript expression 'someValue instanceof myObject', constructor would be set to myObject and possibleInstance would be set to someValue.
+
+If this callback is NULL, 'instanceof' expressions that target your object will return false.
+
+Standard JavaScript practice calls for objects that implement the callAsConstructor callback to implement the hasInstance callback as well.
+*/
+typedef bool
+(*JSObjectHasInstanceCallback) (JSContextRef ctx, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception);
+
+/*!
+@typedef JSObjectConvertToTypeCallback
+@abstract The callback invoked when converting an object to a particular JavaScript type.
+@param ctx The execution context to use.
+@param object The JSObject to convert.
+@param type A JSType specifying the JavaScript type to convert to.
+@param exception A pointer to a JSValueRef in which to return an exception, if any.
+@result The objects's converted value, or NULL if the object was not converted.
+@discussion If you named your function ConvertToType, you would declare it like this:
+
+JSValueRef ConvertToType(JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception);
+
+If this function returns false, the conversion request forwards to object's parent class chain (which includes the default object class).
+
+This function is only invoked when converting an object to number or string. An object converted to boolean is 'true.' An object converted to object is itself.
+*/
+typedef JSValueRef
+(*JSObjectConvertToTypeCallback) (JSContextRef ctx, JSObjectRef object, JSType type, JSValueRef* exception);
+
+/*!
+@struct JSStaticValue
+@abstract This structure describes a statically declared value property.
+@field name A null-terminated UTF8 string containing the property's name.
+@field getProperty A JSObjectGetPropertyCallback to invoke when getting the property's value.
+@field setProperty A JSObjectSetPropertyCallback to invoke when setting the property's value. May be NULL if the ReadOnly attribute is set.
+@field attributes A logically ORed set of JSPropertyAttributes to give to the property.
+*/
+typedef struct {
+ const char* name;
+ JSObjectGetPropertyCallback getProperty;
+ JSObjectSetPropertyCallback setProperty;
+ JSPropertyAttributes attributes;
+} JSStaticValue;
+
+/*!
+@struct JSStaticFunction
+@abstract This structure describes a statically declared function property.
+@field name A null-terminated UTF8 string containing the property's name.
+@field callAsFunction A JSObjectCallAsFunctionCallback to invoke when the property is called as a function.
+@field attributes A logically ORed set of JSPropertyAttributes to give to the property.
+*/
+typedef struct {
+ const char* name;
+ JSObjectCallAsFunctionCallback callAsFunction;
+ JSPropertyAttributes attributes;
+} JSStaticFunction;
+
+/*!
+@struct JSClassDefinition
+@abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL.
+@field version The version number of this structure. The current version is 0.
+@field attributes A logically ORed set of JSClassAttributes to give to the class.
+@field className A null-terminated UTF8 string containing the class's name.
+@field parentClass A JSClass to set as the class's parent class. Pass NULL use the default object class.
+@field staticValues A JSStaticValue array containing the class's statically declared value properties. Pass NULL to specify no statically declared value properties. The array must be terminated by a JSStaticValue whose name field is NULL.
+@field staticFunctions A JSStaticFunction array containing the class's statically declared function properties. Pass NULL to specify no statically declared function properties. The array must be terminated by a JSStaticFunction whose name field is NULL.
+@field initialize The callback invoked when an object is first created. Use this callback to initialize the object.
+@field finalize The callback invoked when an object is finalized (prepared for garbage collection). Use this callback to release resources allocated for the object, and perform other cleanup.
+@field hasProperty The callback invoked when determining whether an object has a property. If this field is NULL, getProperty is called instead. The hasProperty callback enables optimization in cases where only a property's existence needs to be known, not its value, and computing its value is expensive.
+@field getProperty The callback invoked when getting a property's value.
+@field setProperty The callback invoked when setting a property's value.
+@field deleteProperty The callback invoked when deleting a property.
+@field getPropertyNames The callback invoked when collecting the names of an object's properties.
+@field callAsFunction The callback invoked when an object is called as a function.
+@field hasInstance The callback invoked when an object is used as the target of an 'instanceof' expression.
+@field callAsConstructor The callback invoked when an object is used as a constructor in a 'new' expression.
+@field convertToType The callback invoked when converting an object to a particular JavaScript type.
+@discussion The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties. Statically declared properties autmatically service requests like getProperty, setProperty, and getPropertyNames. Property access callbacks are required only to implement unusual properties, like array indexes, whose names are not known at compile-time.
+
+If you named your getter function "GetX" and your setter function "SetX", you would declare a JSStaticValue array containing "X" like this:
+
+JSStaticValue StaticValueArray[] = {
+ { "X", GetX, SetX, kJSPropertyAttributeNone },
+ { 0, 0, 0, 0 }
+};
+
+Standard JavaScript practice calls for storing function objects in prototypes, so they can be shared. The default JSClass created by JSClassCreate follows this idiom, instantiating objects with a shared, automatically generating prototype containing the class's function objects. The kJSClassAttributeNoAutomaticPrototype attribute specifies that a JSClass should not automatically generate such a prototype. The resulting JSClass instantiates objects with the default object prototype, and gives each instance object its own copy of the class's function objects.
+
+A NULL callback specifies that the default object callback should substitute, except in the case of hasProperty, where it specifies that getProperty should substitute.
+*/
+typedef struct {
+ int version; /* current (and only) version is 0 */
+ JSClassAttributes attributes;
+
+ const char* className;
+ JSClassRef parentClass;
+
+ const JSStaticValue* staticValues;
+ const JSStaticFunction* staticFunctions;
+
+ JSObjectInitializeCallback initialize;
+ JSObjectFinalizeCallback finalize;
+ JSObjectHasPropertyCallback hasProperty;
+ JSObjectGetPropertyCallback getProperty;
+ JSObjectSetPropertyCallback setProperty;
+ JSObjectDeletePropertyCallback deleteProperty;
+ JSObjectGetPropertyNamesCallback getPropertyNames;
+ JSObjectCallAsFunctionCallback callAsFunction;
+ JSObjectCallAsConstructorCallback callAsConstructor;
+ JSObjectHasInstanceCallback hasInstance;
+ JSObjectConvertToTypeCallback convertToType;
+} JSClassDefinition;
+
+/*!
+@const kJSClassDefinitionEmpty
+@abstract A JSClassDefinition structure of the current version, filled with NULL pointers and having no attributes.
+@discussion Use this constant as a convenience when creating class definitions. For example, to create a class definition with only a finalize method:
+
+JSClassDefinition definition = kJSClassDefinitionEmpty;
+definition.finalize = Finalize;
+*/
+JS_EXPORT extern const JSClassDefinition kJSClassDefinitionEmpty;
+
+/*!
+@function
+@abstract Creates a JavaScript class suitable for use with JSObjectMake.
+@param definition A JSClassDefinition that defines the class.
+@result A JSClass with the given definition. Ownership follows the Create Rule.
+*/
+JS_EXPORT JSClassRef JSClassCreate(const JSClassDefinition* definition);
+
+/*!
+@function
+@abstract Retains a JavaScript class.
+@param jsClass The JSClass to retain.
+@result A JSClass that is the same as jsClass.
+*/
+JS_EXPORT JSClassRef JSClassRetain(JSClassRef jsClass);
+
+/*!
+@function
+@abstract Releases a JavaScript class.
+@param jsClass The JSClass to release.
+*/
+JS_EXPORT void JSClassRelease(JSClassRef jsClass);
+
+/*!
+@function
+@abstract Creates a JavaScript object.
+@param ctx The execution context to use.
+@param jsClass The JSClass to assign to the object. Pass NULL to use the default object class.
+@param data A void* to set as the object's private data. Pass NULL to specify no private data.
+@result A JSObject with the given class and private data.
+@discussion The default object class does not allocate storage for private data, so you must provide a non-NULL jsClass to JSObjectMake if you want your object to be able to store private data.
+
+data is set on the created object before the intialize methods in its class chain are called. This enables the initialize methods to retrieve and manipulate data through JSObjectGetPrivate.
+*/
+JS_EXPORT JSObjectRef JSObjectMake(JSContextRef ctx, JSClassRef jsClass, void* data);
+
+/*!
+@function
+@abstract Convenience method for creating a JavaScript function with a given callback as its implementation.
+@param ctx The execution context to use.
+@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function.
+@param callAsFunction The JSObjectCallAsFunctionCallback to invoke when the function is called.
+@result A JSObject that is a function. The object's prototype will be the default function prototype.
+*/
+JS_EXPORT JSObjectRef JSObjectMakeFunctionWithCallback(JSContextRef ctx, JSStringRef name, JSObjectCallAsFunctionCallback callAsFunction);
+
+/*!
+@function
+@abstract Convenience method for creating a JavaScript constructor.
+@param ctx The execution context to use.
+@param jsClass A JSClass that is the class your constructor will assign to the objects its constructs. jsClass will be used to set the constructor's .prototype property, and to evaluate 'instanceof' expressions. Pass NULL to use the default object class.
+@param callAsConstructor A JSObjectCallAsConstructorCallback to invoke when your constructor is used in a 'new' expression. Pass NULL to use the default object constructor.
+@result A JSObject that is a constructor. The object's prototype will be the default object prototype.
+@discussion The default object constructor takes no arguments and constructs an object of class jsClass with no private data.
+*/
+JS_EXPORT JSObjectRef JSObjectMakeConstructor(JSContextRef ctx, JSClassRef jsClass, JSObjectCallAsConstructorCallback callAsConstructor);
+
+/*!
+ @function
+ @abstract Creates a JavaScript Array object.
+ @param ctx The execution context to use.
+ @param argumentCount An integer count of the number of arguments in arguments.
+ @param arguments A JSValue array of data to populate the Array with. Pass NULL if argumentCount is 0.
+ @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+ @result A JSObject that is an Array.
+ @discussion The behavior of this function does not exactly match the behavior of the built-in Array constructor. Specifically, if one argument
+ is supplied, this function returns an array with one element.
+ */
+JS_EXPORT JSObjectRef JSObjectMakeArray(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+ @function
+ @abstract Creates a JavaScript Date object, as if by invoking the built-in Date constructor.
+ @param ctx The execution context to use.
+ @param argumentCount An integer count of the number of arguments in arguments.
+ @param arguments A JSValue array of arguments to pass to the Date Constructor. Pass NULL if argumentCount is 0.
+ @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+ @result A JSObject that is a Date.
+ */
+JS_EXPORT JSObjectRef JSObjectMakeDate(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+ @function
+ @abstract Creates a JavaScript Error object, as if by invoking the built-in Error constructor.
+ @param ctx The execution context to use.
+ @param argumentCount An integer count of the number of arguments in arguments.
+ @param arguments A JSValue array of arguments to pass to the Error Constructor. Pass NULL if argumentCount is 0.
+ @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+ @result A JSObject that is a Error.
+ */
+JS_EXPORT JSObjectRef JSObjectMakeError(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+ @function
+ @abstract Creates a JavaScript RegExp object, as if by invoking the built-in RegExp constructor.
+ @param ctx The execution context to use.
+ @param argumentCount An integer count of the number of arguments in arguments.
+ @param arguments A JSValue array of arguments to pass to the RegExp Constructor. Pass NULL if argumentCount is 0.
+ @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+ @result A JSObject that is a RegExp.
+ */
+JS_EXPORT JSObjectRef JSObjectMakeRegExp(JSContextRef ctx, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) CF_AVAILABLE(10_6, 7_0);
+
+/*!
+@function
+@abstract Creates a function with a given script as its body.
+@param ctx The execution context to use.
+@param name A JSString containing the function's name. This will be used when converting the function to string. Pass NULL to create an anonymous function.
+@param parameterCount An integer count of the number of parameter names in parameterNames.
+@param parameterNames A JSString array containing the names of the function's parameters. Pass NULL if parameterCount is 0.
+@param body A JSString containing the script to use as the function's body.
+@param sourceURL A JSString containing a URL for the script's source file. This is only used when reporting exceptions. Pass NULL if you do not care to include source file information in exceptions.
+@param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
+@param exception A pointer to a JSValueRef in which to store a syntax error exception, if any. Pass NULL if you do not care to store a syntax error exception.
+@result A JSObject that is a function, or NULL if either body or parameterNames contains a syntax error. The object's prototype will be the default function prototype.
+@discussion Use this method when you want to execute a script repeatedly, to avoid the cost of re-parsing the script before each execution.
+*/
+JS_EXPORT JSObjectRef JSObjectMakeFunction(JSContextRef ctx, JSStringRef name, unsigned parameterCount, const JSStringRef parameterNames[], JSStringRef body, JSStringRef sourceURL, int startingLineNumber, JSValueRef* exception);
+
+/*!
+@function
+@abstract Gets an object's prototype.
+@param ctx The execution context to use.
+@param object A JSObject whose prototype you want to get.
+@result A JSValue that is the object's prototype.
+*/
+JS_EXPORT JSValueRef JSObjectGetPrototype(JSContextRef ctx, JSObjectRef object);
+
+/*!
+@function
+@abstract Sets an object's prototype.
+@param ctx The execution context to use.
+@param object The JSObject whose prototype you want to set.
+@param value A JSValue to set as the object's prototype.
+*/
+JS_EXPORT void JSObjectSetPrototype(JSContextRef ctx, JSObjectRef object, JSValueRef value);
+
+/*!
+@function
+@abstract Tests whether an object has a given property.
+@param object The JSObject to test.
+@param propertyName A JSString containing the property's name.
+@result true if the object has a property whose name matches propertyName, otherwise false.
+*/
+JS_EXPORT bool JSObjectHasProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
+
+/*!
+@function
+@abstract Gets a property from an object.
+@param ctx The execution context to use.
+@param object The JSObject whose property you want to get.
+@param propertyName A JSString containing the property's name.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result The property's value if object has the property, otherwise the undefined value.
+*/
+JS_EXPORT JSValueRef JSObjectGetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
+
+/*!
+@function
+@abstract Sets a property on an object.
+@param ctx The execution context to use.
+@param object The JSObject whose property you want to set.
+@param propertyName A JSString containing the property's name.
+@param value A JSValue to use as the property's value.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@param attributes A logically ORed set of JSPropertyAttributes to give to the property.
+*/
+JS_EXPORT void JSObjectSetProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSPropertyAttributes attributes, JSValueRef* exception);
+
+/*!
+@function
+@abstract Deletes a property from an object.
+@param ctx The execution context to use.
+@param object The JSObject whose property you want to delete.
+@param propertyName A JSString containing the property's name.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result true if the delete operation succeeds, otherwise false (for example, if the property has the kJSPropertyAttributeDontDelete attribute set).
+*/
+JS_EXPORT bool JSObjectDeleteProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception);
+
+/*!
+@function
+@abstract Gets a property from an object by numeric index.
+@param ctx The execution context to use.
+@param object The JSObject whose property you want to get.
+@param propertyIndex An integer value that is the property's name.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result The property's value if object has the property, otherwise the undefined value.
+@discussion Calling JSObjectGetPropertyAtIndex is equivalent to calling JSObjectGetProperty with a string containing propertyIndex, but JSObjectGetPropertyAtIndex provides optimized access to numeric properties.
+*/
+JS_EXPORT JSValueRef JSObjectGetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef* exception);
+
+/*!
+@function
+@abstract Sets a property on an object by numeric index.
+@param ctx The execution context to use.
+@param object The JSObject whose property you want to set.
+@param propertyIndex The property's name as a number.
+@param value A JSValue to use as the property's value.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@discussion Calling JSObjectSetPropertyAtIndex is equivalent to calling JSObjectSetProperty with a string containing propertyIndex, but JSObjectSetPropertyAtIndex provides optimized access to numeric properties.
+*/
+JS_EXPORT void JSObjectSetPropertyAtIndex(JSContextRef ctx, JSObjectRef object, unsigned propertyIndex, JSValueRef value, JSValueRef* exception);
+
+/*!
+@function
+@abstract Gets an object's private data.
+@param object A JSObject whose private data you want to get.
+@result A void* that is the object's private data, if the object has private data, otherwise NULL.
+*/
+JS_EXPORT void* JSObjectGetPrivate(JSObjectRef object);
+
+/*!
+@function
+@abstract Sets a pointer to private data on an object.
+@param object The JSObject whose private data you want to set.
+@param data A void* to set as the object's private data.
+@result true if object can store private data, otherwise false.
+@discussion The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private data.
+*/
+JS_EXPORT bool JSObjectSetPrivate(JSObjectRef object, void* data);
+
+/*!
+@function
+@abstract Tests whether an object can be called as a function.
+@param ctx The execution context to use.
+@param object The JSObject to test.
+@result true if the object can be called as a function, otherwise false.
+*/
+JS_EXPORT bool JSObjectIsFunction(JSContextRef ctx, JSObjectRef object);
+
+/*!
+@function
+@abstract Calls an object as a function.
+@param ctx The execution context to use.
+@param object The JSObject to call as a function.
+@param thisObject The object to use as "this," or NULL to use the global object as "this."
+@param argumentCount An integer count of the number of arguments in arguments.
+@param arguments A JSValue array of arguments to pass to the function. Pass NULL if argumentCount is 0.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result The JSValue that results from calling object as a function, or NULL if an exception is thrown or object is not a function.
+*/
+JS_EXPORT JSValueRef JSObjectCallAsFunction(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
+
+/*!
+@function
+@abstract Tests whether an object can be called as a constructor.
+@param ctx The execution context to use.
+@param object The JSObject to test.
+@result true if the object can be called as a constructor, otherwise false.
+*/
+JS_EXPORT bool JSObjectIsConstructor(JSContextRef ctx, JSObjectRef object);
+
+/*!
+@function
+@abstract Calls an object as a constructor.
+@param ctx The execution context to use.
+@param object The JSObject to call as a constructor.
+@param argumentCount An integer count of the number of arguments in arguments.
+@param arguments A JSValue array of arguments to pass to the constructor. Pass NULL if argumentCount is 0.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result The JSObject that results from calling object as a constructor, or NULL if an exception is thrown or object is not a constructor.
+*/
+JS_EXPORT JSObjectRef JSObjectCallAsConstructor(JSContextRef ctx, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
+
+/*!
+@function
+@abstract Gets the names of an object's enumerable properties.
+@param ctx The execution context to use.
+@param object The object whose property names you want to get.
+@result A JSPropertyNameArray containing the names object's enumerable properties. Ownership follows the Create Rule.
+*/
+JS_EXPORT JSPropertyNameArrayRef JSObjectCopyPropertyNames(JSContextRef ctx, JSObjectRef object);
+
+/*!
+@function
+@abstract Retains a JavaScript property name array.
+@param array The JSPropertyNameArray to retain.
+@result A JSPropertyNameArray that is the same as array.
+*/
+JS_EXPORT JSPropertyNameArrayRef JSPropertyNameArrayRetain(JSPropertyNameArrayRef array);
+
+/*!
+@function
+@abstract Releases a JavaScript property name array.
+@param array The JSPropetyNameArray to release.
+*/
+JS_EXPORT void JSPropertyNameArrayRelease(JSPropertyNameArrayRef array);
+
+/*!
+@function
+@abstract Gets a count of the number of items in a JavaScript property name array.
+@param array The array from which to retrieve the count.
+@result An integer count of the number of names in array.
+*/
+JS_EXPORT size_t JSPropertyNameArrayGetCount(JSPropertyNameArrayRef array);
+
+/*!
+@function
+@abstract Gets a property name at a given index in a JavaScript property name array.
+@param array The array from which to retrieve the property name.
+@param index The index of the property name to retrieve.
+@result A JSStringRef containing the property name.
+*/
+JS_EXPORT JSStringRef JSPropertyNameArrayGetNameAtIndex(JSPropertyNameArrayRef array, size_t index);
+
+/*!
+@function
+@abstract Adds a property name to a JavaScript property name accumulator.
+@param accumulator The accumulator object to which to add the property name.
+@param propertyName The property name to add.
+*/
+JS_EXPORT void JSPropertyNameAccumulatorAddName(JSPropertyNameAccumulatorRef accumulator, JSStringRef propertyName);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSObjectRef_h */
diff --git a/Source/JavaScriptCore/API/JSObjectRefPrivate.h b/Source/JavaScriptCore/API/JSObjectRefPrivate.h
new file mode 100644
index 000000000..32e80ab26
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSObjectRefPrivate.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSObjectRefPrivate_h
+#define JSObjectRefPrivate_h
+
+#include <JavaScriptCore/JSObjectRef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ @function
+ @abstract Sets a private property on an object. This private property cannot be accessed from within JavaScript.
+ @param ctx The execution context to use.
+ @param object The JSObject whose private property you want to set.
+ @param propertyName A JSString containing the property's name.
+ @param value A JSValue to use as the property's value. This may be NULL.
+ @result true if object can store private data, otherwise false.
+ @discussion This API allows you to store JS values directly an object in a way that will be ensure that they are kept alive without exposing them to JavaScript code and without introducing the reference cycles that may occur when using JSValueProtect.
+
+ The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private properties.
+ */
+JS_EXPORT bool JSObjectSetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value);
+
+/*!
+ @function
+ @abstract Gets a private property from an object.
+ @param ctx The execution context to use.
+ @param object The JSObject whose private property you want to get.
+ @param propertyName A JSString containing the property's name.
+ @result The property's value if object has the property, otherwise NULL.
+ */
+JS_EXPORT JSValueRef JSObjectGetPrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
+
+/*!
+ @function
+ @abstract Deletes a private property from an object.
+ @param ctx The execution context to use.
+ @param object The JSObject whose private property you want to delete.
+ @param propertyName A JSString containing the property's name.
+ @result true if object can store private data, otherwise false.
+ @discussion The default object class does not allocate storage for private data. Only objects created with a non-NULL JSClass can store private data.
+ */
+JS_EXPORT bool JSObjectDeletePrivateProperty(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // JSObjectRefPrivate_h
diff --git a/Source/JavaScriptCore/API/JSProfilerPrivate.cpp b/Source/JavaScriptCore/API/JSProfilerPrivate.cpp
new file mode 100644
index 000000000..ac112ae6e
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSProfilerPrivate.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSProfilerPrivate.h"
+
+#include "APICast.h"
+#include "LegacyProfiler.h"
+#include "OpaqueJSString.h"
+
+using namespace JSC;
+
+void JSStartProfiling(JSContextRef ctx, JSStringRef title)
+{
+ // Use an independent stopwatch for API-initiated profiling, since the user will expect it
+ // to be relative to when their command was issued.
+ RefPtr<Stopwatch> stopwatch = Stopwatch::create();
+ stopwatch->start();
+ LegacyProfiler::profiler()->startProfiling(toJS(ctx), title->string(), stopwatch.release());
+}
+
+void JSEndProfiling(JSContextRef ctx, JSStringRef title)
+{
+ ExecState* exec = toJS(ctx);
+ LegacyProfiler* profiler = LegacyProfiler::profiler();
+ profiler->stopProfiling(exec, title->string());
+}
+
diff --git a/Source/JavaScriptCore/API/JSProfilerPrivate.h b/Source/JavaScriptCore/API/JSProfilerPrivate.h
new file mode 100644
index 000000000..34f26a202
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSProfilerPrivate.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSProfiler_h
+#define JSProfiler_h
+
+#include <JavaScriptCore/JSBase.h>
+
+#ifndef __cplusplus
+#include <stdbool.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+@function JSStartProfiling
+@abstract Enables the profler.
+@param ctx The execution context to use.
+@param title The title of the profile.
+@result The profiler is turned on.
+*/
+JS_EXPORT void JSStartProfiling(JSContextRef ctx, JSStringRef title);
+
+/*!
+@function JSEndProfiling
+@abstract Disables the profler.
+@param ctx The execution context to use.
+@param title The title of the profile.
+@result The profiler is turned off. If there is no name, the most recently started
+ profile is stopped. If the name does not match any profile then no profile
+ is stopped.
+*/
+JS_EXPORT void JSEndProfiling(JSContextRef ctx, JSStringRef title);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSProfiler_h */
diff --git a/Source/JavaScriptCore/API/JSRemoteInspector.cpp b/Source/JavaScriptCore/API/JSRemoteInspector.cpp
new file mode 100644
index 000000000..faebc5de3
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSRemoteInspector.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSRemoteInspector.h"
+
+#include "JSGlobalObjectConsoleClient.h"
+
+#if ENABLE(REMOTE_INSPECTOR)
+#include "RemoteInspector.h"
+#endif
+
+using namespace Inspector;
+
+static bool remoteInspectionEnabledByDefault = true;
+
+void JSRemoteInspectorDisableAutoStart(void)
+{
+#if ENABLE(REMOTE_INSPECTOR)
+ RemoteInspector::startDisabled();
+#endif
+}
+
+void JSRemoteInspectorStart(void)
+{
+#if ENABLE(REMOTE_INSPECTOR)
+ RemoteInspector::singleton();
+#endif
+}
+
+void JSRemoteInspectorSetParentProcessInformation(pid_t pid, const UInt8* auditData, size_t auditLength)
+{
+#if ENABLE(REMOTE_INSPECTOR)
+ RetainPtr<CFDataRef> auditDataRef = adoptCF(CFDataCreate(kCFAllocatorDefault, auditData, auditLength));
+ RemoteInspector::singleton().setParentProcessInformation(pid, auditDataRef);
+#else
+ UNUSED_PARAM(pid);
+ UNUSED_PARAM(auditData);
+ UNUSED_PARAM(auditLength);
+#endif
+}
+
+void JSRemoteInspectorSetLogToSystemConsole(bool logToSystemConsole)
+{
+ JSGlobalObjectConsoleClient::setLogToSystemConsole(logToSystemConsole);
+}
+
+bool JSRemoteInspectorGetInspectionEnabledByDefault(void)
+{
+ return remoteInspectionEnabledByDefault;
+}
+
+void JSRemoteInspectorSetInspectionEnabledByDefault(bool enabledByDefault)
+{
+ remoteInspectionEnabledByDefault = enabledByDefault;
+}
diff --git a/Source/JavaScriptCore/API/JSRemoteInspector.h b/Source/JavaScriptCore/API/JSRemoteInspector.h
new file mode 100644
index 000000000..2bde47949
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSRemoteInspector.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSRemoteInspector_h
+#define JSRemoteInspector_h
+
+#include <JavaScriptCore/JSBase.h>
+#include <JavaScriptCore/WebKitAvailability.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JS_EXPORT void JSRemoteInspectorDisableAutoStart(void) CF_AVAILABLE(10_11, 9_0);
+JS_EXPORT void JSRemoteInspectorStart(void) CF_AVAILABLE(10_11, 9_0);
+JS_EXPORT void JSRemoteInspectorSetParentProcessInformation(pid_t, const uint8_t* auditData, size_t auditLength) CF_AVAILABLE(10_11, 9_0);
+
+JS_EXPORT void JSRemoteInspectorSetLogToSystemConsole(bool) CF_AVAILABLE(10_11, 9_0);
+
+JS_EXPORT bool JSRemoteInspectorGetInspectionEnabledByDefault(void) CF_AVAILABLE(10_11, 9_0);
+JS_EXPORT void JSRemoteInspectorSetInspectionEnabledByDefault(bool) CF_AVAILABLE(10_11, 9_0);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSRemoteInspector_h */
diff --git a/Source/JavaScriptCore/API/JSRetainPtr.h b/Source/JavaScriptCore/API/JSRetainPtr.h
new file mode 100644
index 000000000..e40084080
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSRetainPtr.h
@@ -0,0 +1,215 @@
+/*
+ * Copyright (C) 2005, 2006, 2007, 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSRetainPtr_h
+#define JSRetainPtr_h
+
+#include <JavaScriptCore/JSContextRef.h>
+#include <JavaScriptCore/JSStringRef.h>
+#include <algorithm>
+
+inline void JSRetain(JSStringRef string) { JSStringRetain(string); }
+inline void JSRelease(JSStringRef string) { JSStringRelease(string); }
+inline void JSRetain(JSGlobalContextRef context) { JSGlobalContextRetain(context); }
+inline void JSRelease(JSGlobalContextRef context) { JSGlobalContextRelease(context); }
+
+enum AdoptTag { Adopt };
+
+template<typename T> class JSRetainPtr {
+public:
+ JSRetainPtr() : m_ptr(0) { }
+ JSRetainPtr(T ptr) : m_ptr(ptr) { if (ptr) JSRetain(ptr); }
+ JSRetainPtr(AdoptTag, T ptr) : m_ptr(ptr) { }
+ JSRetainPtr(const JSRetainPtr&);
+ template<typename U> JSRetainPtr(const JSRetainPtr<U>&);
+ ~JSRetainPtr();
+
+ T get() const { return m_ptr; }
+
+ void clear();
+ T leakRef();
+
+ T operator->() const { return m_ptr; }
+
+ bool operator!() const { return !m_ptr; }
+ explicit operator bool() const { return m_ptr; }
+
+ JSRetainPtr& operator=(const JSRetainPtr&);
+ template<typename U> JSRetainPtr& operator=(const JSRetainPtr<U>&);
+ JSRetainPtr& operator=(T);
+ template<typename U> JSRetainPtr& operator=(U*);
+
+ void adopt(T);
+
+ void swap(JSRetainPtr&);
+
+private:
+ T m_ptr;
+};
+
+inline JSRetainPtr<JSStringRef> adopt(JSStringRef o)
+{
+ return JSRetainPtr<JSStringRef>(Adopt, o);
+}
+
+inline JSRetainPtr<JSGlobalContextRef> adopt(JSGlobalContextRef o)
+{
+ return JSRetainPtr<JSGlobalContextRef>(Adopt, o);
+}
+
+template<typename T> inline JSRetainPtr<T>::JSRetainPtr(const JSRetainPtr& o)
+ : m_ptr(o.m_ptr)
+{
+ if (m_ptr)
+ JSRetain(m_ptr);
+}
+
+template<typename T> template<typename U> inline JSRetainPtr<T>::JSRetainPtr(const JSRetainPtr<U>& o)
+ : m_ptr(o.get())
+{
+ if (m_ptr)
+ JSRetain(m_ptr);
+}
+
+template<typename T> inline JSRetainPtr<T>::~JSRetainPtr()
+{
+ if (m_ptr)
+ JSRelease(m_ptr);
+}
+
+template<typename T> inline void JSRetainPtr<T>::clear()
+{
+ if (T ptr = m_ptr) {
+ m_ptr = 0;
+ JSRelease(ptr);
+ }
+}
+
+template<typename T> inline T JSRetainPtr<T>::leakRef()
+{
+ T ptr = m_ptr;
+ m_ptr = 0;
+ return ptr;
+}
+
+template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(const JSRetainPtr<T>& o)
+{
+ T optr = o.get();
+ if (optr)
+ JSRetain(optr);
+ T ptr = m_ptr;
+ m_ptr = optr;
+ if (ptr)
+ JSRelease(ptr);
+ return *this;
+}
+
+template<typename T> template<typename U> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(const JSRetainPtr<U>& o)
+{
+ T optr = o.get();
+ if (optr)
+ JSRetain(optr);
+ T ptr = m_ptr;
+ m_ptr = optr;
+ if (ptr)
+ JSRelease(ptr);
+ return *this;
+}
+
+template<typename T> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(T optr)
+{
+ if (optr)
+ JSRetain(optr);
+ T ptr = m_ptr;
+ m_ptr = optr;
+ if (ptr)
+ JSRelease(ptr);
+ return *this;
+}
+
+template<typename T> inline void JSRetainPtr<T>::adopt(T optr)
+{
+ T ptr = m_ptr;
+ m_ptr = optr;
+ if (ptr)
+ JSRelease(ptr);
+}
+
+template<typename T> template<typename U> inline JSRetainPtr<T>& JSRetainPtr<T>::operator=(U* optr)
+{
+ if (optr)
+ JSRetain(optr);
+ T ptr = m_ptr;
+ m_ptr = optr;
+ if (ptr)
+ JSRelease(ptr);
+ return *this;
+}
+
+template<typename T> inline void JSRetainPtr<T>::swap(JSRetainPtr<T>& o)
+{
+ std::swap(m_ptr, o.m_ptr);
+}
+
+template<typename T> inline void swap(JSRetainPtr<T>& a, JSRetainPtr<T>& b)
+{
+ a.swap(b);
+}
+
+template<typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
+{
+ return a.get() == b.get();
+}
+
+template<typename T, typename U> inline bool operator==(const JSRetainPtr<T>& a, U* b)
+{
+ return a.get() == b;
+}
+
+template<typename T, typename U> inline bool operator==(T* a, const JSRetainPtr<U>& b)
+{
+ return a == b.get();
+}
+
+template<typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, const JSRetainPtr<U>& b)
+{
+ return a.get() != b.get();
+}
+
+template<typename T, typename U> inline bool operator!=(const JSRetainPtr<T>& a, U* b)
+{
+ return a.get() != b;
+}
+
+template<typename T, typename U> inline bool operator!=(T* a, const JSRetainPtr<U>& b)
+{
+ return a != b.get();
+}
+
+
+#endif // JSRetainPtr_h
diff --git a/Source/JavaScriptCore/API/JSScriptRef.cpp b/Source/JavaScriptCore/API/JSScriptRef.cpp
new file mode 100644
index 000000000..3b7b76bf3
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSScriptRef.cpp
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2012 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "APICast.h"
+#include "Completion.h"
+#include "Exception.h"
+#include "JSBasePrivate.h"
+#include "VM.h"
+#include "JSScriptRefPrivate.h"
+#include "OpaqueJSString.h"
+#include "JSCInlines.h"
+#include "Parser.h"
+#include "SourceCode.h"
+#include "SourceProvider.h"
+
+using namespace JSC;
+
+struct OpaqueJSScript : public SourceProvider {
+public:
+ static WTF::RefPtr<OpaqueJSScript> create(VM* vm, const String& url, int startingLineNumber, const String& source)
+ {
+ return WTF::adoptRef(*new OpaqueJSScript(vm, url, startingLineNumber, source));
+ }
+
+ virtual const String& source() const override
+ {
+ return m_source;
+ }
+
+ VM* vm() const { return m_vm; }
+
+private:
+ OpaqueJSScript(VM* vm, const String& url, int startingLineNumber, const String& source)
+ : SourceProvider(url, TextPosition(OrdinalNumber::fromOneBasedInt(startingLineNumber), OrdinalNumber::first()))
+ , m_vm(vm)
+ , m_source(source)
+ {
+ }
+
+ virtual ~OpaqueJSScript() { }
+
+ VM* m_vm;
+ String m_source;
+};
+
+static bool parseScript(VM* vm, const SourceCode& source, ParserError& error)
+{
+ return !!JSC::parse<JSC::ProgramNode>(
+ vm, source, Identifier(), JSParserBuiltinMode::NotBuiltin,
+ JSParserStrictMode::NotStrict, SourceParseMode::ProgramMode,
+ error);
+}
+
+extern "C" {
+
+JSScriptRef JSScriptCreateReferencingImmortalASCIIText(JSContextGroupRef contextGroup, JSStringRef url, int startingLineNumber, const char* source, size_t length, JSStringRef* errorMessage, int* errorLine)
+{
+ VM* vm = toJS(contextGroup);
+ JSLockHolder locker(vm);
+ for (size_t i = 0; i < length; i++) {
+ if (!isASCII(source[i]))
+ return 0;
+ }
+
+ startingLineNumber = std::max(1, startingLineNumber);
+
+ RefPtr<OpaqueJSScript> result = OpaqueJSScript::create(vm, url ? url->string() : String(), startingLineNumber, String(StringImpl::createFromLiteral(source, length)));
+
+ ParserError error;
+ if (!parseScript(vm, SourceCode(result), error)) {
+ if (errorMessage)
+ *errorMessage = OpaqueJSString::create(error.message()).leakRef();
+ if (errorLine)
+ *errorLine = error.line();
+ return nullptr;
+ }
+
+ return result.release().leakRef();
+}
+
+JSScriptRef JSScriptCreateFromString(JSContextGroupRef contextGroup, JSStringRef url, int startingLineNumber, JSStringRef source, JSStringRef* errorMessage, int* errorLine)
+{
+ VM* vm = toJS(contextGroup);
+ JSLockHolder locker(vm);
+
+ startingLineNumber = std::max(1, startingLineNumber);
+
+ RefPtr<OpaqueJSScript> result = OpaqueJSScript::create(vm, url ? url->string() : String(), startingLineNumber, source->string());
+
+ ParserError error;
+ if (!parseScript(vm, SourceCode(result), error)) {
+ if (errorMessage)
+ *errorMessage = OpaqueJSString::create(error.message()).leakRef();
+ if (errorLine)
+ *errorLine = error.line();
+ return nullptr;
+ }
+
+ return result.release().leakRef();
+}
+
+void JSScriptRetain(JSScriptRef script)
+{
+ JSLockHolder locker(script->vm());
+ script->ref();
+}
+
+void JSScriptRelease(JSScriptRef script)
+{
+ JSLockHolder locker(script->vm());
+ script->deref();
+}
+
+JSValueRef JSScriptEvaluate(JSContextRef context, JSScriptRef script, JSValueRef thisValueRef, JSValueRef* exception)
+{
+ ExecState* exec = toJS(context);
+ JSLockHolder locker(exec);
+ if (script->vm() != &exec->vm()) {
+ RELEASE_ASSERT_NOT_REACHED();
+ return 0;
+ }
+ NakedPtr<Exception> internalException;
+ JSValue thisValue = thisValueRef ? toJS(exec, thisValueRef) : jsUndefined();
+ JSValue result = evaluate(exec, SourceCode(script), thisValue, internalException);
+ if (internalException) {
+ if (exception)
+ *exception = toRef(exec, internalException->value());
+ return 0;
+ }
+ ASSERT(result);
+ return toRef(exec, result);
+}
+
+}
diff --git a/Source/JavaScriptCore/API/JSScriptRefPrivate.h b/Source/JavaScriptCore/API/JSScriptRefPrivate.h
new file mode 100644
index 000000000..e6224ce37
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSScriptRefPrivate.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2012 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSScriptRefPrivate_h
+#define JSScriptRefPrivate_h
+
+#include <JavaScriptCore/JSContextRef.h>
+#include <JavaScriptCore/JSStringRef.h>
+#include <JavaScriptCore/JSValueRef.h>
+
+/*! @typedef JSScriptRef A JavaScript script reference. */
+typedef struct OpaqueJSScript* JSScriptRef;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ @function
+ @abstract Creates a script reference from an ascii string, without copying or taking ownership of the string
+ @param contextGroup The context group the script is to be used in.
+ @param url The source url to be reported in errors and exceptions.
+ @param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
+ @param source The source string. This is required to be pure ASCII and to never be deallocated.
+ @param length The length of the source string.
+ @param errorMessage A pointer to a JSStringRef in which to store the parse error message if the source is not valid. Pass NULL if you do not care to store an error message.
+ @param errorLine A pointer to an int in which to store the line number of a parser error. Pass NULL if you do not care to store an error line.
+ @result A JSScriptRef for the provided source, or NULL if any non-ASCII character is found in source or if the source is not a valid JavaScript program. Ownership follows the Create Rule.
+ @discussion Use this function to create a reusable script reference with a constant
+ buffer as the backing string. The source string must outlive the global context.
+ */
+JS_EXPORT JSScriptRef JSScriptCreateReferencingImmortalASCIIText(JSContextGroupRef contextGroup, JSStringRef url, int startingLineNumber, const char* source, size_t length, JSStringRef* errorMessage, int* errorLine);
+
+/*!
+ @function
+ @abstract Creates a script reference from a string
+ @param contextGroup The context group the script is to be used in.
+ @param url The source url to be reported in errors and exceptions.
+ @param startingLineNumber An integer value specifying the script's starting line number in the file located at sourceURL. This is only used when reporting exceptions. The value is one-based, so the first line is line 1 and invalid values are clamped to 1.
+ @param source The source string.
+ @param errorMessage A pointer to a JSStringRef in which to store the parse error message if the source is not valid. Pass NULL if you do not care to store an error message.
+ @param errorLine A pointer to an int in which to store the line number of a parser error. Pass NULL if you do not care to store an error line.
+ @result A JSScriptRef for the provided source, or NULL is the source is not a valid JavaScript program. Ownership follows the Create Rule.
+ */
+JS_EXPORT JSScriptRef JSScriptCreateFromString(JSContextGroupRef contextGroup, JSStringRef url, int startingLineNumber, JSStringRef source, JSStringRef* errorMessage, int* errorLine);
+
+/*!
+ @function
+ @abstract Retains a JavaScript script.
+ @param script The script to retain.
+ */
+JS_EXPORT void JSScriptRetain(JSScriptRef script);
+
+/*!
+ @function
+ @abstract Releases a JavaScript script.
+ @param script The script to release.
+ */
+JS_EXPORT void JSScriptRelease(JSScriptRef script);
+
+/*!
+ @function
+ @abstract Evaluates a JavaScript script.
+ @param ctx The execution context to use.
+ @param script The JSScript to evaluate.
+ @param thisValue The value to use as "this" when evaluating the script.
+ @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+ @result The JSValue that results from evaluating script, or NULL if an exception is thrown.
+ */
+JS_EXPORT JSValueRef JSScriptEvaluate(JSContextRef ctx, JSScriptRef script, JSValueRef thisValue, JSValueRef* exception);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSScriptRefPrivate_h */
diff --git a/Source/JavaScriptCore/API/JSStringRef.cpp b/Source/JavaScriptCore/API/JSStringRef.cpp
new file mode 100644
index 000000000..c9b380ce6
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSStringRef.cpp
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSStringRef.h"
+#include "JSStringRefPrivate.h"
+
+#include "InitializeThreading.h"
+#include "OpaqueJSString.h"
+#include <wtf/unicode/UTF8.h>
+
+using namespace JSC;
+using namespace WTF::Unicode;
+
+JSStringRef JSStringCreateWithCharacters(const JSChar* chars, size_t numChars)
+{
+ initializeThreading();
+ return &OpaqueJSString::create(chars, numChars).leakRef();
+}
+
+JSStringRef JSStringCreateWithUTF8CString(const char* string)
+{
+ initializeThreading();
+ if (string) {
+ size_t length = strlen(string);
+ Vector<UChar, 1024> buffer(length);
+ UChar* p = buffer.data();
+ bool sourceIsAllASCII;
+ const LChar* stringStart = reinterpret_cast<const LChar*>(string);
+ if (conversionOK == convertUTF8ToUTF16(&string, string + length, &p, p + length, &sourceIsAllASCII)) {
+ if (sourceIsAllASCII)
+ return &OpaqueJSString::create(stringStart, length).leakRef();
+ return &OpaqueJSString::create(buffer.data(), p - buffer.data()).leakRef();
+ }
+ }
+
+ return &OpaqueJSString::create().leakRef();
+}
+
+JSStringRef JSStringCreateWithCharactersNoCopy(const JSChar* chars, size_t numChars)
+{
+ initializeThreading();
+ return OpaqueJSString::create(StringImpl::createWithoutCopying(chars, numChars)).leakRef();
+}
+
+JSStringRef JSStringRetain(JSStringRef string)
+{
+ string->ref();
+ return string;
+}
+
+void JSStringRelease(JSStringRef string)
+{
+ string->deref();
+}
+
+size_t JSStringGetLength(JSStringRef string)
+{
+ if (!string)
+ return 0;
+ return string->length();
+}
+
+const JSChar* JSStringGetCharactersPtr(JSStringRef string)
+{
+ if (!string)
+ return nullptr;
+ return string->characters();
+}
+
+size_t JSStringGetMaximumUTF8CStringSize(JSStringRef string)
+{
+ // Any UTF8 character > 3 bytes encodes as a UTF16 surrogate pair.
+ return string->length() * 3 + 1; // + 1 for terminating '\0'
+}
+
+size_t JSStringGetUTF8CString(JSStringRef string, char* buffer, size_t bufferSize)
+{
+ if (!string || !buffer || !bufferSize)
+ return 0;
+
+ char* destination = buffer;
+ ConversionResult result;
+ if (string->is8Bit()) {
+ const LChar* source = string->characters8();
+ result = convertLatin1ToUTF8(&source, source + string->length(), &destination, destination + bufferSize - 1);
+ } else {
+ const UChar* source = string->characters16();
+ result = convertUTF16ToUTF8(&source, source + string->length(), &destination, destination + bufferSize - 1, true);
+ }
+
+ *destination++ = '\0';
+ if (result != conversionOK && result != targetExhausted)
+ return 0;
+
+ return destination - buffer;
+}
+
+bool JSStringIsEqual(JSStringRef a, JSStringRef b)
+{
+ return OpaqueJSString::equal(a, b);
+}
+
+bool JSStringIsEqualToUTF8CString(JSStringRef a, const char* b)
+{
+ JSStringRef bBuf = JSStringCreateWithUTF8CString(b);
+ bool result = JSStringIsEqual(a, bBuf);
+ JSStringRelease(bBuf);
+
+ return result;
+}
diff --git a/Source/JavaScriptCore/API/JSStringRef.h b/Source/JavaScriptCore/API/JSStringRef.h
new file mode 100644
index 000000000..6f45fcbd8
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSStringRef.h
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSStringRef_h
+#define JSStringRef_h
+
+#include <JavaScriptCore/JSValueRef.h>
+
+#ifndef __cplusplus
+#include <stdbool.h>
+#endif
+#include <stddef.h> /* for size_t */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(WIN32) && !defined(_WIN32) \
+ && !((defined(__CC_ARM) || defined(__ARMCC__)) && !defined(__linux__)) /* RVCT */
+/*!
+@typedef JSChar
+@abstract A Unicode character.
+*/
+ typedef unsigned short JSChar;
+#else
+ typedef wchar_t JSChar;
+#endif
+
+/*!
+@function
+@abstract Creates a JavaScript string from a buffer of Unicode characters.
+@param chars The buffer of Unicode characters to copy into the new JSString.
+@param numChars The number of characters to copy from the buffer pointed to by chars.
+@result A JSString containing chars. Ownership follows the Create Rule.
+*/
+JS_EXPORT JSStringRef JSStringCreateWithCharacters(const JSChar* chars, size_t numChars);
+/*!
+@function
+@abstract Creates a JavaScript string from a null-terminated UTF8 string.
+@param string The null-terminated UTF8 string to copy into the new JSString.
+@result A JSString containing string. Ownership follows the Create Rule.
+*/
+JS_EXPORT JSStringRef JSStringCreateWithUTF8CString(const char* string);
+
+/*!
+@function
+@abstract Retains a JavaScript string.
+@param string The JSString to retain.
+@result A JSString that is the same as string.
+*/
+JS_EXPORT JSStringRef JSStringRetain(JSStringRef string);
+/*!
+@function
+@abstract Releases a JavaScript string.
+@param string The JSString to release.
+*/
+JS_EXPORT void JSStringRelease(JSStringRef string);
+
+/*!
+@function
+@abstract Returns the number of Unicode characters in a JavaScript string.
+@param string The JSString whose length (in Unicode characters) you want to know.
+@result The number of Unicode characters stored in string.
+*/
+JS_EXPORT size_t JSStringGetLength(JSStringRef string);
+/*!
+@function
+@abstract Returns a pointer to the Unicode character buffer that
+ serves as the backing store for a JavaScript string.
+@param string The JSString whose backing store you want to access.
+@result A pointer to the Unicode character buffer that serves as string's
+ backing store, which will be deallocated when string is deallocated.
+*/
+JS_EXPORT const JSChar* JSStringGetCharactersPtr(JSStringRef string);
+
+/*!
+@function
+@abstract Returns the maximum number of bytes a JavaScript string will
+ take up if converted into a null-terminated UTF8 string.
+@param string The JSString whose maximum converted size (in bytes) you
+ want to know.
+@result The maximum number of bytes that could be required to convert string into a
+ null-terminated UTF8 string. The number of bytes that the conversion actually ends
+ up requiring could be less than this, but never more.
+*/
+JS_EXPORT size_t JSStringGetMaximumUTF8CStringSize(JSStringRef string);
+/*!
+@function
+@abstract Converts a JavaScript string into a null-terminated UTF8 string,
+ and copies the result into an external byte buffer.
+@param string The source JSString.
+@param buffer The destination byte buffer into which to copy a null-terminated
+ UTF8 representation of string. On return, buffer contains a UTF8 string
+ representation of string. If bufferSize is too small, buffer will contain only
+ partial results. If buffer is not at least bufferSize bytes in size,
+ behavior is undefined.
+@param bufferSize The size of the external buffer in bytes.
+@result The number of bytes written into buffer (including the null-terminator byte).
+*/
+JS_EXPORT size_t JSStringGetUTF8CString(JSStringRef string, char* buffer, size_t bufferSize);
+
+/*!
+@function
+@abstract Tests whether two JavaScript strings match.
+@param a The first JSString to test.
+@param b The second JSString to test.
+@result true if the two strings match, otherwise false.
+*/
+JS_EXPORT bool JSStringIsEqual(JSStringRef a, JSStringRef b);
+/*!
+@function
+@abstract Tests whether a JavaScript string matches a null-terminated UTF8 string.
+@param a The JSString to test.
+@param b The null-terminated UTF8 string to test.
+@result true if the two strings match, otherwise false.
+*/
+JS_EXPORT bool JSStringIsEqualToUTF8CString(JSStringRef a, const char* b);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSStringRef_h */
diff --git a/Source/JavaScriptCore/API/JSStringRefBSTR.cpp b/Source/JavaScriptCore/API/JSStringRefBSTR.cpp
new file mode 100644
index 000000000..e900d24d8
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSStringRefBSTR.cpp
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSStringRefBSTR.h"
+
+#include "JSStringRef.h"
+
+JSStringRef JSStringCreateWithBSTR(BSTR string)
+{
+ return JSStringCreateWithCharacters(string ? string : L"", string ? SysStringLen(string) : 0);
+}
+
+BSTR JSStringCopyBSTR(const JSStringRef string)
+{
+ return SysAllocStringLen(JSStringGetCharactersPtr(string), JSStringGetLength(string));
+}
diff --git a/Source/JavaScriptCore/API/JSStringRefBSTR.h b/Source/JavaScriptCore/API/JSStringRefBSTR.h
new file mode 100644
index 000000000..066c68d53
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSStringRefBSTR.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSStringRefBSTR_h
+#define JSStringRefBSTR_h
+
+#include "JSBase.h"
+
+#include <windows.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* COM convenience methods */
+
+/*!
+@function
+@abstract Creates a JavaScript string from a BSTR.
+@param string The BSTR to copy into the new JSString.
+@result A JSString containing string. Ownership follows the Create Rule.
+*/
+JS_EXPORT JSStringRef JSStringCreateWithBSTR(const BSTR string);
+
+/*!
+@function
+@abstract Creates a BSTR from a JavaScript string.
+@param string The JSString to copy into the new BSTR.
+@result A BSTR containing string. Ownership follows the Create Rule.
+*/
+JS_EXPORT BSTR JSStringCopyBSTR(const JSStringRef string);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSStringRefBSTR_h */
diff --git a/Source/JavaScriptCore/API/JSStringRefCF.cpp b/Source/JavaScriptCore/API/JSStringRefCF.cpp
new file mode 100644
index 000000000..05872593f
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSStringRefCF.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSStringRefCF.h"
+
+#include "APICast.h"
+#include "InitializeThreading.h"
+#include "JSCJSValue.h"
+#include "JSStringRef.h"
+#include "OpaqueJSString.h"
+#include <wtf/StdLibExtras.h>
+
+JSStringRef JSStringCreateWithCFString(CFStringRef string)
+{
+ JSC::initializeThreading();
+
+ // We cannot use CFIndex here since CFStringGetLength can return values larger than
+ // it can hold. (<rdar://problem/6806478>)
+ size_t length = CFStringGetLength(string);
+ if (!length)
+ return &OpaqueJSString::create(reinterpret_cast<const LChar*>(""), 0).leakRef();
+
+ Vector<LChar, 1024> lcharBuffer(length);
+ CFIndex usedBufferLength;
+ CFIndex convertedSize = CFStringGetBytes(string, CFRangeMake(0, length), kCFStringEncodingISOLatin1, 0, false, lcharBuffer.data(), length, &usedBufferLength);
+ if (static_cast<size_t>(convertedSize) == length && static_cast<size_t>(usedBufferLength) == length)
+ return &OpaqueJSString::create(lcharBuffer.data(), length).leakRef();
+
+ auto buffer = std::make_unique<UniChar[]>(length);
+ CFStringGetCharacters(string, CFRangeMake(0, length), buffer.get());
+ static_assert(sizeof(UniChar) == sizeof(UChar), "UniChar and UChar must be same size");
+ return &OpaqueJSString::create(reinterpret_cast<UChar*>(buffer.get()), length).leakRef();
+}
+
+CFStringRef JSStringCopyCFString(CFAllocatorRef allocator, JSStringRef string)
+{
+ if (!string || !string->length())
+ return CFSTR("");
+
+ if (string->is8Bit())
+ return CFStringCreateWithBytes(allocator, reinterpret_cast<const UInt8*>(string->characters8()), string->length(), kCFStringEncodingISOLatin1, false);
+
+ return CFStringCreateWithCharacters(allocator, reinterpret_cast<const UniChar*>(string->characters16()), string->length());
+}
diff --git a/Source/JavaScriptCore/API/JSStringRefCF.h b/Source/JavaScriptCore/API/JSStringRefCF.h
new file mode 100644
index 000000000..1e210c7a9
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSStringRefCF.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSStringRefCF_h
+#define JSStringRefCF_h
+
+#include "JSBase.h"
+#include <CoreFoundation/CoreFoundation.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* CFString convenience methods */
+
+/*!
+@function
+@abstract Creates a JavaScript string from a CFString.
+@discussion This function is optimized to take advantage of cases when
+ CFStringGetCharactersPtr returns a valid pointer.
+@param string The CFString to copy into the new JSString.
+@result A JSString containing string. Ownership follows the Create Rule.
+*/
+JS_EXPORT JSStringRef JSStringCreateWithCFString(CFStringRef string);
+/*!
+@function
+@abstract Creates a CFString from a JavaScript string.
+@param alloc The alloc parameter to pass to CFStringCreate.
+@param string The JSString to copy into the new CFString.
+@result A CFString containing string. Ownership follows the Create Rule.
+*/
+JS_EXPORT CFStringRef JSStringCopyCFString(CFAllocatorRef alloc, JSStringRef string) CF_RETURNS_RETAINED;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSStringRefCF_h */
diff --git a/Source/JavaScriptCore/API/JSStringRefPrivate.h b/Source/JavaScriptCore/API/JSStringRefPrivate.h
new file mode 100644
index 000000000..f1db806ee
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSStringRefPrivate.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSStringRefPrivate_h
+#define JSStringRefPrivate_h
+
+#include <JavaScriptCore/JSStringRef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JS_EXPORT JSStringRef JSStringCreateWithCharactersNoCopy(const JSChar* chars, size_t numChars);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSStringRefPrivate_h */
diff --git a/Source/JavaScriptCore/API/JSValue.h b/Source/JavaScriptCore/API/JSValue.h
new file mode 100644
index 000000000..803d10513
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSValue.h
@@ -0,0 +1,679 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSValue_h
+#define JSValue_h
+
+#if JSC_OBJC_API_ENABLED
+
+#import <CoreGraphics/CGGeometry.h>
+
+@class JSContext;
+
+/*!
+@interface
+@discussion A JSValue is a reference to a value within the JavaScript object space of a
+ JSVirtualMachine. All instances of JSValue originate from a JSContext and
+ hold a strong reference to this JSContext. As long as any value associated with
+ a particular JSContext is retained, that JSContext will remain alive.
+ Where an instance method is invoked upon a JSValue, and this returns another
+ JSValue, the returned JSValue will originate from the same JSContext as the
+ JSValue on which the method was invoked.
+
+ All JavaScript values are associated with a particular JSVirtualMachine
+ (the associated JSVirtualMachine is available indirectly via the context
+ property). An instance of JSValue may only be passed as an argument to
+ methods on instances of JSValue and JSContext that belong to the same
+ JSVirtualMachine - passing a JSValue to a method on an object originating
+ from a different JSVirtualMachine will result in an Objective-C exception
+ being raised.
+*/
+NS_CLASS_AVAILABLE(10_9, 7_0)
+@interface JSValue : NSObject
+
+/*!
+@property
+@abstract The JSContext that this value originates from.
+*/
+@property (readonly, strong) JSContext *context;
+
+/*!
+@methodgroup Creating JavaScript Values
+*/
+/*!
+@method
+@abstract Create a JSValue by converting an Objective-C object.
+@discussion The resulting JSValue retains the provided Objective-C object.
+@param value The Objective-C object to be converted.
+@result The new JSValue.
+*/
++ (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a JavaScript value from a BOOL primitive.
+@param value
+@param context The JSContext in which the resulting JSValue will be created.
+@result The new JSValue representing the equivalent boolean value.
+*/
++ (JSValue *)valueWithBool:(BOOL)value inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a JavaScript value from a double primitive.
+@param value
+@param context The JSContext in which the resulting JSValue will be created.
+@result The new JSValue representing the equivalent boolean value.
+*/
++ (JSValue *)valueWithDouble:(double)value inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a JavaScript value from an <code>int32_t</code> primitive.
+@param value
+@param context The JSContext in which the resulting JSValue will be created.
+@result The new JSValue representing the equivalent boolean value.
+*/
++ (JSValue *)valueWithInt32:(int32_t)value inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a JavaScript value from a <code>uint32_t</code> primitive.
+@param value
+@param context The JSContext in which the resulting JSValue will be created.
+@result The new JSValue representing the equivalent boolean value.
+*/
++ (JSValue *)valueWithUInt32:(uint32_t)value inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a new, empty JavaScript object.
+@param context The JSContext in which the resulting object will be created.
+@result The new JavaScript object.
+*/
++ (JSValue *)valueWithNewObjectInContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a new, empty JavaScript array.
+@param context The JSContext in which the resulting array will be created.
+@result The new JavaScript array.
+*/
++ (JSValue *)valueWithNewArrayInContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a new JavaScript regular expression object.
+@param pattern The regular expression pattern.
+@param flags The regular expression flags.
+@param context The JSContext in which the resulting regular expression object will be created.
+@result The new JavaScript regular expression object.
+*/
++ (JSValue *)valueWithNewRegularExpressionFromPattern:(NSString *)pattern flags:(NSString *)flags inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a new JavaScript error object.
+@param message The error message.
+@param context The JSContext in which the resulting error object will be created.
+@result The new JavaScript error object.
+*/
++ (JSValue *)valueWithNewErrorFromMessage:(NSString *)message inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create the JavaScript value <code>null</code>.
+@param context The JSContext to which the resulting JSValue belongs.
+@result The JSValue representing the JavaScript value <code>null</code>.
+*/
++ (JSValue *)valueWithNullInContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create the JavaScript value <code>undefined</code>.
+@param context The JSContext to which the resulting JSValue belongs.
+@result The JSValue representing the JavaScript value <code>undefined</code>.
+*/
++ (JSValue *)valueWithUndefinedInContext:(JSContext *)context;
+
+/*!
+@methodgroup Converting to Objective-C Types
+@discussion When converting between JavaScript values and Objective-C objects a copy is
+ performed. Values of types listed below are copied to the corresponding
+ types on conversion in each direction. For NSDictionaries, entries in the
+ dictionary that are keyed by strings are copied onto a JavaScript object.
+ For dictionaries and arrays, conversion is recursive, with the same object
+ conversion being applied to all entries in the collection.
+
+<pre>
+@textblock
+ 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)
+@/textblock
+</pre>
+
+ (1) Instances of NSBlock with supported arguments types will be presented to
+ JavaScript as a callable Function object. For more information on supported
+ argument types see JSExport.h. If a JavaScript Function originating from an
+ Objective-C block is converted back to an Objective-C object the block will
+ be returned. All other JavaScript functions will be converted in the same
+ manner as a JavaScript object of type Object.
+
+ (2) For Objective-C instances that do not derive from the set of types listed
+ above, a wrapper object to provide a retaining handle to the Objective-C
+ instance from JavaScript. For more information on these wrapper objects, see
+ JSExport.h. When a JavaScript wrapper object is converted back to Objective-C
+ the Objective-C instance being retained by the wrapper is returned.
+
+ (3) For Objective-C Class objects a constructor object containing exported
+ class methods will be returned. See JSExport.h for more information on
+ constructor objects.
+
+ For all methods taking arguments of type id, arguments will be converted
+ into a JavaScript value according to the above conversion.
+*/
+/*!
+@method
+@abstract Convert this JSValue to an Objective-C object.
+@discussion The JSValue is converted to an Objective-C object according
+ to the conversion rules specified above.
+@result The Objective-C representation of this JSValue.
+*/
+- (id)toObject;
+
+/*!
+@method
+@abstract Convert a JSValue to an Objective-C object of a specific class.
+@discussion The JSValue is converted to an Objective-C object of the specified Class.
+ If the result is not of the specified Class then <code>nil</code> will be returned.
+@result An Objective-C object of the specified Class or <code>nil</code>.
+*/
+- (id)toObjectOfClass:(Class)expectedClass;
+
+/*!
+@method
+@abstract Convert a JSValue to a boolean.
+@discussion The JSValue is converted to a boolean according to the rules specified
+ by the JavaScript language.
+@result The boolean result of the conversion.
+*/
+- (BOOL)toBool;
+
+/*!
+@method
+@abstract Convert a JSValue to a double.
+@discussion The JSValue is converted to a number according to the rules specified
+ by the JavaScript language.
+@result The double result of the conversion.
+*/
+- (double)toDouble;
+
+/*!
+@method
+@abstract Convert a JSValue to an <code>int32_t</code>.
+@discussion The JSValue is converted to an integer according to the rules specified
+ by the JavaScript language.
+@result The <code>int32_t</code> result of the conversion.
+*/
+- (int32_t)toInt32;
+
+/*!
+@method
+@abstract Convert a JSValue to a <code>uint32_t</code>.
+@discussion The JSValue is converted to an integer according to the rules specified
+ by the JavaScript language.
+@result The <code>uint32_t</code> result of the conversion.
+*/
+- (uint32_t)toUInt32;
+
+/*!
+@method
+@abstract Convert a JSValue to a NSNumber.
+@discussion If the JSValue represents a boolean, a NSNumber value of YES or NO
+ will be returned. For all other types the value will be converted to a number according
+ to the rules specified by the JavaScript language.
+@result The NSNumber result of the conversion.
+*/
+- (NSNumber *)toNumber;
+
+/*!
+@method
+@abstract Convert a JSValue to a NSString.
+@discussion The JSValue is converted to a string according to the rules specified
+ by the JavaScript language.
+@result The NSString containing the result of the conversion.
+*/
+- (NSString *)toString;
+
+/*!
+@method
+@abstract Convert a JSValue to a NSDate.
+@discussion The value is converted to a number representing a time interval
+ since 1970 which is then used to create a new NSDate instance.
+@result The NSDate created using the converted time interval.
+*/
+- (NSDate *)toDate;
+
+/*!
+@method
+@abstract Convert a JSValue to a NSArray.
+@discussion If the value is <code>null</code> or <code>undefined</code> then <code>nil</code> is returned.
+ If the value is not an object then a JavaScript TypeError will be thrown.
+ The property <code>length</code> is read from the object, converted to an unsigned
+ integer, and an NSArray of this size is allocated. Properties corresponding
+ to indicies within the array bounds will be copied to the array, with
+ JSValues converted to equivalent Objective-C objects as specified.
+@result The NSArray containing the recursively converted contents of the
+ converted JavaScript array.
+*/
+- (NSArray *)toArray;
+
+/*!
+@method
+@abstract Convert a JSValue to a NSDictionary.
+@discussion If the value is <code>null</code> or <code>undefined</code> then <code>nil</code> is returned.
+ If the value is not an object then a JavaScript TypeError will be thrown.
+ All enumerable properties of the object are copied to the dictionary, with
+ JSValues converted to equivalent Objective-C objects as specified.
+@result The NSDictionary containing the recursively converted contents of
+ the converted JavaScript object.
+*/
+- (NSDictionary *)toDictionary;
+
+/*!
+@methodgroup Accessing Properties
+*/
+/*!
+@method
+@abstract Access a property of a JSValue.
+@result The JSValue for the requested property or the JSValue <code>undefined</code>
+ if the property does not exist.
+*/
+- (JSValue *)valueForProperty:(NSString *)property;
+
+/*!
+@method
+@abstract Set a property on a JSValue.
+*/
+- (void)setValue:(id)value forProperty:(NSString *)property;
+
+/*!
+@method
+@abstract Delete a property from a JSValue.
+@result YES if deletion is successful, NO otherwise.
+*/
+- (BOOL)deleteProperty:(NSString *)property;
+
+/*!
+@method
+@abstract Check if a JSValue has a property.
+@discussion This method has the same function as the JavaScript operator <code>in</code>.
+@result Returns YES if property is present on the value.
+*/
+- (BOOL)hasProperty:(NSString *)property;
+
+/*!
+@method
+@abstract Define properties with custom descriptors on JSValues.
+@discussion This method may be used to create a data or accessor property on an object.
+ This method operates in accordance with the Object.defineProperty method in the
+ JavaScript language.
+*/
+- (void)defineProperty:(NSString *)property descriptor:(id)descriptor;
+
+/*!
+@method
+@abstract Access an indexed (numerical) property on a JSValue.
+@result The JSValue for the property at the specified index.
+ Returns the JavaScript value <code>undefined</code> if no property exists at that index.
+*/
+- (JSValue *)valueAtIndex:(NSUInteger)index;
+
+/*!
+@method
+@abstract Set an indexed (numerical) property on a JSValue.
+@discussion For JSValues that are JavaScript arrays, indices greater than
+ UINT_MAX - 1 will not affect the length of the array.
+*/
+- (void)setValue:(id)value atIndex:(NSUInteger)index;
+
+/*!
+@methodgroup Checking JavaScript Types
+*/
+/*!
+@method
+@abstract Check if a JSValue corresponds to the JavaScript value <code>undefined</code>.
+*/
+@property (readonly) BOOL isUndefined;
+
+/*!
+@method
+@abstract Check if a JSValue corresponds to the JavaScript value <code>null</code>.
+*/
+@property (readonly) BOOL isNull;
+
+/*!
+@method
+@abstract Check if a JSValue is a boolean.
+*/
+@property (readonly) BOOL isBoolean;
+
+/*!
+@method
+@abstract Check if a JSValue is a number.
+@discussion In JavaScript, there is no differentiation between types of numbers.
+ Semantically all numbers behave like doubles except in special cases like bit
+ operations.
+*/
+@property (readonly) BOOL isNumber;
+
+/*!
+@method
+@abstract Check if a JSValue is a string.
+*/
+@property (readonly) BOOL isString;
+
+/*!
+@method
+@abstract Check if a JSValue is an object.
+*/
+@property (readonly) BOOL isObject;
+
+/*!
+@method
+@abstract Check if a JSValue is an array.
+*/
+@property (readonly) BOOL isArray NS_AVAILABLE(10_11, 9_0);
+
+/*!
+@method
+@abstract Check if a JSValue is a date.
+*/
+@property (readonly) BOOL isDate NS_AVAILABLE(10_11, 9_0);
+
+/*!
+@method
+@abstract Compare two JSValues using JavaScript's <code>===</code> operator.
+*/
+- (BOOL)isEqualToObject:(id)value;
+
+/*!
+@method
+@abstract Compare two JSValues using JavaScript's <code>==</code> operator.
+*/
+- (BOOL)isEqualWithTypeCoercionToObject:(id)value;
+
+/*!
+@method
+@abstract Check if a JSValue is an instance of another object.
+@discussion This method has the same function as the JavaScript operator <code>instanceof</code>.
+ If an object other than a JSValue is passed, it will first be converted according to
+ the aforementioned rules.
+*/
+- (BOOL)isInstanceOf:(id)value;
+
+/*!
+@methodgroup Calling Functions and Constructors
+*/
+/*!
+@method
+@abstract Invoke a JSValue as a function.
+@discussion In JavaScript, if a function doesn't explicitly return a value then it
+ implicitly returns the JavaScript value <code>undefined</code>.
+@param arguments The arguments to pass to the function.
+@result The return value of the function call.
+*/
+- (JSValue *)callWithArguments:(NSArray *)arguments;
+
+/*!
+@method
+@abstract Invoke a JSValue as a constructor.
+@discussion This is equivalent to using the <code>new</code> syntax in JavaScript.
+@param arguments The arguments to pass to the constructor.
+@result The return value of the constructor call.
+*/
+- (JSValue *)constructWithArguments:(NSArray *)arguments;
+
+/*!
+@method
+@abstract Invoke a method on a JSValue.
+@discussion Accesses the property named <code>method</code> from this value and
+ calls the resulting value as a function, passing this JSValue as the <code>this</code>
+ value along with the specified arguments.
+@param method The name of the method to be invoked.
+@param arguments The arguments to pass to the method.
+@result The return value of the method call.
+*/
+- (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments;
+
+@end
+
+/*!
+@category
+@discussion Objective-C methods exported to JavaScript may have argument and/or return
+ values of struct types, provided that conversion to and from the struct is
+ supported by JSValue. Support is provided for any types where JSValue
+ contains both a class method <code>valueWith<Type>:inContext:</code>, and and instance
+ method <code>to<Type></code>- where the string <code><Type></code> in these selector names match,
+ with the first argument to the former being of the same struct type as the
+ return type of the latter.
+ Support is provided for structs of type CGPoint, NSRange, CGRect and CGSize.
+*/
+@interface JSValue (StructSupport)
+
+/*!
+@method
+@abstract Create a JSValue from a CGPoint.
+@result A newly allocated JavaScript object containing properties
+ named <code>x</code> and <code>y</code>, with values from the CGPoint.
+*/
++ (JSValue *)valueWithPoint:(CGPoint)point inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a JSValue from a NSRange.
+@result A newly allocated JavaScript object containing properties
+ named <code>location</code> and <code>length</code>, with values from the NSRange.
+*/
++ (JSValue *)valueWithRange:(NSRange)range inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract
+Create a JSValue from a CGRect.
+@result A newly allocated JavaScript object containing properties
+ named <code>x</code>, <code>y</code>, <code>width</code>, and <code>height</code>, with values from the CGRect.
+*/
++ (JSValue *)valueWithRect:(CGRect)rect inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Create a JSValue from a CGSize.
+@result A newly allocated JavaScript object containing properties
+ named <code>width</code> and <code>height</code>, with values from the CGSize.
+*/
++ (JSValue *)valueWithSize:(CGSize)size inContext:(JSContext *)context;
+
+/*!
+@method
+@abstract Convert a JSValue to a CGPoint.
+@discussion Reads the properties named <code>x</code> and <code>y</code> from
+ this JSValue, and converts the results to double.
+@result The new CGPoint.
+*/
+- (CGPoint)toPoint;
+
+/*!
+@method
+@abstract Convert a JSValue to an NSRange.
+@discussion Reads the properties named <code>location</code> and
+ <code>length</code> from this JSValue and converts the results to double.
+@result The new NSRange.
+*/
+- (NSRange)toRange;
+
+/*!
+@method
+@abstract Convert a JSValue to a CGRect.
+@discussion Reads the properties named <code>x</code>, <code>y</code>,
+ <code>width</code>, and <code>height</code> from this JSValue and converts the results to double.
+@result The new CGRect.
+*/
+- (CGRect)toRect;
+
+/*!
+@method
+@abstract Convert a JSValue to a CGSize.
+@discussion Reads the properties named <code>width</code> and
+ <code>height</code> from this JSValue and converts the results to double.
+@result The new CGSize.
+*/
+- (CGSize)toSize;
+
+@end
+
+/*!
+@category
+@discussion Instances of JSValue implement the following methods in order to enable
+ support for subscript access by key and index, for example:
+
+@textblock
+ JSValue *objectA, *objectB;
+ JSValue *v1 = object[@"X"]; // Get value for property "X" from 'object'.
+ JSValue *v2 = object[42]; // Get value for index 42 from 'object'.
+ object[@"Y"] = v1; // Assign 'v1' to property "Y" of 'object'.
+ object[101] = v2; // Assign 'v2' to index 101 of 'object'.
+@/textblock
+
+ An object key passed as a subscript will be converted to a JavaScript value,
+ and then the value converted to a string used as a property name.
+*/
+@interface JSValue (SubscriptSupport)
+
+- (JSValue *)objectForKeyedSubscript:(id)key;
+- (JSValue *)objectAtIndexedSubscript:(NSUInteger)index;
+- (void)setObject:(id)object forKeyedSubscript:(NSObject <NSCopying> *)key;
+- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index;
+
+@end
+
+/*!
+@category
+@discussion These functions are for bridging between the C API and the Objective-C API.
+*/
+@interface JSValue (JSValueRefSupport)
+
+/*!
+@method
+@abstract Creates a JSValue, wrapping its C API counterpart.
+@param value
+@param context
+@result The Objective-C API equivalent of the specified JSValueRef.
+*/
++ (JSValue *)valueWithJSValueRef:(JSValueRef)value inContext:(JSContext *)context;
+
+/*!
+@property
+@abstract Returns the C API counterpart wrapped by a JSContext.
+@result The C API equivalent of this JSValue.
+*/
+@property (readonly) JSValueRef JSValueRef;
+@end
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+@group Property Descriptor Constants
+@discussion These keys may assist in creating a property descriptor for use with the
+ defineProperty method on JSValue.
+ Property descriptors must fit one of three descriptions:
+
+ Data Descriptor:
+ - A descriptor containing one or both of the keys <code>value</code> and <code>writable</code>,
+ and optionally containing one or both of the keys <code>enumerable</code> and
+ <code>configurable</code>. A data descriptor may not contain either the <code>get</code> or
+ <code>set</code> key.
+ A data descriptor may be used to create or modify the attributes of a
+ data property on an object (replacing any existing accessor property).
+
+ Accessor Descriptor:
+ - A descriptor containing one or both of the keys <code>get</code> and <code>set</code>, and
+ optionally containing one or both of the keys <code>enumerable</code> and
+ <code>configurable</code>. An accessor descriptor may not contain either the <code>value</code>
+ or <code>writable</code> key.
+ An accessor descriptor may be used to create or modify the attributes of
+ an accessor property on an object (replacing any existing data property).
+
+ Generic Descriptor:
+ - A descriptor containing one or both of the keys <code>enumerable</code> and
+ <code>configurable</code>. A generic descriptor may not contain any of the keys
+ <code>value</code>, <code>writable</code>, <code>get</code>, or <code>set</code>.
+ A generic descriptor may be used to modify the attributes of an existing
+ data or accessor property, or to create a new data property.
+*/
+/*!
+@const
+*/
+JS_EXPORT extern NSString * const JSPropertyDescriptorWritableKey;
+/*!
+@const
+*/
+JS_EXPORT extern NSString * const JSPropertyDescriptorEnumerableKey;
+/*!
+@const
+*/
+JS_EXPORT extern NSString * const JSPropertyDescriptorConfigurableKey;
+/*!
+@const
+*/
+JS_EXPORT extern NSString * const JSPropertyDescriptorValueKey;
+/*!
+@const
+*/
+JS_EXPORT extern NSString * const JSPropertyDescriptorGetKey;
+/*!
+@const
+*/
+JS_EXPORT extern NSString * const JSPropertyDescriptorSetKey;
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif
+
+#endif // JSValue_h
diff --git a/Source/JavaScriptCore/API/JSValueInternal.h b/Source/JavaScriptCore/API/JSValueInternal.h
new file mode 100644
index 000000000..4f1a8f69c
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSValueInternal.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSValueInternal_h
+#define JSValueInternal_h
+
+#import <JavaScriptCore/JavaScriptCore.h>
+#import <JavaScriptCore/JSValue.h>
+
+#if JSC_OBJC_API_ENABLED
+
+@interface JSValue(Internal)
+
+JSValueRef valueInternalValue(JSValue *);
+
+- (JSValue *)initWithValue:(JSValueRef)value inContext:(JSContext *)context;
+
+JSValueRef objectToValue(JSContext *, id);
+id valueToObject(JSContext *, JSValueRef);
+id valueToNumber(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
+id valueToString(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
+id valueToDate(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
+id valueToArray(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
+id valueToDictionary(JSGlobalContextRef, JSValueRef, JSValueRef* exception);
+
++ (SEL)selectorForStructToValue:(const char *)structTag;
++ (SEL)selectorForValueToStruct:(const char *)structTag;
+
+@end
+
+NSInvocation *typeToValueInvocationFor(const char* encodedType);
+NSInvocation *valueToTypeInvocationFor(const char* encodedType);
+
+#endif
+
+#endif // JSValueInternal_h
diff --git a/Source/JavaScriptCore/API/JSValueRef.cpp b/Source/JavaScriptCore/API/JSValueRef.cpp
new file mode 100644
index 000000000..54405e2af
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSValueRef.cpp
@@ -0,0 +1,471 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSValueRef.h"
+
+#include "APICast.h"
+#include "DateInstance.h"
+#include "Exception.h"
+#include "JSAPIWrapperObject.h"
+#include "JSCInlines.h"
+#include "JSCJSValue.h"
+#include "JSCallbackObject.h"
+#include "JSGlobalObject.h"
+#include "JSONObject.h"
+#include "JSString.h"
+#include "LiteralParser.h"
+#include "Protect.h"
+#include <algorithm>
+#include <wtf/Assertions.h>
+#include <wtf/text/StringHash.h>
+#include <wtf/text/WTFString.h>
+
+#if PLATFORM(MAC)
+#include <mach-o/dyld.h>
+#endif
+
+#if ENABLE(REMOTE_INSPECTOR)
+#include "JSGlobalObjectInspectorController.h"
+#endif
+
+using namespace JSC;
+
+enum class ExceptionStatus {
+ DidThrow,
+ DidNotThrow
+};
+
+static ExceptionStatus handleExceptionIfNeeded(ExecState* exec, JSValueRef* returnedExceptionRef)
+{
+ if (exec->hadException()) {
+ Exception* exception = exec->exception();
+ if (returnedExceptionRef)
+ *returnedExceptionRef = toRef(exec, exception->value());
+ exec->clearException();
+#if ENABLE(REMOTE_INSPECTOR)
+ exec->vmEntryGlobalObject()->inspectorController().reportAPIException(exec, exception);
+#endif
+ return ExceptionStatus::DidThrow;
+ }
+ return ExceptionStatus::DidNotThrow;
+}
+
+#if PLATFORM(MAC)
+static bool evernoteHackNeeded()
+{
+ static const int32_t webkitLastVersionWithEvernoteHack = 35133959;
+ static bool hackNeeded = CFEqual(CFBundleGetIdentifier(CFBundleGetMainBundle()), CFSTR("com.evernote.Evernote"))
+ && NSVersionOfLinkTimeLibrary("JavaScriptCore") <= webkitLastVersionWithEvernoteHack;
+
+ return hackNeeded;
+}
+#endif
+
+::JSType JSValueGetType(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return kJSTypeUndefined;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJS(exec, value);
+
+ if (jsValue.isUndefined())
+ return kJSTypeUndefined;
+ if (jsValue.isNull())
+ return kJSTypeNull;
+ if (jsValue.isBoolean())
+ return kJSTypeBoolean;
+ if (jsValue.isNumber())
+ return kJSTypeNumber;
+ if (jsValue.isString())
+ return kJSTypeString;
+ ASSERT(jsValue.isObject());
+ return kJSTypeObject;
+}
+
+bool JSValueIsUndefined(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toJS(exec, value).isUndefined();
+}
+
+bool JSValueIsNull(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toJS(exec, value).isNull();
+}
+
+bool JSValueIsBoolean(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toJS(exec, value).isBoolean();
+}
+
+bool JSValueIsNumber(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toJS(exec, value).isNumber();
+}
+
+bool JSValueIsString(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toJS(exec, value).isString();
+}
+
+bool JSValueIsObject(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toJS(exec, value).isObject();
+}
+
+bool JSValueIsArray(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toJS(exec, value).inherits(JSArray::info());
+}
+
+bool JSValueIsDate(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toJS(exec, value).inherits(DateInstance::info());
+}
+
+bool JSValueIsObjectOfClass(JSContextRef ctx, JSValueRef value, JSClassRef jsClass)
+{
+ if (!ctx || !jsClass) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJS(exec, value);
+
+ if (JSObject* o = jsValue.getObject()) {
+ if (o->inherits(JSProxy::info()))
+ o = jsCast<JSProxy*>(o)->target();
+
+ if (o->inherits(JSCallbackObject<JSGlobalObject>::info()))
+ return jsCast<JSCallbackObject<JSGlobalObject>*>(o)->inherits(jsClass);
+ if (o->inherits(JSCallbackObject<JSDestructibleObject>::info()))
+ return jsCast<JSCallbackObject<JSDestructibleObject>*>(o)->inherits(jsClass);
+#if JSC_OBJC_API_ENABLED
+ if (o->inherits(JSCallbackObject<JSAPIWrapperObject>::info()))
+ return jsCast<JSCallbackObject<JSAPIWrapperObject>*>(o)->inherits(jsClass);
+#endif
+ }
+ return false;
+}
+
+bool JSValueIsEqual(JSContextRef ctx, JSValueRef a, JSValueRef b, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsA = toJS(exec, a);
+ JSValue jsB = toJS(exec, b);
+
+ bool result = JSValue::equal(exec, jsA, jsB); // false if an exception is thrown
+ handleExceptionIfNeeded(exec, exception);
+
+ return result;
+}
+
+bool JSValueIsStrictEqual(JSContextRef ctx, JSValueRef a, JSValueRef b)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsA = toJS(exec, a);
+ JSValue jsB = toJS(exec, b);
+
+ return JSValue::strictEqual(exec, jsA, jsB);
+}
+
+bool JSValueIsInstanceOfConstructor(JSContextRef ctx, JSValueRef value, JSObjectRef constructor, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJS(exec, value);
+
+ JSObject* jsConstructor = toJS(constructor);
+ if (!jsConstructor->structure()->typeInfo().implementsHasInstance())
+ return false;
+ bool result = jsConstructor->hasInstance(exec, jsValue); // false if an exception is thrown
+ handleExceptionIfNeeded(exec, exception);
+ return result;
+}
+
+JSValueRef JSValueMakeUndefined(JSContextRef ctx)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toRef(exec, jsUndefined());
+}
+
+JSValueRef JSValueMakeNull(JSContextRef ctx)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toRef(exec, jsNull());
+}
+
+JSValueRef JSValueMakeBoolean(JSContextRef ctx, bool value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toRef(exec, jsBoolean(value));
+}
+
+JSValueRef JSValueMakeNumber(JSContextRef ctx, double value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toRef(exec, jsNumber(purifyNaN(value)));
+}
+
+JSValueRef JSValueMakeString(JSContextRef ctx, JSStringRef string)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ return toRef(exec, jsString(exec, string ? string->string() : String()));
+}
+
+JSValueRef JSValueMakeFromJSONString(JSContextRef ctx, JSStringRef string)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ String str = string->string();
+ unsigned length = str.length();
+ if (!length || str.is8Bit()) {
+ LiteralParser<LChar> parser(exec, str.characters8(), length, StrictJSON);
+ return toRef(exec, parser.tryLiteralParse());
+ }
+ LiteralParser<UChar> parser(exec, str.characters16(), length, StrictJSON);
+ return toRef(exec, parser.tryLiteralParse());
+}
+
+JSStringRef JSValueCreateJSONString(JSContextRef ctx, JSValueRef apiValue, unsigned indent, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ JSValue value = toJS(exec, apiValue);
+ String result = JSONStringify(exec, value, indent);
+ if (exception)
+ *exception = 0;
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ return 0;
+ return OpaqueJSString::create(result).leakRef();
+}
+
+bool JSValueToBoolean(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJS(exec, value);
+ return jsValue.toBoolean(exec);
+}
+
+double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return PNaN;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJS(exec, value);
+
+ double number = jsValue.toNumber(exec);
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ number = PNaN;
+ return number;
+}
+
+JSStringRef JSValueToStringCopy(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJS(exec, value);
+
+ RefPtr<OpaqueJSString> stringRef(OpaqueJSString::create(jsValue.toString(exec)->value(exec)));
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ stringRef = nullptr;
+ return stringRef.release().leakRef();
+}
+
+JSObjectRef JSValueToObject(JSContextRef ctx, JSValueRef value, JSValueRef* exception)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJS(exec, value);
+
+ JSObjectRef objectRef = toRef(jsValue.toObject(exec));
+ if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
+ objectRef = 0;
+ return objectRef;
+}
+
+void JSValueProtect(JSContextRef ctx, JSValueRef value)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJSForGC(exec, value);
+ gcProtect(jsValue);
+}
+
+void JSValueUnprotect(JSContextRef ctx, JSValueRef value)
+{
+#if PLATFORM(MAC)
+ if ((!value || !ctx) && evernoteHackNeeded())
+ return;
+#endif
+
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+
+ JSValue jsValue = toJSForGC(exec, value);
+ gcUnprotect(jsValue);
+}
diff --git a/Source/JavaScriptCore/API/JSValueRef.h b/Source/JavaScriptCore/API/JSValueRef.h
new file mode 100644
index 000000000..9c4fa58cd
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSValueRef.h
@@ -0,0 +1,319 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSValueRef_h
+#define JSValueRef_h
+
+#include <JavaScriptCore/JSBase.h>
+#include <JavaScriptCore/WebKitAvailability.h>
+
+#ifndef __cplusplus
+#include <stdbool.h>
+#endif
+
+/*!
+@enum JSType
+@abstract A constant identifying the type of a JSValue.
+@constant kJSTypeUndefined The unique undefined value.
+@constant kJSTypeNull The unique null value.
+@constant kJSTypeBoolean A primitive boolean value, one of true or false.
+@constant kJSTypeNumber A primitive number value.
+@constant kJSTypeString A primitive string value.
+@constant kJSTypeObject An object value (meaning that this JSValueRef is a JSObjectRef).
+*/
+typedef enum {
+ kJSTypeUndefined,
+ kJSTypeNull,
+ kJSTypeBoolean,
+ kJSTypeNumber,
+ kJSTypeString,
+ kJSTypeObject
+} JSType;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+@function
+@abstract Returns a JavaScript value's type.
+@param ctx The execution context to use.
+@param value The JSValue whose type you want to obtain.
+@result A value of type JSType that identifies value's type.
+*/
+JS_EXPORT JSType JSValueGetType(JSContextRef ctx, JSValueRef);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value's type is the undefined type.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@result true if value's type is the undefined type, otherwise false.
+*/
+JS_EXPORT bool JSValueIsUndefined(JSContextRef ctx, JSValueRef value);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value's type is the null type.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@result true if value's type is the null type, otherwise false.
+*/
+JS_EXPORT bool JSValueIsNull(JSContextRef ctx, JSValueRef value);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value's type is the boolean type.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@result true if value's type is the boolean type, otherwise false.
+*/
+JS_EXPORT bool JSValueIsBoolean(JSContextRef ctx, JSValueRef value);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value's type is the number type.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@result true if value's type is the number type, otherwise false.
+*/
+JS_EXPORT bool JSValueIsNumber(JSContextRef ctx, JSValueRef value);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value's type is the string type.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@result true if value's type is the string type, otherwise false.
+*/
+JS_EXPORT bool JSValueIsString(JSContextRef ctx, JSValueRef value);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value's type is the object type.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@result true if value's type is the object type, otherwise false.
+*/
+JS_EXPORT bool JSValueIsObject(JSContextRef ctx, JSValueRef value);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value is an object with a given class in its class chain.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@param jsClass The JSClass to test against.
+@result true if value is an object and has jsClass in its class chain, otherwise false.
+*/
+JS_EXPORT bool JSValueIsObjectOfClass(JSContextRef ctx, JSValueRef value, JSClassRef jsClass);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value is an array.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@result true if value is an array, otherwise false.
+*/
+JS_EXPORT bool JSValueIsArray(JSContextRef ctx, JSValueRef value) CF_AVAILABLE(10_11, 9_0);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value is a date.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@result true if value is a date, otherwise false.
+*/
+JS_EXPORT bool JSValueIsDate(JSContextRef ctx, JSValueRef value) CF_AVAILABLE(10_11, 9_0);
+
+/* Comparing values */
+
+/*!
+@function
+@abstract Tests whether two JavaScript values are equal, as compared by the JS == operator.
+@param ctx The execution context to use.
+@param a The first value to test.
+@param b The second value to test.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result true if the two values are equal, false if they are not equal or an exception is thrown.
+*/
+JS_EXPORT bool JSValueIsEqual(JSContextRef ctx, JSValueRef a, JSValueRef b, JSValueRef* exception);
+
+/*!
+@function
+@abstract Tests whether two JavaScript values are strict equal, as compared by the JS === operator.
+@param ctx The execution context to use.
+@param a The first value to test.
+@param b The second value to test.
+@result true if the two values are strict equal, otherwise false.
+*/
+JS_EXPORT bool JSValueIsStrictEqual(JSContextRef ctx, JSValueRef a, JSValueRef b);
+
+/*!
+@function
+@abstract Tests whether a JavaScript value is an object constructed by a given constructor, as compared by the JS instanceof operator.
+@param ctx The execution context to use.
+@param value The JSValue to test.
+@param constructor The constructor to test against.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result true if value is an object constructed by constructor, as compared by the JS instanceof operator, otherwise false.
+*/
+JS_EXPORT bool JSValueIsInstanceOfConstructor(JSContextRef ctx, JSValueRef value, JSObjectRef constructor, JSValueRef* exception);
+
+/* Creating values */
+
+/*!
+@function
+@abstract Creates a JavaScript value of the undefined type.
+@param ctx The execution context to use.
+@result The unique undefined value.
+*/
+JS_EXPORT JSValueRef JSValueMakeUndefined(JSContextRef ctx);
+
+/*!
+@function
+@abstract Creates a JavaScript value of the null type.
+@param ctx The execution context to use.
+@result The unique null value.
+*/
+JS_EXPORT JSValueRef JSValueMakeNull(JSContextRef ctx);
+
+/*!
+@function
+@abstract Creates a JavaScript value of the boolean type.
+@param ctx The execution context to use.
+@param boolean The bool to assign to the newly created JSValue.
+@result A JSValue of the boolean type, representing the value of boolean.
+*/
+JS_EXPORT JSValueRef JSValueMakeBoolean(JSContextRef ctx, bool boolean);
+
+/*!
+@function
+@abstract Creates a JavaScript value of the number type.
+@param ctx The execution context to use.
+@param number The double to assign to the newly created JSValue.
+@result A JSValue of the number type, representing the value of number.
+*/
+JS_EXPORT JSValueRef JSValueMakeNumber(JSContextRef ctx, double number);
+
+/*!
+@function
+@abstract Creates a JavaScript value of the string type.
+@param ctx The execution context to use.
+@param string The JSString to assign to the newly created JSValue. The
+ newly created JSValue retains string, and releases it upon garbage collection.
+@result A JSValue of the string type, representing the value of string.
+*/
+JS_EXPORT JSValueRef JSValueMakeString(JSContextRef ctx, JSStringRef string);
+
+/* Converting to and from JSON formatted strings */
+
+/*!
+ @function
+ @abstract Creates a JavaScript value from a JSON formatted string.
+ @param ctx The execution context to use.
+ @param string The JSString containing the JSON string to be parsed.
+ @result A JSValue containing the parsed value, or NULL if the input is invalid.
+ */
+JS_EXPORT JSValueRef JSValueMakeFromJSONString(JSContextRef ctx, JSStringRef string) CF_AVAILABLE(10_7, 7_0);
+
+/*!
+ @function
+ @abstract Creates a JavaScript string containing the JSON serialized representation of a JS value.
+ @param ctx The execution context to use.
+ @param value The value to serialize.
+ @param indent The number of spaces to indent when nesting. If 0, the resulting JSON will not contains newlines. The size of the indent is clamped to 10 spaces.
+ @param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+ @result A JSString with the result of serialization, or NULL if an exception is thrown.
+ */
+JS_EXPORT JSStringRef JSValueCreateJSONString(JSContextRef ctx, JSValueRef value, unsigned indent, JSValueRef* exception) CF_AVAILABLE(10_7, 7_0);
+
+/* Converting to primitive values */
+
+/*!
+@function
+@abstract Converts a JavaScript value to boolean and returns the resulting boolean.
+@param ctx The execution context to use.
+@param value The JSValue to convert.
+@result The boolean result of conversion.
+*/
+JS_EXPORT bool JSValueToBoolean(JSContextRef ctx, JSValueRef value);
+
+/*!
+@function
+@abstract Converts a JavaScript value to number and returns the resulting number.
+@param ctx The execution context to use.
+@param value The JSValue to convert.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result The numeric result of conversion, or NaN if an exception is thrown.
+*/
+JS_EXPORT double JSValueToNumber(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
+
+/*!
+@function
+@abstract Converts a JavaScript value to string and copies the result into a JavaScript string.
+@param ctx The execution context to use.
+@param value The JSValue to convert.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result A JSString with the result of conversion, or NULL if an exception is thrown. Ownership follows the Create Rule.
+*/
+JS_EXPORT JSStringRef JSValueToStringCopy(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
+
+/*!
+@function
+@abstract Converts a JavaScript value to object and returns the resulting object.
+@param ctx The execution context to use.
+@param value The JSValue to convert.
+@param exception A pointer to a JSValueRef in which to store an exception, if any. Pass NULL if you do not care to store an exception.
+@result The JSObject result of conversion, or NULL if an exception is thrown.
+*/
+JS_EXPORT JSObjectRef JSValueToObject(JSContextRef ctx, JSValueRef value, JSValueRef* exception);
+
+/* Garbage collection */
+/*!
+@function
+@abstract Protects a JavaScript value from garbage collection.
+@param ctx The execution context to use.
+@param value The JSValue to protect.
+@discussion Use this method when you want to store a JSValue in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
+
+A value may be protected multiple times and must be unprotected an equal number of times before becoming eligible for garbage collection.
+*/
+JS_EXPORT void JSValueProtect(JSContextRef ctx, JSValueRef value);
+
+/*!
+@function
+@abstract Unprotects a JavaScript value from garbage collection.
+@param ctx The execution context to use.
+@param value The JSValue to unprotect.
+@discussion A value may be protected multiple times and must be unprotected an
+ equal number of times before becoming eligible for garbage collection.
+*/
+JS_EXPORT void JSValueUnprotect(JSContextRef ctx, JSValueRef value);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* JSValueRef_h */
diff --git a/Source/JavaScriptCore/API/JSVirtualMachine.h b/Source/JavaScriptCore/API/JSVirtualMachine.h
new file mode 100644
index 000000000..ccf9264d5
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSVirtualMachine.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <JavaScriptCore/JavaScriptCore.h>
+
+#if JSC_OBJC_API_ENABLED
+
+/*!
+@interface
+@discussion An instance of JSVirtualMachine represents a single JavaScript "object space"
+ or set of execution resources. Thread safety is supported by locking the
+ virtual machine, with concurrent JavaScript execution supported by allocating
+ separate instances of JSVirtualMachine.
+*/
+NS_CLASS_AVAILABLE(10_9, 7_0)
+@interface JSVirtualMachine : NSObject
+
+/*!
+@methodgroup Creating New Virtual Machines
+*/
+/*!
+@method
+@abstract Create a new JSVirtualMachine.
+*/
+- (instancetype)init;
+
+/*!
+@methodgroup Memory Management
+*/
+/*!
+@method
+@abstract Notify the JSVirtualMachine of an external object relationship.
+@discussion Allows clients of JSVirtualMachine to make the JavaScript runtime aware of
+ arbitrary external Objective-C object graphs. The runtime can then use
+ this information to retain any JavaScript values that are referenced
+ from somewhere in said object graph.
+
+ For correct behavior clients must make their external object graphs
+ reachable from within the JavaScript runtime. If an Objective-C object is
+ reachable from within the JavaScript runtime, all managed references
+ transitively reachable from it as recorded using
+ -addManagedReference:withOwner: will be scanned by the garbage collector.
+@param object The object that the owner points to.
+@param owner The object that owns the pointed to object.
+*/
+- (void)addManagedReference:(id)object withOwner:(id)owner;
+
+/*!
+@method
+@abstract Notify the JSVirtualMachine that a previous object relationship no longer exists.
+@discussion The JavaScript runtime will continue to scan any references that were
+ reported to it by -addManagedReference:withOwner: until those references are removed.
+@param object The object that was formerly owned.
+@param owner The former owner.
+*/
+- (void)removeManagedReference:(id)object withOwner:(id)owner;
+
+@end
+
+#endif
diff --git a/Source/JavaScriptCore/API/JSVirtualMachineInternal.h b/Source/JavaScriptCore/API/JSVirtualMachineInternal.h
new file mode 100644
index 000000000..5a4fbefa5
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSVirtualMachineInternal.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSVirtualMachineInternal_h
+#define JSVirtualMachineInternal_h
+
+#if JSC_OBJC_API_ENABLED
+
+#import <JavaScriptCore/JavaScriptCore.h>
+
+namespace JSC {
+class VM;
+class SlotVisitor;
+}
+
+#if defined(__OBJC__)
+@class NSMapTable;
+
+@interface JSVirtualMachine(Internal)
+
+JSContextGroupRef getGroupFromVirtualMachine(JSVirtualMachine *);
+
++ (JSVirtualMachine *)virtualMachineWithContextGroupRef:(JSContextGroupRef)group;
+
+- (JSContext *)contextForGlobalContextRef:(JSGlobalContextRef)globalContext;
+- (void)addContext:(JSContext *)wrapper forGlobalContextRef:(JSGlobalContextRef)globalContext;
+
+- (NSMapTable *)externalObjectGraph;
+
+@end
+#endif // defined(__OBJC__)
+
+void scanExternalObjectGraph(JSC::VM&, JSC::SlotVisitor&, void* root);
+void scanExternalRememberedSet(JSC::VM&, JSC::SlotVisitor&);
+
+#endif // JSC_OBJC_API_ENABLED
+
+#endif // JSVirtualMachineInternal_h
diff --git a/Source/JavaScriptCore/API/JSWeakObjectMapRefInternal.h b/Source/JavaScriptCore/API/JSWeakObjectMapRefInternal.h
new file mode 100644
index 000000000..9037947d7
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSWeakObjectMapRefInternal.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSWeakObjectMapRefInternal_h
+#define JSWeakObjectMapRefInternal_h
+
+#include "WeakGCMap.h"
+#include <wtf/RefCounted.h>
+
+namespace JSC {
+
+class JSObject;
+
+}
+
+typedef void (*JSWeakMapDestroyedCallback)(struct OpaqueJSWeakObjectMap*, void*);
+
+typedef JSC::WeakGCMap<void*, JSC::JSObject> WeakMapType;
+
+struct OpaqueJSWeakObjectMap : public RefCounted<OpaqueJSWeakObjectMap> {
+public:
+ static Ref<OpaqueJSWeakObjectMap> create(JSC::VM& vm, void* data, JSWeakMapDestroyedCallback callback)
+ {
+ return adoptRef(*new OpaqueJSWeakObjectMap(vm, data, callback));
+ }
+
+ WeakMapType& map() { return m_map; }
+
+ ~OpaqueJSWeakObjectMap()
+ {
+ m_callback(this, m_data);
+ }
+
+private:
+ OpaqueJSWeakObjectMap(JSC::VM& vm, void* data, JSWeakMapDestroyedCallback callback)
+ : m_map(vm)
+ , m_data(data)
+ , m_callback(callback)
+ {
+ }
+ WeakMapType m_map;
+ void* m_data;
+ JSWeakMapDestroyedCallback m_callback;
+};
+
+
+#endif // JSWeakObjectMapInternal_h
diff --git a/Source/JavaScriptCore/API/JSWeakObjectMapRefPrivate.cpp b/Source/JavaScriptCore/API/JSWeakObjectMapRefPrivate.cpp
new file mode 100644
index 000000000..925c00f0b
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSWeakObjectMapRefPrivate.cpp
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "JSWeakObjectMapRefPrivate.h"
+
+#include "APICast.h"
+#include "JSCJSValue.h"
+#include "JSCallbackObject.h"
+#include "JSWeakObjectMapRefInternal.h"
+#include "JSCInlines.h"
+#include "Weak.h"
+#include "WeakGCMapInlines.h"
+#include <wtf/HashMap.h>
+#include <wtf/text/StringHash.h>
+
+using namespace WTF;
+using namespace JSC;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JSWeakObjectMapRef JSWeakObjectMapCreate(JSContextRef context, void* privateData, JSWeakMapDestroyedCallback callback)
+{
+ ExecState* exec = toJS(context);
+ JSLockHolder locker(exec);
+ RefPtr<OpaqueJSWeakObjectMap> map = OpaqueJSWeakObjectMap::create(exec->vm(), privateData, callback);
+ exec->lexicalGlobalObject()->registerWeakMap(map.get());
+ return map.get();
+}
+
+void JSWeakObjectMapSet(JSContextRef ctx, JSWeakObjectMapRef map, void* key, JSObjectRef object)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ JSObject* obj = toJS(object);
+ if (!obj)
+ return;
+ ASSERT(obj->inherits(JSProxy::info())
+ || obj->inherits(JSCallbackObject<JSGlobalObject>::info())
+ || obj->inherits(JSCallbackObject<JSDestructibleObject>::info()));
+ map->map().set(key, obj);
+}
+
+JSObjectRef JSWeakObjectMapGet(JSContextRef ctx, JSWeakObjectMapRef map, void* key)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ return toRef(jsCast<JSObject*>(map->map().get(key)));
+}
+
+void JSWeakObjectMapRemove(JSContextRef ctx, JSWeakObjectMapRef map, void* key)
+{
+ if (!ctx) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ ExecState* exec = toJS(ctx);
+ JSLockHolder locker(exec);
+ map->map().remove(key);
+}
+
+// We need to keep this function in the build to keep the nightlies running.
+JS_EXPORT bool JSWeakObjectMapClear(JSContextRef, JSWeakObjectMapRef, void*, JSObjectRef);
+bool JSWeakObjectMapClear(JSContextRef, JSWeakObjectMapRef, void*, JSObjectRef)
+{
+ return true;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/Source/JavaScriptCore/API/JSWeakObjectMapRefPrivate.h b/Source/JavaScriptCore/API/JSWeakObjectMapRefPrivate.h
new file mode 100644
index 000000000..5a07cf7c4
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSWeakObjectMapRefPrivate.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSWeakObjectMapRefPrivate_h
+#define JSWeakObjectMapRefPrivate_h
+
+#include <JavaScriptCore/JSContextRef.h>
+#include <JavaScriptCore/JSValueRef.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*! @typedef JSWeakObjectMapRef A weak map for storing JSObjectRefs */
+typedef struct OpaqueJSWeakObjectMap* JSWeakObjectMapRef;
+
+/*!
+ @typedef JSWeakMapDestroyedCallback
+ @abstract The callback invoked when a JSWeakObjectMapRef is being destroyed.
+ @param map The map that is being destroyed.
+ @param data The private data (if any) that was associated with the map instance.
+ */
+typedef void (*JSWeakMapDestroyedCallback)(JSWeakObjectMapRef map, void* data);
+
+/*!
+ @function
+ @abstract Creates a weak value map that can be used to reference user defined objects without preventing them from being collected.
+ @param ctx The execution context to use.
+ @param data A void* to set as the map's private data. Pass NULL to specify no private data.
+ @param destructor A function to call when the weak map is destroyed.
+ @result A JSWeakObjectMapRef bound to the given context, data and destructor.
+ @discussion The JSWeakObjectMapRef can be used as a storage mechanism to hold custom JS objects without forcing those objects to
+ remain live as JSValueProtect would.
+ */
+JS_EXPORT JSWeakObjectMapRef JSWeakObjectMapCreate(JSContextRef ctx, void* data, JSWeakMapDestroyedCallback destructor);
+
+/*!
+ @function
+ @abstract Associates a JSObjectRef with the given key in a JSWeakObjectMap.
+ @param ctx The execution context to use.
+ @param map The map to operate on.
+ @param key The key to associate a weak reference with.
+ @param object The user defined object to associate with the key.
+ */
+JS_EXPORT void JSWeakObjectMapSet(JSContextRef ctx, JSWeakObjectMapRef map, void* key, JSObjectRef);
+
+/*!
+ @function
+ @abstract Retrieves the JSObjectRef associated with a key.
+ @param ctx The execution context to use.
+ @param map The map to query.
+ @param key The key to search for.
+ @result Either the live object associated with the provided key, or NULL.
+ */
+JS_EXPORT JSObjectRef JSWeakObjectMapGet(JSContextRef ctx, JSWeakObjectMapRef map, void* key);
+
+/*!
+ @function
+ @abstract Removes the entry for the given key if the key is present, otherwise it has no effect.
+ @param ctx The execution context to use.
+ @param map The map to use.
+ @param key The key to remove.
+ */
+JS_EXPORT void JSWeakObjectMapRemove(JSContextRef ctx, JSWeakObjectMapRef map, void* key);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // JSWeakObjectMapPrivate_h
diff --git a/Source/JavaScriptCore/API/JSWrapperMap.h b/Source/JavaScriptCore/API/JSWrapperMap.h
new file mode 100644
index 000000000..c6aa1af13
--- /dev/null
+++ b/Source/JavaScriptCore/API/JSWrapperMap.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <JavaScriptCore/JavaScriptCore.h>
+#import <JSValueInternal.h>
+#import <objc/objc-runtime.h>
+
+#if JSC_OBJC_API_ENABLED
+
+@interface JSWrapperMap : NSObject
+
+- (id)initWithContext:(JSContext *)context;
+
+- (JSValue *)jsWrapperForObject:(id)object;
+
+- (JSValue *)objcWrapperForJSValueRef:(JSValueRef)value;
+
+@end
+
+id tryUnwrapObjcObject(JSGlobalContextRef, JSValueRef);
+
+bool supportsInitMethodConstructors();
+Protocol *getJSExportProtocol();
+Class getNSBlockClass();
+
+#endif
diff --git a/Source/JavaScriptCore/API/JavaScript.h b/Source/JavaScriptCore/API/JavaScript.h
new file mode 100644
index 000000000..ffe7b83fc
--- /dev/null
+++ b/Source/JavaScriptCore/API/JavaScript.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Alp Toker <alp@atoker.com>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JavaScript_h
+#define JavaScript_h
+
+#include <JavaScriptCore/JSBase.h>
+#include <JavaScriptCore/JSContextRef.h>
+#include <JavaScriptCore/JSStringRef.h>
+#include <JavaScriptCore/JSObjectRef.h>
+#include <JavaScriptCore/JSValueRef.h>
+
+#endif /* JavaScript_h */
diff --git a/Source/JavaScriptCore/API/JavaScriptCore.h b/Source/JavaScriptCore/API/JavaScriptCore.h
new file mode 100644
index 000000000..b2fde1dbe
--- /dev/null
+++ b/Source/JavaScriptCore/API/JavaScriptCore.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#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 */
diff --git a/Source/JavaScriptCore/API/ObjCCallbackFunction.h b/Source/JavaScriptCore/API/ObjCCallbackFunction.h
new file mode 100644
index 000000000..adb167c76
--- /dev/null
+++ b/Source/JavaScriptCore/API/ObjCCallbackFunction.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef ObjCCallbackFunction_h
+#define ObjCCallbackFunction_h
+
+#include <JavaScriptCore/JSBase.h>
+
+#if JSC_OBJC_API_ENABLED
+
+#import <JavaScriptCore/JSCallbackFunction.h>
+
+#if defined(__OBJC__)
+JSObjectRef objCCallbackFunctionForMethod(JSContext *, Class, Protocol *, BOOL isInstanceMethod, SEL, const char* types);
+JSObjectRef objCCallbackFunctionForBlock(JSContext *, id);
+JSObjectRef objCCallbackFunctionForInit(JSContext *, Class, Protocol *, SEL, const char* types);
+
+id tryUnwrapConstructor(JSObjectRef);
+#endif
+
+namespace JSC {
+
+class ObjCCallbackFunctionImpl;
+
+class ObjCCallbackFunction : public InternalFunction {
+ friend struct APICallbackFunction;
+public:
+ typedef InternalFunction Base;
+
+ static ObjCCallbackFunction* create(VM&, JSGlobalObject*, const String& name, std::unique_ptr<ObjCCallbackFunctionImpl>);
+ static void destroy(JSCell*);
+
+ static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
+ {
+ ASSERT(globalObject);
+ return Structure::create(vm, globalObject, prototype, TypeInfo(ObjectType, StructureFlags), info());
+ }
+
+ DECLARE_EXPORT_INFO;
+
+ ObjCCallbackFunctionImpl* impl() const { return m_impl.get(); }
+
+protected:
+ ObjCCallbackFunction(VM&, JSGlobalObject*, JSObjectCallAsFunctionCallback, JSObjectCallAsConstructorCallback, std::unique_ptr<ObjCCallbackFunctionImpl>);
+
+private:
+ static CallType getCallData(JSCell*, CallData&);
+ static ConstructType getConstructData(JSCell*, ConstructData&);
+
+ JSObjectCallAsFunctionCallback functionCallback() { return m_functionCallback; }
+ JSObjectCallAsConstructorCallback constructCallback() { return m_constructCallback; }
+
+ JSObjectCallAsFunctionCallback m_functionCallback;
+ JSObjectCallAsConstructorCallback m_constructCallback;
+ std::unique_ptr<ObjCCallbackFunctionImpl> m_impl;
+};
+
+} // namespace JSC
+
+#endif
+
+#endif // ObjCCallbackFunction_h
diff --git a/Source/JavaScriptCore/API/ObjcRuntimeExtras.h b/Source/JavaScriptCore/API/ObjcRuntimeExtras.h
new file mode 100644
index 000000000..128df5c90
--- /dev/null
+++ b/Source/JavaScriptCore/API/ObjcRuntimeExtras.h
@@ -0,0 +1,242 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <objc/Protocol.h>
+#import <objc/runtime.h>
+#import <wtf/HashSet.h>
+#import <wtf/Vector.h>
+
+inline bool protocolImplementsProtocol(Protocol *candidate, Protocol *target)
+{
+ unsigned protocolProtocolsCount;
+ Protocol ** protocolProtocols = protocol_copyProtocolList(candidate, &protocolProtocolsCount);
+ for (unsigned i = 0; i < protocolProtocolsCount; ++i) {
+ if (protocol_isEqual(protocolProtocols[i], target)) {
+ free(protocolProtocols);
+ return true;
+ }
+ }
+ free(protocolProtocols);
+ return false;
+}
+
+inline void forEachProtocolImplementingProtocol(Class cls, Protocol *target, void (^callback)(Protocol *))
+{
+ ASSERT(cls);
+ ASSERT(target);
+
+ 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);
+ }
+}
+
+inline void forEachMethodInClass(Class cls, void (^callback)(Method))
+{
+ unsigned count;
+ Method* methods = class_copyMethodList(cls, &count);
+ for (unsigned i = 0; i < count; ++i)
+ callback(methods[i]);
+ free(methods);
+}
+
+inline void forEachMethodInProtocol(Protocol *protocol, BOOL isRequiredMethod, BOOL isInstanceMethod, void (^callback)(SEL, const char*))
+{
+ unsigned count;
+ struct objc_method_description* methods = protocol_copyMethodDescriptionList(protocol, isRequiredMethod, isInstanceMethod, &count);
+ for (unsigned i = 0; i < count; ++i)
+ callback(methods[i].name, methods[i].types);
+ free(methods);
+}
+
+inline void forEachPropertyInProtocol(Protocol *protocol, void (^callback)(objc_property_t))
+{
+ unsigned count;
+ objc_property_t* properties = protocol_copyPropertyList(protocol, &count);
+ for (unsigned i = 0; i < count; ++i)
+ callback(properties[i]);
+ free(properties);
+}
+
+template<char open, char close>
+void skipPair(const char*& position)
+{
+ size_t count = 1;
+ do {
+ char c = *position++;
+ if (!c)
+ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Malformed type encoding" userInfo:nil];
+ if (c == open)
+ ++count;
+ else if (c == close)
+ --count;
+ } while (count);
+}
+
+class StringRange {
+ WTF_MAKE_NONCOPYABLE(StringRange);
+public:
+ StringRange(const char* begin, const char* end) : m_ptr(strndup(begin, end - begin)) { }
+ ~StringRange() { free(m_ptr); }
+ operator const char*() const { return m_ptr; }
+ const char* get() const { return m_ptr; }
+
+private:
+ char* m_ptr;
+};
+
+class StructBuffer {
+ WTF_MAKE_NONCOPYABLE(StructBuffer);
+public:
+ StructBuffer(const char* encodedType)
+ {
+ NSUInteger size, alignment;
+ NSGetSizeAndAlignment(encodedType, &size, &alignment);
+ --alignment;
+ m_allocation = static_cast<char*>(malloc(size + alignment));
+ m_buffer = reinterpret_cast<char*>((reinterpret_cast<intptr_t>(m_allocation) + alignment) & ~alignment);
+ }
+
+ ~StructBuffer() { free(m_allocation); }
+ operator void*() const { return m_buffer; }
+
+private:
+ void* m_allocation;
+ void* m_buffer;
+};
+
+template<typename DelegateType>
+typename DelegateType::ResultType parseObjCType(const char*& position)
+{
+ ASSERT(*position);
+
+ switch (*position++) {
+ case 'c':
+ return DelegateType::template typeInteger<char>();
+ case 'i':
+ return DelegateType::template typeInteger<int>();
+ case 's':
+ return DelegateType::template typeInteger<short>();
+ case 'l':
+ return DelegateType::template typeInteger<long>();
+ case 'q':
+ return DelegateType::template typeDouble<long long>();
+ case 'C':
+ return DelegateType::template typeInteger<unsigned char>();
+ case 'I':
+ return DelegateType::template typeInteger<unsigned>();
+ case 'S':
+ return DelegateType::template typeInteger<unsigned short>();
+ case 'L':
+ return DelegateType::template typeInteger<unsigned long>();
+ case 'Q':
+ return DelegateType::template typeDouble<unsigned long long>();
+ case 'f':
+ return DelegateType::template typeDouble<float>();
+ case 'd':
+ return DelegateType::template typeDouble<double>();
+ case 'B':
+ return DelegateType::typeBool();
+ case 'v':
+ return DelegateType::typeVoid();
+
+ case '@': { // An object (whether statically typed or typed id)
+ if (position[0] == '?' && position[1] == '<') {
+ position += 2;
+ const char* begin = position;
+ skipPair<'<','>'>(position);
+ return DelegateType::typeBlock(begin, position - 1);
+ }
+
+ if (*position == '"') {
+ const char* begin = position + 1;
+ const char* protocolPosition = strchr(begin, '<');
+ const char* endOfType = strchr(begin, '"');
+ position = endOfType + 1;
+
+ // There's no protocol involved in this type, so just handle the class name.
+ if (!protocolPosition || protocolPosition > endOfType)
+ return DelegateType::typeOfClass(begin, endOfType);
+ // We skipped the class name and went straight to the protocol, so this is an id type.
+ if (begin == protocolPosition)
+ return DelegateType::typeId();
+ // We have a class name with a protocol. For now, ignore the protocol.
+ return DelegateType::typeOfClass(begin, protocolPosition);
+ }
+
+ return DelegateType::typeId();
+ }
+
+ case '{': { // {name=type...} A structure
+ const char* begin = position - 1;
+ skipPair<'{','}'>(position);
+ return DelegateType::typeStruct(begin, position);
+ }
+
+ // NOT supporting C strings, arrays, pointers, unions, bitfields, function pointers.
+ case '*': // A character string (char *)
+ case '[': // [array type] An array
+ case '(': // (name=type...) A union
+ case 'b': // bnum A bit field of num bits
+ case '^': // ^type A pointer to type
+ case '?': // An unknown type (among other things, this code is used for function pointers)
+ // NOT supporting Objective-C Class, SEL
+ case '#': // A class object (Class)
+ case ':': // A method selector (SEL)
+ default:
+ return nil;
+ }
+}
+
+extern "C" {
+ // Forward declare some Objective-C runtime internal methods that are not API.
+ const char *_protocol_getMethodTypeEncoding(Protocol *, SEL, BOOL isRequiredMethod, BOOL isInstanceMethod);
+ id objc_initWeak(id *, id);
+ void objc_destroyWeak(id *);
+ bool _Block_has_signature(void *);
+ const char * _Block_signature(void *);
+}
diff --git a/Source/JavaScriptCore/API/OpaqueJSString.cpp b/Source/JavaScriptCore/API/OpaqueJSString.cpp
new file mode 100644
index 000000000..07a79ad99
--- /dev/null
+++ b/Source/JavaScriptCore/API/OpaqueJSString.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "OpaqueJSString.h"
+
+#include "CallFrame.h"
+#include "Identifier.h"
+#include "IdentifierInlines.h"
+#include "JSGlobalObject.h"
+#include <wtf/text/StringView.h>
+
+using namespace JSC;
+
+RefPtr<OpaqueJSString> OpaqueJSString::create(const String& string)
+{
+ if (string.isNull())
+ return nullptr;
+
+ return adoptRef(new OpaqueJSString(string));
+}
+
+OpaqueJSString::~OpaqueJSString()
+{
+ // m_characters is put in a local here to avoid an extra atomic load.
+ UChar* characters = m_characters;
+ if (!characters)
+ return;
+
+ if (!m_string.is8Bit() && m_string.characters16() == characters)
+ return;
+
+ fastFree(characters);
+}
+
+String OpaqueJSString::string() const
+{
+ // Return a copy of the wrapped string, because the caller may make it an Identifier.
+ return m_string.isolatedCopy();
+}
+
+Identifier OpaqueJSString::identifier(VM* vm) const
+{
+ if (m_string.isNull())
+ return Identifier();
+
+ if (m_string.isEmpty())
+ return Identifier(Identifier::EmptyIdentifier);
+
+ if (m_string.is8Bit())
+ return Identifier::fromString(vm, m_string.characters8(), m_string.length());
+
+ return Identifier::fromString(vm, m_string.characters16(), m_string.length());
+}
+
+const UChar* OpaqueJSString::characters()
+{
+ // m_characters is put in a local here to avoid an extra atomic load.
+ UChar* characters = m_characters;
+ if (characters)
+ return characters;
+
+ if (m_string.isNull())
+ return nullptr;
+
+ unsigned length = m_string.length();
+ UChar* newCharacters = static_cast<UChar*>(fastMalloc(length * sizeof(UChar)));
+ StringView(m_string).getCharactersWithUpconvert(newCharacters);
+
+ if (!m_characters.compare_exchange_strong(characters, newCharacters)) {
+ fastFree(newCharacters);
+ return characters;
+ }
+
+ return newCharacters;
+}
+
+bool OpaqueJSString::equal(const OpaqueJSString* a, const OpaqueJSString* b)
+{
+ if (a == b)
+ return true;
+
+ if (!a || !b)
+ return false;
+
+ return a->m_string == b->m_string;
+}
diff --git a/Source/JavaScriptCore/API/OpaqueJSString.h b/Source/JavaScriptCore/API/OpaqueJSString.h
new file mode 100644
index 000000000..208131b3b
--- /dev/null
+++ b/Source/JavaScriptCore/API/OpaqueJSString.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef OpaqueJSString_h
+#define OpaqueJSString_h
+
+#include <atomic>
+#include <wtf/ThreadSafeRefCounted.h>
+#include <wtf/text/WTFString.h>
+
+namespace JSC {
+ class Identifier;
+ class VM;
+}
+
+struct OpaqueJSString : public ThreadSafeRefCounted<OpaqueJSString> {
+ static Ref<OpaqueJSString> create()
+ {
+ return adoptRef(*new OpaqueJSString);
+ }
+
+ static Ref<OpaqueJSString> create(const LChar* characters, unsigned length)
+ {
+ return adoptRef(*new OpaqueJSString(characters, length));
+ }
+
+ static Ref<OpaqueJSString> create(const UChar* characters, unsigned length)
+ {
+ return adoptRef(*new OpaqueJSString(characters, length));
+ }
+
+ JS_EXPORT_PRIVATE static RefPtr<OpaqueJSString> create(const String&);
+
+ JS_EXPORT_PRIVATE ~OpaqueJSString();
+
+ bool is8Bit() { return m_string.is8Bit(); }
+ const LChar* characters8() { return m_string.characters8(); }
+ const UChar* characters16() { return m_string.characters16(); }
+ unsigned length() { return m_string.length(); }
+
+ const UChar* characters();
+
+ JS_EXPORT_PRIVATE String string() const;
+ JSC::Identifier identifier(JSC::VM*) const;
+
+ static bool equal(const OpaqueJSString*, const OpaqueJSString*);
+
+private:
+ friend class WTF::ThreadSafeRefCounted<OpaqueJSString>;
+
+ OpaqueJSString()
+ : m_characters(nullptr)
+ {
+ }
+
+ OpaqueJSString(const String& string)
+ : m_string(string.isolatedCopy())
+ , m_characters(m_string.impl() && m_string.is8Bit() ? nullptr : const_cast<UChar*>(m_string.characters16()))
+ {
+ }
+
+ OpaqueJSString(const LChar* characters, unsigned length)
+ : m_string(characters, length)
+ , m_characters(nullptr)
+ {
+ }
+
+ OpaqueJSString(const UChar* characters, unsigned length)
+ : m_string(characters, length)
+ , m_characters(m_string.impl() && m_string.is8Bit() ? nullptr : const_cast<UChar*>(m_string.characters16()))
+ {
+ }
+
+ String m_string;
+
+ // This will be initialized on demand when characters() is called if the string needs up-conversion.
+ std::atomic<UChar*> m_characters;
+};
+
+#endif
diff --git a/Source/JavaScriptCore/API/WebKitAvailability.h b/Source/JavaScriptCore/API/WebKitAvailability.h
new file mode 100644
index 000000000..28b3af4ee
--- /dev/null
+++ b/Source/JavaScriptCore/API/WebKitAvailability.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2008, 2009, 2010, 2014 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __WebKitAvailability__
+#define __WebKitAvailability__
+
+#if defined(__APPLE__) && !defined(BUILDING_GTK__)
+
+#include <AvailabilityMacros.h>
+#include <CoreFoundation/CoreFoundation.h>
+
+#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED < 101100
+/* To support availability macros that mention newer OS X versions when building on older OS X versions,
+ we provide our own definitions of the underlying macros that the availability macros expand to. We're
+ free to expand the macros as no-ops since frameworks built on older OS X versions only ship bundled with
+ an application rather than as part of the system.
+*/
+
+#ifndef __NSi_10_10 // Building from trunk rather than SDK.
+#define __NSi_10_10 introduced=10.0 // Use 10.0 to indicate that everything is available.
+#endif
+
+#ifndef __NSi_10_11 // Building from trunk rather than SDK.
+#define __NSi_10_11 introduced=10.0 // Use 10.0 to indicate that everything is available.
+#endif
+
+#ifndef __AVAILABILITY_INTERNAL__MAC_10_9
+#define __AVAILABILITY_INTERNAL__MAC_10_9
+#endif
+
+#ifndef __AVAILABILITY_INTERNAL__MAC_10_10
+#define __AVAILABILITY_INTERNAL__MAC_10_10
+#endif
+
+#ifndef AVAILABLE_MAC_OS_X_VERSION_10_9_AND_LATER
+#define AVAILABLE_MAC_OS_X_VERSION_10_9_AND_LATER
+#endif
+
+#ifndef AVAILABLE_MAC_OS_X_VERSION_10_10_AND_LATER
+#define AVAILABLE_MAC_OS_X_VERSION_10_10_AND_LATER
+#endif
+
+#endif /* __MAC_OS_X_VERSION_MIN_REQUIRED <= 101100 */
+
+#else
+#define CF_AVAILABLE(_mac, _ios)
+#endif
+
+#endif /* __WebKitAvailability__ */
diff --git a/Source/JavaScriptCore/API/tests/CompareAndSwapTest.cpp b/Source/JavaScriptCore/API/tests/CompareAndSwapTest.cpp
new file mode 100644
index 000000000..c78d47da4
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/CompareAndSwapTest.cpp
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "CompareAndSwapTest.h"
+
+#include <stdio.h>
+#include <wtf/Atomics.h>
+#include <wtf/Threading.h>
+
+class Bitmap {
+public:
+ Bitmap() { clearAll(); }
+
+ inline void clearAll();
+ inline bool concurrentTestAndSet(size_t n);
+ inline size_t numBits() const { return words * wordSize; }
+
+private:
+ static const size_t Size = 4096*10;
+
+ static const unsigned wordSize = sizeof(uint8_t) * 8;
+ static const unsigned words = (Size + wordSize - 1) / wordSize;
+ static const uint8_t one = 1;
+
+ uint8_t bits[words];
+};
+
+inline void Bitmap::clearAll()
+{
+ memset(&bits, 0, sizeof(bits));
+}
+
+inline bool Bitmap::concurrentTestAndSet(size_t n)
+{
+ uint8_t mask = one << (n % wordSize);
+ size_t index = n / wordSize;
+ uint8_t* wordPtr = &bits[index];
+ uint8_t oldValue;
+ do {
+ oldValue = *wordPtr;
+ if (oldValue & mask)
+ return true;
+ } while (!WTF::weakCompareAndSwap(wordPtr, oldValue, oldValue | mask));
+ return false;
+}
+
+struct Data {
+ Bitmap* bitmap;
+ int id;
+ int numThreads;
+};
+
+static void setBitThreadFunc(void* p)
+{
+ Data* data = reinterpret_cast<Data*>(p);
+ Bitmap* bitmap = data->bitmap;
+ size_t numBits = bitmap->numBits();
+
+ // The computed start index here is heuristic that seems to maximize (anecdotally)
+ // the chance for the CAS issue to manifest.
+ size_t start = (numBits * (data->numThreads - data->id)) / data->numThreads;
+
+ printf(" started Thread %d\n", data->id);
+ for (size_t i = start; i < numBits; i++)
+ while (!bitmap->concurrentTestAndSet(i)) { }
+ for (size_t i = 0; i < start; i++)
+ while (!bitmap->concurrentTestAndSet(i)) { }
+
+ printf(" finished Thread %d\n", data->id);
+}
+
+void testCompareAndSwap()
+{
+ Bitmap bitmap;
+ const int numThreads = 5;
+ ThreadIdentifier threadIDs[numThreads];
+ Data data[numThreads];
+
+ WTF::initializeThreading();
+
+ printf("Starting %d threads for CompareAndSwap test. Test should complete without hanging.\n", numThreads);
+ for (int i = 0; i < numThreads; i++) {
+ data[i].bitmap = &bitmap;
+ data[i].id = i;
+ data[i].numThreads = numThreads;
+ std::function<void()> threadFunc = std::bind(setBitThreadFunc, &data[i]);
+ threadIDs[i] = createThread("setBitThreadFunc", threadFunc);
+ }
+
+ printf("Waiting for %d threads to join\n", numThreads);
+ for (int i = 0; i < numThreads; i++)
+ waitForThreadCompletion(threadIDs[i]);
+
+ printf("PASS: CompareAndSwap test completed without a hang\n");
+}
diff --git a/Source/JavaScriptCore/API/tests/CompareAndSwapTest.h b/Source/JavaScriptCore/API/tests/CompareAndSwapTest.h
new file mode 100644
index 000000000..73fa0de13
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/CompareAndSwapTest.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CompareAndSwapTest_h
+#define CompareAndSwapTest_h
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Regression test for webkit.org/b/142513 */
+void testCompareAndSwap();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* CompareAndSwapTest_h */
diff --git a/Source/JavaScriptCore/API/tests/CurrentThisInsideBlockGetterTest.h b/Source/JavaScriptCore/API/tests/CurrentThisInsideBlockGetterTest.h
new file mode 100644
index 000000000..f228333c4
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/CurrentThisInsideBlockGetterTest.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CurrentThisInsideBlockGetterTest_h
+#define CurrentThisInsideBlockGetterTest_h
+
+#include <JavaScriptCore/JavaScriptCore.h>
+
+#if JSC_OBJC_API_ENABLED
+
+void currentThisInsideBlockGetterTest();
+
+#endif // JSC_OBJC_API_ENABLED
+
+
+#endif // CurrentThisInsideBlockGetterTest_h
diff --git a/Source/JavaScriptCore/API/tests/CustomGlobalObjectClassTest.c b/Source/JavaScriptCore/API/tests/CustomGlobalObjectClassTest.c
new file mode 100644
index 000000000..62e63978e
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/CustomGlobalObjectClassTest.c
@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2014 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "CustomGlobalObjectClassTest.h"
+
+#include <JavaScriptCore/JSObjectRefPrivate.h>
+#include <JavaScriptCore/JavaScriptCore.h>
+#include <stdio.h>
+
+extern bool assertTrue(bool value, const char* message);
+
+static bool executedCallback = false;
+
+static JSValueRef jsDoSomething(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef args[], JSValueRef* exception)
+{
+ (void)function;
+ (void)thisObject;
+ (void)argc;
+ (void)args;
+ (void)exception;
+ executedCallback = true;
+ return JSValueMakeNull(ctx);
+}
+
+static JSStaticFunction bridgedFunctions[] = {
+ {"doSomething", jsDoSomething, kJSPropertyAttributeDontDelete},
+ {0, 0, 0},
+};
+
+static JSClassRef bridgedObjectClass = NULL;
+static JSClassDefinition bridgedClassDef;
+
+static JSClassRef jsClassRef()
+{
+ if (!bridgedObjectClass) {
+ bridgedClassDef = kJSClassDefinitionEmpty;
+ bridgedClassDef.className = "BridgedObject";
+ bridgedClassDef.staticFunctions = bridgedFunctions;
+ bridgedObjectClass = JSClassCreate(&bridgedClassDef);
+ }
+ return bridgedObjectClass;
+}
+
+void customGlobalObjectClassTest()
+{
+ JSClassRef bridgedObjectJsClassRef = jsClassRef();
+ JSGlobalContextRef globalContext = JSGlobalContextCreate(bridgedObjectJsClassRef);
+
+ JSObjectRef globalObj = JSContextGetGlobalObject(globalContext);
+
+ JSPropertyNameArrayRef propertyNames = JSObjectCopyPropertyNames(globalContext, globalObj);
+ size_t propertyCount = JSPropertyNameArrayGetCount(propertyNames);
+ assertTrue(propertyCount == 1, "Property count == 1");
+
+ JSStringRef propertyNameRef = JSPropertyNameArrayGetNameAtIndex(propertyNames, 0);
+ size_t propertyNameLength = JSStringGetLength(propertyNameRef);
+ size_t bufferSize = sizeof(char) * (propertyNameLength + 1);
+ char* buffer = (char*)malloc(bufferSize);
+ JSStringGetUTF8CString(propertyNameRef, buffer, bufferSize);
+ buffer[propertyNameLength] = '\0';
+ assertTrue(!strncmp(buffer, "doSomething", propertyNameLength), "First property name is doSomething");
+ free(buffer);
+
+ bool hasMethod = JSObjectHasProperty(globalContext, globalObj, propertyNameRef);
+ assertTrue(hasMethod, "Property found by name");
+
+ JSValueRef doSomethingProperty =
+ JSObjectGetProperty(globalContext, globalObj, propertyNameRef, NULL);
+ assertTrue(!JSValueIsUndefined(globalContext, doSomethingProperty), "Property is defined");
+
+ bool globalObjectClassMatchesClassRef = JSValueIsObjectOfClass(globalContext, globalObj, bridgedObjectJsClassRef);
+ assertTrue(globalObjectClassMatchesClassRef, "Global object is the right class");
+
+ JSStringRef script = JSStringCreateWithUTF8CString("doSomething();");
+ JSEvaluateScript(globalContext, script, NULL, NULL, 1, NULL);
+ JSStringRelease(script);
+
+ assertTrue(executedCallback, "Executed custom global object callback");
+}
+
+void globalObjectSetPrototypeTest()
+{
+ JSClassDefinition definition = kJSClassDefinitionEmpty;
+ definition.className = "Global";
+ JSClassRef global = JSClassCreate(&definition);
+ JSGlobalContextRef context = JSGlobalContextCreate(global);
+ JSObjectRef object = JSContextGetGlobalObject(context);
+
+ JSObjectRef above = JSObjectMake(context, 0, 0);
+ JSStringRef test = JSStringCreateWithUTF8CString("test");
+ JSValueRef value = JSValueMakeString(context, test);
+ JSObjectSetProperty(context, above, test, value, kJSPropertyAttributeDontEnum, 0);
+
+ JSObjectSetPrototype(context, object, above);
+ JSStringRef script = JSStringCreateWithUTF8CString("test === \"test\"");
+ JSValueRef result = JSEvaluateScript(context, script, 0, 0, 0, 0);
+
+ assertTrue(JSValueToBoolean(context, result), "test === \"test\"");
+
+ JSStringRelease(test);
+ JSStringRelease(script);
+}
+
+void globalObjectPrivatePropertyTest()
+{
+ JSClassDefinition definition = kJSClassDefinitionEmpty;
+ definition.className = "Global";
+ JSClassRef global = JSClassCreate(&definition);
+ JSGlobalContextRef context = JSGlobalContextCreate(global);
+ JSObjectRef globalObject = JSContextGetGlobalObject(context);
+
+ JSStringRef privateName = JSStringCreateWithUTF8CString("private");
+ JSValueRef privateValue = JSValueMakeString(context, privateName);
+ assertTrue(JSObjectSetPrivateProperty(context, globalObject, privateName, privateValue), "JSObjectSetPrivateProperty succeeded");
+ JSValueRef result = JSObjectGetPrivateProperty(context, globalObject, privateName);
+ assertTrue(JSValueIsStrictEqual(context, privateValue, result), "privateValue === \"private\"");
+
+ assertTrue(JSObjectDeletePrivateProperty(context, globalObject, privateName), "JSObjectDeletePrivateProperty succeeded");
+ result = JSObjectGetPrivateProperty(context, globalObject, privateName);
+ assertTrue(JSValueIsNull(context, result), "Deleted private property is indeed no longer present");
+
+ JSStringRelease(privateName);
+}
diff --git a/Source/JavaScriptCore/API/tests/CustomGlobalObjectClassTest.h b/Source/JavaScriptCore/API/tests/CustomGlobalObjectClassTest.h
new file mode 100644
index 000000000..86914ca6f
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/CustomGlobalObjectClassTest.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2014 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomGlobalObjectClassTest_h
+#define CustomGlobalObjectClassTest_h
+
+void customGlobalObjectClassTest(void);
+void globalObjectSetPrototypeTest(void);
+void globalObjectPrivatePropertyTest(void);
+
+#endif // CustomGlobalObjectClassTest_h
diff --git a/Source/JavaScriptCore/API/tests/DateTests.h b/Source/JavaScriptCore/API/tests/DateTests.h
new file mode 100644
index 000000000..eeb47a165
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/DateTests.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2014 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <JavaScriptCore/JavaScriptCore.h>
+
+#if JSC_OBJC_API_ENABLED
+
+void runDateTests();
+
+#endif // JSC_OBJC_API_ENABLED
diff --git a/Source/JavaScriptCore/API/tests/ExecutionTimeLimitTest.cpp b/Source/JavaScriptCore/API/tests/ExecutionTimeLimitTest.cpp
new file mode 100644
index 000000000..4ecac8ec3
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/ExecutionTimeLimitTest.cpp
@@ -0,0 +1,332 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "ExecutionTimeLimitTest.h"
+
+#include "InitializeThreading.h"
+#include "JSContextRefPrivate.h"
+#include "JavaScriptCore.h"
+#include "Options.h"
+#include <chrono>
+#include <wtf/CurrentTime.h>
+#include <wtf/text/StringBuilder.h>
+
+using namespace std::chrono;
+using JSC::Options;
+
+static JSGlobalContextRef context = nullptr;
+
+static JSValueRef currentCPUTimeAsJSFunctionCallback(JSContextRef ctx, JSObjectRef functionObject, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(functionObject);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ UNUSED_PARAM(exception);
+
+ ASSERT(JSContextGetGlobalContext(ctx) == context);
+ return JSValueMakeNumber(ctx, currentCPUTime().count() / 1000000.);
+}
+
+bool shouldTerminateCallbackWasCalled = false;
+static bool shouldTerminateCallback(JSContextRef, void*)
+{
+ shouldTerminateCallbackWasCalled = true;
+ return true;
+}
+
+bool cancelTerminateCallbackWasCalled = false;
+static bool cancelTerminateCallback(JSContextRef, void*)
+{
+ cancelTerminateCallbackWasCalled = true;
+ return false;
+}
+
+int extendTerminateCallbackCalled = 0;
+static bool extendTerminateCallback(JSContextRef ctx, void*)
+{
+ extendTerminateCallbackCalled++;
+ if (extendTerminateCallbackCalled == 1) {
+ JSContextGroupRef contextGroup = JSContextGetGroup(ctx);
+ JSContextGroupSetExecutionTimeLimit(contextGroup, .200f, extendTerminateCallback, 0);
+ return false;
+ }
+ return true;
+}
+
+struct TierOptions {
+ const char* tier;
+ unsigned timeLimitAdjustmentMillis;
+ const char* optionsStr;
+};
+
+static void testResetAfterTimeout(bool& failed)
+{
+ JSValueRef v = nullptr;
+ JSValueRef exception = nullptr;
+ const char* reentryScript = "100";
+ JSStringRef script = JSStringCreateWithUTF8CString(reentryScript);
+ v = JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
+ if (exception) {
+ printf("FAIL: Watchdog timeout was not reset.\n");
+ failed = true;
+ } else if (!JSValueIsNumber(context, v) || JSValueToNumber(context, v, nullptr) != 100) {
+ printf("FAIL: Script result is not as expected.\n");
+ failed = true;
+ }
+}
+
+int testExecutionTimeLimit()
+{
+ static const TierOptions tierOptionsList[] = {
+ { "LLINT", 0, "--enableConcurrentJIT=false --useLLInt=true --useJIT=false" },
+ { "Baseline", 0, "--enableConcurrentJIT=false --useLLInt=true --useJIT=true --useDFGJIT=false" },
+ { "DFG", 0, "--enableConcurrentJIT=false --useLLInt=true --useJIT=true --useDFGJIT=true --useFTLJIT=false" },
+ { "FTL", 200, "--enableConcurrentJIT=false --useLLInt=true --useJIT=true --useDFGJIT=true --useFTLJIT=true" },
+ };
+
+ bool failed = false;
+
+ JSC::initializeThreading();
+ Options::initialize(); // Ensure options is initialized first.
+
+ for (auto tierOptions : tierOptionsList) {
+ StringBuilder savedOptionsBuilder;
+ Options::dumpAllOptionsInALine(savedOptionsBuilder);
+
+ Options::setOptions(tierOptions.optionsStr);
+
+ unsigned tierAdjustmentMillis = tierOptions.timeLimitAdjustmentMillis;
+ double timeLimit;
+
+ context = JSGlobalContextCreateInGroup(nullptr, nullptr);
+
+ JSContextGroupRef contextGroup = JSContextGetGroup(context);
+ JSObjectRef globalObject = JSContextGetGlobalObject(context);
+ ASSERT(JSValueIsObject(context, globalObject));
+
+ JSValueRef scriptResult = nullptr;
+ JSValueRef exception = nullptr;
+
+ JSStringRef currentCPUTimeStr = JSStringCreateWithUTF8CString("currentCPUTime");
+ JSObjectRef currentCPUTimeFunction = JSObjectMakeFunctionWithCallback(context, currentCPUTimeStr, currentCPUTimeAsJSFunctionCallback);
+ JSObjectSetProperty(context, globalObject, currentCPUTimeStr, currentCPUTimeFunction, kJSPropertyAttributeNone, nullptr);
+ JSStringRelease(currentCPUTimeStr);
+
+ /* Test script timeout: */
+ timeLimit = (100 + tierAdjustmentMillis) / 1000.0;
+ JSContextGroupSetExecutionTimeLimit(contextGroup, timeLimit, shouldTerminateCallback, 0);
+ {
+ unsigned timeAfterWatchdogShouldHaveFired = 150 + tierAdjustmentMillis;
+
+ StringBuilder scriptBuilder;
+ scriptBuilder.append("function foo() { var startTime = currentCPUTime(); while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
+ scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
+ scriptBuilder.append(") break; } } foo();");
+
+ JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
+ exception = nullptr;
+ shouldTerminateCallbackWasCalled = false;
+ auto startTime = currentCPUTime();
+ scriptResult = JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
+ auto endTime = currentCPUTime();
+
+ if (((endTime - startTime) < milliseconds(timeAfterWatchdogShouldHaveFired)) && shouldTerminateCallbackWasCalled)
+ printf("PASS: %s script timed out as expected.\n", tierOptions.tier);
+ else {
+ if ((endTime - startTime) >= milliseconds(timeAfterWatchdogShouldHaveFired))
+ printf("FAIL: %s script did not time out as expected.\n", tierOptions.tier);
+ if (!shouldTerminateCallbackWasCalled)
+ printf("FAIL: %s script timeout callback was not called.\n", tierOptions.tier);
+ failed = true;
+ }
+
+ if (!exception) {
+ printf("FAIL: %s TerminatedExecutionException was not thrown.\n", tierOptions.tier);
+ failed = true;
+ }
+
+ testResetAfterTimeout(failed);
+ }
+
+ /* Test the script timeout's TerminatedExecutionException should NOT be catchable: */
+ timeLimit = (100 + tierAdjustmentMillis) / 1000.0;
+ JSContextGroupSetExecutionTimeLimit(contextGroup, timeLimit, shouldTerminateCallback, 0);
+ {
+ unsigned timeAfterWatchdogShouldHaveFired = 150 + tierAdjustmentMillis;
+
+ StringBuilder scriptBuilder;
+ scriptBuilder.append("function foo() { var startTime = currentCPUTime(); try { while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
+ scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
+ scriptBuilder.append(") break; } } catch(e) { } } foo();");
+
+ JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
+ exception = nullptr;
+ shouldTerminateCallbackWasCalled = false;
+
+ auto startTime = currentCPUTime();
+ scriptResult = JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
+ auto endTime = currentCPUTime();
+
+ if (((endTime - startTime) >= milliseconds(timeAfterWatchdogShouldHaveFired)) || !shouldTerminateCallbackWasCalled) {
+ if (!((endTime - startTime) < milliseconds(timeAfterWatchdogShouldHaveFired)))
+ printf("FAIL: %s script did not time out as expected.\n", tierOptions.tier);
+ if (!shouldTerminateCallbackWasCalled)
+ printf("FAIL: %s script timeout callback was not called.\n", tierOptions.tier);
+ failed = true;
+ }
+
+ if (exception)
+ printf("PASS: %s TerminatedExecutionException was not catchable as expected.\n", tierOptions.tier);
+ else {
+ printf("FAIL: %s TerminatedExecutionException was caught.\n", tierOptions.tier);
+ failed = true;
+ }
+
+ testResetAfterTimeout(failed);
+ }
+
+ /* Test script timeout with no callback: */
+ timeLimit = (100 + tierAdjustmentMillis) / 1000.0;
+ JSContextGroupSetExecutionTimeLimit(contextGroup, timeLimit, 0, 0);
+ {
+ unsigned timeAfterWatchdogShouldHaveFired = 150 + tierAdjustmentMillis;
+
+ StringBuilder scriptBuilder;
+ scriptBuilder.append("function foo() { var startTime = currentCPUTime(); while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
+ scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
+ scriptBuilder.append(") break; } } foo();");
+
+ JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
+ exception = nullptr;
+ shouldTerminateCallbackWasCalled = false;
+
+ auto startTime = currentCPUTime();
+ scriptResult = JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
+ auto endTime = currentCPUTime();
+
+ if (((endTime - startTime) < milliseconds(timeAfterWatchdogShouldHaveFired)) && !shouldTerminateCallbackWasCalled)
+ printf("PASS: %s script timed out as expected when no callback is specified.\n", tierOptions.tier);
+ else {
+ if ((endTime - startTime) >= milliseconds(timeAfterWatchdogShouldHaveFired))
+ printf("FAIL: %s script did not time out as expected when no callback is specified.\n", tierOptions.tier);
+ else
+ printf("FAIL: %s script called stale callback function.\n", tierOptions.tier);
+ failed = true;
+ }
+
+ if (!exception) {
+ printf("FAIL: %s TerminatedExecutionException was not thrown.\n", tierOptions.tier);
+ failed = true;
+ }
+
+ testResetAfterTimeout(failed);
+ }
+
+ /* Test script timeout cancellation: */
+ timeLimit = (100 + tierAdjustmentMillis) / 1000.0;
+ JSContextGroupSetExecutionTimeLimit(contextGroup, timeLimit, cancelTerminateCallback, 0);
+ {
+ unsigned timeAfterWatchdogShouldHaveFired = 150 + tierAdjustmentMillis;
+
+ StringBuilder scriptBuilder;
+ scriptBuilder.append("function foo() { var startTime = currentCPUTime(); while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
+ scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
+ scriptBuilder.append(") break; } } foo();");
+
+ JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
+ exception = nullptr;
+ cancelTerminateCallbackWasCalled = false;
+
+ auto startTime = currentCPUTime();
+ scriptResult = JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
+ auto endTime = currentCPUTime();
+
+ if (((endTime - startTime) >= milliseconds(timeAfterWatchdogShouldHaveFired)) && cancelTerminateCallbackWasCalled && !exception)
+ printf("PASS: %s script timeout was cancelled as expected.\n", tierOptions.tier);
+ else {
+ if (((endTime - startTime) < milliseconds(timeAfterWatchdogShouldHaveFired)) || exception)
+ printf("FAIL: %s script timeout was not cancelled.\n", tierOptions.tier);
+ if (!cancelTerminateCallbackWasCalled)
+ printf("FAIL: %s script timeout callback was not called.\n", tierOptions.tier);
+ failed = true;
+ }
+
+ if (exception) {
+ printf("FAIL: %s Unexpected TerminatedExecutionException thrown.\n", tierOptions.tier);
+ failed = true;
+ }
+ }
+
+ /* Test script timeout extension: */
+ timeLimit = (100 + tierAdjustmentMillis) / 1000.0;
+ JSContextGroupSetExecutionTimeLimit(contextGroup, timeLimit, extendTerminateCallback, 0);
+ {
+ unsigned timeBeforeExtendedDeadline = 200 + tierAdjustmentMillis;
+ unsigned timeAfterExtendedDeadline = 400 + tierAdjustmentMillis;
+ unsigned maxBusyLoopTime = 600 + tierAdjustmentMillis;
+
+ StringBuilder scriptBuilder;
+ scriptBuilder.append("function foo() { var startTime = currentCPUTime(); while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
+ scriptBuilder.appendNumber(maxBusyLoopTime / 1000.0); // in seconds.
+ scriptBuilder.append(") break; } } foo();");
+
+ JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
+ exception = nullptr;
+ extendTerminateCallbackCalled = 0;
+
+ auto startTime = currentCPUTime();
+ scriptResult = JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
+ auto endTime = currentCPUTime();
+ auto deltaTime = endTime - startTime;
+
+ if ((deltaTime >= milliseconds(timeBeforeExtendedDeadline)) && (deltaTime < milliseconds(timeAfterExtendedDeadline)) && (extendTerminateCallbackCalled == 2) && exception)
+ printf("PASS: %s script timeout was extended as expected.\n", tierOptions.tier);
+ else {
+ if (deltaTime < milliseconds(timeBeforeExtendedDeadline))
+ printf("FAIL: %s script timeout was not extended as expected.\n", tierOptions.tier);
+ else if (deltaTime >= milliseconds(timeAfterExtendedDeadline))
+ printf("FAIL: %s script did not timeout.\n", tierOptions.tier);
+
+ if (extendTerminateCallbackCalled < 1)
+ printf("FAIL: %s script timeout callback was not called.\n", tierOptions.tier);
+ if (extendTerminateCallbackCalled < 2)
+ printf("FAIL: %s script timeout callback was not called after timeout extension.\n", tierOptions.tier);
+
+ if (!exception)
+ printf("FAIL: %s TerminatedExecutionException was not thrown during timeout extension test.\n", tierOptions.tier);
+
+ failed = true;
+ }
+ }
+
+ JSGlobalContextRelease(context);
+
+ Options::setOptions(savedOptionsBuilder.toString().ascii().data());
+ }
+
+ return failed;
+}
diff --git a/Source/JavaScriptCore/API/tests/ExecutionTimeLimitTest.h b/Source/JavaScriptCore/API/tests/ExecutionTimeLimitTest.h
new file mode 100644
index 000000000..8294a86a6
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/ExecutionTimeLimitTest.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ExecutionTimeLimitTest_h
+#define ExecutionTimeLimitTest_h
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Returns 1 if failures were encountered. Else, returns 0. */
+int testExecutionTimeLimit();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* ExecutionTimeLimitTest_h */
diff --git a/Source/JavaScriptCore/API/tests/GlobalContextWithFinalizerTest.cpp b/Source/JavaScriptCore/API/tests/GlobalContextWithFinalizerTest.cpp
new file mode 100644
index 000000000..7023bc365
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/GlobalContextWithFinalizerTest.cpp
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "GlobalContextWithFinalizerTest.h"
+
+#include "JavaScriptCore.h"
+#include <wtf/DataLog.h>
+
+static bool failed = true;
+
+static void finalize(JSObjectRef)
+{
+ failed = false;
+}
+
+int testGlobalContextWithFinalizer()
+{
+ JSClassDefinition def = kJSClassDefinitionEmpty;
+ def.className = "testClass";
+ def.finalize = finalize;
+ JSClassRef classRef = JSClassCreate(&def);
+
+ JSGlobalContextRef ref = JSGlobalContextCreateInGroup(nullptr, classRef);
+ JSGlobalContextRelease(ref);
+ JSClassRelease(classRef);
+
+ if (failed)
+ printf("FAIL: JSGlobalContextRef did not call its JSClassRef finalizer.\n");
+ else
+ printf("PASS: JSGlobalContextRef called its JSClassRef finalizer as expected.\n");
+
+ return failed;
+}
diff --git a/Source/JavaScriptCore/API/tests/GlobalContextWithFinalizerTest.h b/Source/JavaScriptCore/API/tests/GlobalContextWithFinalizerTest.h
new file mode 100644
index 000000000..55b439fff
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/GlobalContextWithFinalizerTest.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef GlobalContextWithFinalizerTest_h
+#define GlobalContextWithFinalizerTest_h
+
+#include "JSContextRefPrivate.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Returns 1 if failures were encountered. Else, returns 0. */
+int testGlobalContextWithFinalizer();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* GlobalContextWithFinalizerTest_h */
diff --git a/Source/JavaScriptCore/API/tests/JSExportTests.h b/Source/JavaScriptCore/API/tests/JSExportTests.h
new file mode 100644
index 000000000..9d501ee7e
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/JSExportTests.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2014 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Foundation/Foundation.h>
+#import <JavaScriptCore/JavaScriptCore.h>
+
+#if JSC_OBJC_API_ENABLED
+
+void runJSExportTests();
+
+#endif // JSC_OBJC_API_ENABLED
+
diff --git a/Source/JavaScriptCore/API/tests/JSNode.c b/Source/JavaScriptCore/API/tests/JSNode.c
new file mode 100644
index 000000000..d0a0dc3ec
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/JSNode.c
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <wtf/Platform.h>
+
+#include "JSNode.h"
+#include "JSNodeList.h"
+#include "JSObjectRef.h"
+#include "JSStringRef.h"
+#include "JSValueRef.h"
+#include "Node.h"
+#include "NodeList.h"
+#include <wtf/Assertions.h>
+
+static JSValueRef JSNode_appendChild(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(function);
+
+ /* Example of throwing a type error for invalid values */
+ if (!JSValueIsObjectOfClass(context, thisObject, JSNode_class(context))) {
+ JSStringRef message = JSStringCreateWithUTF8CString("TypeError: appendChild can only be called on nodes");
+ *exception = JSValueMakeString(context, message);
+ JSStringRelease(message);
+ } else if (argumentCount < 1 || !JSValueIsObjectOfClass(context, arguments[0], JSNode_class(context))) {
+ JSStringRef message = JSStringCreateWithUTF8CString("TypeError: first argument to appendChild must be a node");
+ *exception = JSValueMakeString(context, message);
+ JSStringRelease(message);
+ } else {
+ Node* node = JSObjectGetPrivate(thisObject);
+ Node* child = JSObjectGetPrivate(JSValueToObject(context, arguments[0], NULL));
+
+ Node_appendChild(node, child);
+ }
+
+ return JSValueMakeUndefined(context);
+}
+
+static JSValueRef JSNode_removeChild(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(function);
+
+ /* Example of ignoring invalid values */
+ if (argumentCount > 0) {
+ if (JSValueIsObjectOfClass(context, thisObject, JSNode_class(context))) {
+ if (JSValueIsObjectOfClass(context, arguments[0], JSNode_class(context))) {
+ Node* node = JSObjectGetPrivate(thisObject);
+ Node* child = JSObjectGetPrivate(JSValueToObject(context, arguments[0], exception));
+
+ Node_removeChild(node, child);
+ }
+ }
+ }
+
+ return JSValueMakeUndefined(context);
+}
+
+static JSValueRef JSNode_replaceChild(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(function);
+
+ if (argumentCount > 1) {
+ if (JSValueIsObjectOfClass(context, thisObject, JSNode_class(context))) {
+ if (JSValueIsObjectOfClass(context, arguments[0], JSNode_class(context))) {
+ if (JSValueIsObjectOfClass(context, arguments[1], JSNode_class(context))) {
+ Node* node = JSObjectGetPrivate(thisObject);
+ Node* newChild = JSObjectGetPrivate(JSValueToObject(context, arguments[0], exception));
+ Node* oldChild = JSObjectGetPrivate(JSValueToObject(context, arguments[1], exception));
+
+ Node_replaceChild(node, newChild, oldChild);
+ }
+ }
+ }
+ }
+
+ return JSValueMakeUndefined(context);
+}
+
+static JSStaticFunction JSNode_staticFunctions[] = {
+ { "appendChild", JSNode_appendChild, kJSPropertyAttributeDontDelete },
+ { "removeChild", JSNode_removeChild, kJSPropertyAttributeDontDelete },
+ { "replaceChild", JSNode_replaceChild, kJSPropertyAttributeDontDelete },
+ { 0, 0, 0 }
+};
+
+static JSValueRef JSNode_getNodeType(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(exception);
+
+ Node* node = JSObjectGetPrivate(object);
+ if (node) {
+ JSStringRef nodeType = JSStringCreateWithUTF8CString(node->nodeType);
+ JSValueRef value = JSValueMakeString(context, nodeType);
+ JSStringRelease(nodeType);
+ return value;
+ }
+
+ return NULL;
+}
+
+static JSValueRef JSNode_getChildNodes(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(exception);
+
+ Node* node = JSObjectGetPrivate(thisObject);
+ ASSERT(node);
+ return JSNodeList_new(context, NodeList_new(node));
+}
+
+static JSValueRef JSNode_getFirstChild(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(exception);
+
+ return JSValueMakeUndefined(context);
+}
+
+static JSStaticValue JSNode_staticValues[] = {
+ { "nodeType", JSNode_getNodeType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+ { "childNodes", JSNode_getChildNodes, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+ { "firstChild", JSNode_getFirstChild, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+ { 0, 0, 0, 0 }
+};
+
+static void JSNode_initialize(JSContextRef context, JSObjectRef object)
+{
+ UNUSED_PARAM(context);
+
+ Node* node = JSObjectGetPrivate(object);
+ ASSERT(node);
+
+ Node_ref(node);
+}
+
+static void JSNode_finalize(JSObjectRef object)
+{
+ Node* node = JSObjectGetPrivate(object);
+ ASSERT(node);
+
+ Node_deref(node);
+}
+
+JSClassRef JSNode_class(JSContextRef context)
+{
+ UNUSED_PARAM(context);
+
+ static JSClassRef jsClass;
+ if (!jsClass) {
+ JSClassDefinition definition = kJSClassDefinitionEmpty;
+ definition.staticValues = JSNode_staticValues;
+ definition.staticFunctions = JSNode_staticFunctions;
+ definition.initialize = JSNode_initialize;
+ definition.finalize = JSNode_finalize;
+
+ jsClass = JSClassCreate(&definition);
+ }
+ return jsClass;
+}
+
+JSObjectRef JSNode_new(JSContextRef context, Node* node)
+{
+ return JSObjectMake(context, JSNode_class(context), node);
+}
+
+JSObjectRef JSNode_construct(JSContextRef context, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ UNUSED_PARAM(exception);
+
+ return JSNode_new(context, Node_new());
+}
diff --git a/Source/JavaScriptCore/API/tests/JSNode.h b/Source/JavaScriptCore/API/tests/JSNode.h
new file mode 100644
index 000000000..a6aee2f7b
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/JSNode.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSNode_h
+#define JSNode_h
+
+#include "JSBase.h"
+#include "Node.h"
+#include <stddef.h>
+
+extern JSObjectRef JSNode_new(JSContextRef context, Node* node);
+extern JSClassRef JSNode_class(JSContextRef context);
+extern JSObjectRef JSNode_construct(JSContextRef context, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
+
+#endif /* JSNode_h */
diff --git a/Source/JavaScriptCore/API/tests/JSNodeList.c b/Source/JavaScriptCore/API/tests/JSNodeList.c
new file mode 100644
index 000000000..f037e094a
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/JSNodeList.c
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <wtf/Platform.h>
+
+#include "JSNode.h"
+#include "JSNodeList.h"
+#include "JSObjectRef.h"
+#include "JSValueRef.h"
+#include <wtf/Assertions.h>
+
+static JSValueRef JSNodeList_item(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+
+ if (argumentCount > 0) {
+ NodeList* nodeList = JSObjectGetPrivate(thisObject);
+ ASSERT(nodeList);
+ Node* node = NodeList_item(nodeList, (unsigned)JSValueToNumber(context, arguments[0], exception));
+ if (node)
+ return JSNode_new(context, node);
+ }
+
+ return JSValueMakeUndefined(context);
+}
+
+static JSStaticFunction JSNodeList_staticFunctions[] = {
+ { "item", JSNodeList_item, kJSPropertyAttributeDontDelete },
+ { 0, 0, 0 }
+};
+
+static JSValueRef JSNodeList_length(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(exception);
+
+ NodeList* nodeList = JSObjectGetPrivate(thisObject);
+ ASSERT(nodeList);
+ return JSValueMakeNumber(context, NodeList_length(nodeList));
+}
+
+static JSStaticValue JSNodeList_staticValues[] = {
+ { "length", JSNodeList_length, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
+ { 0, 0, 0, 0 }
+};
+
+static JSValueRef JSNodeList_getProperty(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception)
+{
+ NodeList* nodeList = JSObjectGetPrivate(thisObject);
+ ASSERT(nodeList);
+ double index = JSValueToNumber(context, JSValueMakeString(context, propertyName), exception);
+ unsigned uindex = (unsigned)index;
+ if (uindex == index) { /* false for NaN */
+ Node* node = NodeList_item(nodeList, uindex);
+ if (node)
+ return JSNode_new(context, node);
+ }
+
+ return NULL;
+}
+
+static void JSNodeList_initialize(JSContextRef context, JSObjectRef thisObject)
+{
+ UNUSED_PARAM(context);
+
+ NodeList* nodeList = JSObjectGetPrivate(thisObject);
+ ASSERT(nodeList);
+
+ NodeList_ref(nodeList);
+}
+
+static void JSNodeList_finalize(JSObjectRef thisObject)
+{
+ NodeList* nodeList = JSObjectGetPrivate(thisObject);
+ ASSERT(nodeList);
+
+ NodeList_deref(nodeList);
+}
+
+static JSClassRef JSNodeList_class(JSContextRef context)
+{
+ UNUSED_PARAM(context);
+
+ static JSClassRef jsClass;
+ if (!jsClass) {
+ JSClassDefinition definition = kJSClassDefinitionEmpty;
+ definition.staticValues = JSNodeList_staticValues;
+ definition.staticFunctions = JSNodeList_staticFunctions;
+ definition.getProperty = JSNodeList_getProperty;
+ definition.initialize = JSNodeList_initialize;
+ definition.finalize = JSNodeList_finalize;
+
+ jsClass = JSClassCreate(&definition);
+ }
+
+ return jsClass;
+}
+
+JSObjectRef JSNodeList_new(JSContextRef context, NodeList* nodeList)
+{
+ return JSObjectMake(context, JSNodeList_class(context), nodeList);
+}
diff --git a/Source/JavaScriptCore/API/tests/JSNodeList.h b/Source/JavaScriptCore/API/tests/JSNodeList.h
new file mode 100644
index 000000000..d3eb52bb9
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/JSNodeList.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSNodeList_h
+#define JSNodeList_h
+
+#include "JSBase.h"
+#include "NodeList.h"
+
+extern JSObjectRef JSNodeList_new(JSContextRef, NodeList*);
+
+#endif /* JSNodeList_h */
diff --git a/Source/JavaScriptCore/API/tests/Node.c b/Source/JavaScriptCore/API/tests/Node.c
new file mode 100644
index 000000000..db687e952
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/Node.c
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "Node.h"
+#include <stddef.h>
+#include <stdlib.h>
+
+Node* Node_new(void)
+{
+ Node* node = (Node*)malloc(sizeof(Node));
+ node->refCount = 0;
+ node->nodeType = "Node";
+ node->childNodesTail = NULL;
+
+ return node;
+}
+
+void Node_appendChild(Node* node, Node* child)
+{
+ Node_ref(child);
+ NodeLink* nodeLink = (NodeLink*)malloc(sizeof(NodeLink));
+ nodeLink->node = child;
+ nodeLink->prev = node->childNodesTail;
+ node->childNodesTail = nodeLink;
+}
+
+void Node_removeChild(Node* node, Node* child)
+{
+ /* Linear search from tail -- good enough for our purposes here */
+ NodeLink* current;
+ NodeLink** currentHandle;
+ for (currentHandle = &node->childNodesTail, current = *currentHandle; current; currentHandle = &current->prev, current = *currentHandle) {
+ if (current->node == child) {
+ Node_deref(current->node);
+ *currentHandle = current->prev;
+ free(current);
+ break;
+ }
+ }
+}
+
+void Node_replaceChild(Node* node, Node* newChild, Node* oldChild)
+{
+ /* Linear search from tail -- good enough for our purposes here */
+ NodeLink* current;
+ for (current = node->childNodesTail; current; current = current->prev) {
+ if (current->node == oldChild) {
+ Node_deref(current->node);
+ current->node = newChild;
+ }
+ }
+}
+
+void Node_ref(Node* node)
+{
+ ++node->refCount;
+}
+
+void Node_deref(Node* node)
+{
+ if (--node->refCount == 0)
+ free(node);
+}
diff --git a/Source/JavaScriptCore/API/tests/Node.h b/Source/JavaScriptCore/API/tests/Node.h
new file mode 100644
index 000000000..41b5d493a
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/Node.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef Node_h
+#define Node_h
+
+typedef struct __Node Node;
+typedef struct __NodeLink NodeLink;
+
+struct __NodeLink {
+ Node* node;
+ NodeLink* prev;
+};
+
+struct __Node {
+ unsigned refCount;
+ const char* nodeType;
+ NodeLink* childNodesTail;
+};
+
+extern Node* Node_new(void);
+extern void Node_ref(Node* node);
+extern void Node_deref(Node* node);
+extern void Node_appendChild(Node* node, Node* child);
+extern void Node_removeChild(Node* node, Node* child);
+extern void Node_replaceChild(Node* node, Node* newChild, Node* oldChild);
+
+#endif /* Node_h */
diff --git a/Source/JavaScriptCore/API/tests/NodeList.c b/Source/JavaScriptCore/API/tests/NodeList.c
new file mode 100644
index 000000000..69f4cd5c4
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/NodeList.c
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "NodeList.h"
+
+#include <stdlib.h>
+
+extern NodeList* NodeList_new(Node* parentNode)
+{
+ Node_ref(parentNode);
+
+ NodeList* nodeList = (NodeList*)malloc(sizeof(NodeList));
+ nodeList->parentNode = parentNode;
+ nodeList->refCount = 0;
+ return nodeList;
+}
+
+extern unsigned NodeList_length(NodeList* nodeList)
+{
+ /* Linear count from tail -- good enough for our purposes here */
+ unsigned i = 0;
+ NodeLink* n = nodeList->parentNode->childNodesTail;
+ while (n) {
+ n = n->prev;
+ ++i;
+ }
+
+ return i;
+}
+
+extern Node* NodeList_item(NodeList* nodeList, unsigned index)
+{
+ unsigned length = NodeList_length(nodeList);
+ if (index >= length)
+ return NULL;
+
+ /* Linear search from tail -- good enough for our purposes here */
+ NodeLink* n = nodeList->parentNode->childNodesTail;
+ unsigned i = 0;
+ unsigned count = length - 1 - index;
+ while (i < count) {
+ ++i;
+ n = n->prev;
+ }
+ return n->node;
+}
+
+extern void NodeList_ref(NodeList* nodeList)
+{
+ ++nodeList->refCount;
+}
+
+extern void NodeList_deref(NodeList* nodeList)
+{
+ if (--nodeList->refCount == 0) {
+ Node_deref(nodeList->parentNode);
+ free(nodeList);
+ }
+}
diff --git a/Source/JavaScriptCore/API/tests/NodeList.h b/Source/JavaScriptCore/API/tests/NodeList.h
new file mode 100644
index 000000000..020b76f59
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/NodeList.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef NodeList_h
+#define NodeList_h
+
+#include "Node.h"
+
+typedef struct {
+ unsigned refCount;
+ Node* parentNode;
+} NodeList;
+
+extern NodeList* NodeList_new(Node* parentNode);
+extern unsigned NodeList_length(NodeList*);
+extern Node* NodeList_item(NodeList*, unsigned);
+extern void NodeList_ref(NodeList*);
+extern void NodeList_deref(NodeList*);
+
+#endif /* NodeList_h */
diff --git a/Source/JavaScriptCore/API/tests/Regress141275.h b/Source/JavaScriptCore/API/tests/Regress141275.h
new file mode 100644
index 000000000..bf3492afa
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/Regress141275.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Foundation/Foundation.h>
+#import <JavaScriptCore/JavaScriptCore.h>
+
+#if JSC_OBJC_API_ENABLED
+
+void runRegress141275();
+
+#endif // JSC_OBJC_API_ENABLED
+
diff --git a/Source/JavaScriptCore/API/tests/Regress141809.h b/Source/JavaScriptCore/API/tests/Regress141809.h
new file mode 100644
index 000000000..43b099c94
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/Regress141809.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Foundation/Foundation.h>
+#import <JavaScriptCore/JavaScriptCore.h>
+
+#if JSC_OBJC_API_ENABLED
+
+void runRegress141809();
+
+#endif // JSC_OBJC_API_ENABLED
+
diff --git a/Source/JavaScriptCore/API/tests/minidom.c b/Source/JavaScriptCore/API/tests/minidom.c
new file mode 100644
index 000000000..02b41a9c7
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/minidom.c
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Alp Toker <alp@atoker.com>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <wtf/Platform.h>
+
+#include "JSContextRef.h"
+#include "JSNode.h"
+#include "JSObjectRef.h"
+#include "JSStringRef.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <wtf/Assertions.h>
+
+static char* createStringWithContentsOfFile(const char* fileName);
+static JSValueRef print(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
+
+int main(int argc, char* argv[])
+{
+ const char *scriptPath = "minidom.js";
+ if (argc > 1) {
+ scriptPath = argv[1];
+ }
+
+ JSGlobalContextRef context = JSGlobalContextCreateInGroup(NULL, NULL);
+ JSObjectRef globalObject = JSContextGetGlobalObject(context);
+
+ JSStringRef printIString = JSStringCreateWithUTF8CString("print");
+ JSObjectSetProperty(context, globalObject, printIString, JSObjectMakeFunctionWithCallback(context, printIString, print), kJSPropertyAttributeNone, NULL);
+ JSStringRelease(printIString);
+
+ JSStringRef node = JSStringCreateWithUTF8CString("Node");
+ JSObjectSetProperty(context, globalObject, node, JSObjectMakeConstructor(context, JSNode_class(context), JSNode_construct), kJSPropertyAttributeNone, NULL);
+ JSStringRelease(node);
+
+ char* scriptUTF8 = createStringWithContentsOfFile(scriptPath);
+ JSStringRef script = JSStringCreateWithUTF8CString(scriptUTF8);
+ JSValueRef exception;
+ JSValueRef result = JSEvaluateScript(context, script, NULL, NULL, 1, &exception);
+ if (result)
+ printf("PASS: Test script executed successfully.\n");
+ else {
+ printf("FAIL: Test script threw exception:\n");
+ JSStringRef exceptionIString = JSValueToStringCopy(context, exception, NULL);
+ size_t exceptionUTF8Size = JSStringGetMaximumUTF8CStringSize(exceptionIString);
+ char* exceptionUTF8 = (char*)malloc(exceptionUTF8Size);
+ JSStringGetUTF8CString(exceptionIString, exceptionUTF8, exceptionUTF8Size);
+ printf("%s\n", exceptionUTF8);
+ free(exceptionUTF8);
+ JSStringRelease(exceptionIString);
+ }
+ JSStringRelease(script);
+ free(scriptUTF8);
+
+ globalObject = 0;
+ JSGlobalContextRelease(context);
+ printf("PASS: Program exited normally.\n");
+ return 0;
+}
+
+static JSValueRef print(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(thisObject);
+
+ if (argumentCount > 0) {
+ JSStringRef string = JSValueToStringCopy(context, arguments[0], exception);
+ size_t numChars = JSStringGetMaximumUTF8CStringSize(string);
+ char stringUTF8[numChars];
+ JSStringGetUTF8CString(string, stringUTF8, numChars);
+ printf("%s\n", stringUTF8);
+ }
+
+ return JSValueMakeUndefined(context);
+}
+
+static char* createStringWithContentsOfFile(const char* fileName)
+{
+ char* buffer;
+
+ size_t buffer_size = 0;
+ size_t buffer_capacity = 1024;
+ buffer = (char*)malloc(buffer_capacity);
+
+ FILE* f = fopen(fileName, "r");
+ if (!f) {
+ fprintf(stderr, "Could not open file: %s\n", fileName);
+ free(buffer);
+ return 0;
+ }
+
+ while (!feof(f) && !ferror(f)) {
+ buffer_size += fread(buffer + buffer_size, 1, buffer_capacity - buffer_size, f);
+ if (buffer_size == buffer_capacity) { /* guarantees space for trailing '\0' */
+ buffer_capacity *= 2;
+ buffer = (char*)realloc(buffer, buffer_capacity);
+ ASSERT(buffer);
+ }
+
+ ASSERT(buffer_size < buffer_capacity);
+ }
+ fclose(f);
+ buffer[buffer_size] = '\0';
+
+ return buffer;
+}
diff --git a/Source/JavaScriptCore/API/tests/minidom.html b/Source/JavaScriptCore/API/tests/minidom.html
new file mode 100644
index 000000000..7ea474752
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/minidom.html
@@ -0,0 +1,9 @@
+<html>
+<head>
+<script src="minidom.js"></script>
+</head>
+
+<body onload="test()">
+ <pre id='pre'></pre>
+</body>
+</html>
diff --git a/Source/JavaScriptCore/API/tests/minidom.js b/Source/JavaScriptCore/API/tests/minidom.js
new file mode 100644
index 000000000..85134d7cb
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/minidom.js
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+function shouldBe(a, b)
+{
+ var evalA;
+ try {
+ evalA = eval(a);
+ } catch(e) {
+ evalA = e;
+ }
+
+ if (evalA == b || isNaN(evalA) && typeof evalA == 'number' && isNaN(b) && typeof b == 'number')
+ print("PASS: " + a + " should be " + b + " and is.", "green");
+ else
+ print("__FAIL__: " + a + " should be " + b + " but instead is " + evalA + ".", "red");
+}
+
+function test()
+{
+ print("Node is " + Node);
+ for (var p in Node)
+ print(p + ": " + Node[p]);
+
+ node = new Node();
+ print("node is " + node);
+ for (var p in node)
+ print(p + ": " + node[p]);
+
+ child1 = new Node();
+ child2 = new Node();
+ child3 = new Node();
+
+ node.appendChild(child1);
+ node.appendChild(child2);
+
+ var childNodes = node.childNodes;
+
+ for (var i = 0; i < childNodes.length + 1; i++) {
+ print("item " + i + ": " + childNodes.item(i));
+ }
+
+ for (var i = 0; i < childNodes.length + 1; i++) {
+ print(i + ": " + childNodes[i]);
+ }
+
+ node.removeChild(child1);
+ node.replaceChild(child3, child2);
+
+ for (var i = 0; i < childNodes.length + 1; i++) {
+ print("item " + i + ": " + childNodes.item(i));
+ }
+
+ for (var i = 0; i < childNodes.length + 1; i++) {
+ print(i + ": " + childNodes[i]);
+ }
+
+ try {
+ node.appendChild(null);
+ } catch(e) {
+ print("caught: " + e);
+ }
+
+ try {
+ var o = new Object();
+ o.appendChild = node.appendChild;
+ o.appendChild(node);
+ } catch(e) {
+ print("caught: " + e);
+ }
+
+ try {
+ node.appendChild();
+ } catch(e) {
+ print("caught: " + e);
+ }
+
+ oldNodeType = node.nodeType;
+ node.nodeType = 1;
+ shouldBe("node.nodeType", oldNodeType);
+
+ shouldBe("node instanceof Node", true);
+ shouldBe("new Object() instanceof Node", false);
+
+ print(Node);
+}
+
+test();
diff --git a/Source/JavaScriptCore/API/tests/testapi.c b/Source/JavaScriptCore/API/tests/testapi.c
new file mode 100644
index 000000000..81cbc408a
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/testapi.c
@@ -0,0 +1,1993 @@
+/*
+ * Copyright (C) 2006, 2015 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <wtf/Platform.h>
+
+#include "JavaScriptCore.h"
+#include "JSBasePrivate.h"
+#include "JSContextRefPrivate.h"
+#include "JSObjectRefPrivate.h"
+#include "JSScriptRefPrivate.h"
+#include "JSStringRefPrivate.h"
+#include <math.h>
+#define ASSERT_DISABLED 0
+#include <wtf/Assertions.h>
+
+#if OS(WINDOWS)
+#include <windows.h>
+#endif
+
+#include "CompareAndSwapTest.h"
+#include "CustomGlobalObjectClassTest.h"
+#include "GlobalContextWithFinalizerTest.h"
+
+#include "ExecutionTimeLimitTest.h"
+
+#if JSC_OBJC_API_ENABLED
+void testObjectiveCAPI(void);
+#endif
+
+bool assertTrue(bool value, const char* message);
+extern void JSSynchronousGarbageCollectForDebugging(JSContextRef);
+
+static JSGlobalContextRef context;
+int failed;
+static void assertEqualsAsBoolean(JSValueRef value, bool expectedValue)
+{
+ if (JSValueToBoolean(context, value) != expectedValue) {
+ fprintf(stderr, "assertEqualsAsBoolean failed: %p, %d\n", value, expectedValue);
+ failed = 1;
+ }
+}
+
+static void assertEqualsAsNumber(JSValueRef value, double expectedValue)
+{
+ double number = JSValueToNumber(context, value, NULL);
+
+ // FIXME <rdar://4668451> - On i386 the isnan(double) macro tries to map to the isnan(float) function,
+ // causing a build break with -Wshorten-64-to-32 enabled. The issue is known by the appropriate team.
+ // After that's resolved, we can remove these casts
+ if (number != expectedValue && !(isnan((float)number) && isnan((float)expectedValue))) {
+ fprintf(stderr, "assertEqualsAsNumber failed: %p, %lf\n", value, expectedValue);
+ failed = 1;
+ }
+}
+
+static void assertEqualsAsUTF8String(JSValueRef value, const char* expectedValue)
+{
+ JSStringRef valueAsString = JSValueToStringCopy(context, value, NULL);
+
+ size_t jsSize = JSStringGetMaximumUTF8CStringSize(valueAsString);
+ char* jsBuffer = (char*)malloc(jsSize);
+ JSStringGetUTF8CString(valueAsString, jsBuffer, jsSize);
+
+ unsigned i;
+ for (i = 0; jsBuffer[i]; i++) {
+ if (jsBuffer[i] != expectedValue[i]) {
+ fprintf(stderr, "assertEqualsAsUTF8String failed at character %d: %c(%d) != %c(%d)\n", i, jsBuffer[i], jsBuffer[i], expectedValue[i], expectedValue[i]);
+ fprintf(stderr, "value: %s\n", jsBuffer);
+ fprintf(stderr, "expectedValue: %s\n", expectedValue);
+ failed = 1;
+ }
+ }
+
+ if (jsSize < strlen(jsBuffer) + 1) {
+ fprintf(stderr, "assertEqualsAsUTF8String failed: jsSize was too small\n");
+ failed = 1;
+ }
+
+ free(jsBuffer);
+ JSStringRelease(valueAsString);
+}
+
+static void assertEqualsAsCharactersPtr(JSValueRef value, const char* expectedValue)
+{
+ JSStringRef valueAsString = JSValueToStringCopy(context, value, NULL);
+
+ size_t jsLength = JSStringGetLength(valueAsString);
+ const JSChar* jsBuffer = JSStringGetCharactersPtr(valueAsString);
+
+ CFStringRef expectedValueAsCFString = CFStringCreateWithCString(kCFAllocatorDefault,
+ expectedValue,
+ kCFStringEncodingUTF8);
+ CFIndex cfLength = CFStringGetLength(expectedValueAsCFString);
+ UniChar* cfBuffer = (UniChar*)malloc(cfLength * sizeof(UniChar));
+ CFStringGetCharacters(expectedValueAsCFString, CFRangeMake(0, cfLength), cfBuffer);
+ CFRelease(expectedValueAsCFString);
+
+ if (memcmp(jsBuffer, cfBuffer, cfLength * sizeof(UniChar)) != 0) {
+ fprintf(stderr, "assertEqualsAsCharactersPtr failed: jsBuffer != cfBuffer\n");
+ failed = 1;
+ }
+
+ if (jsLength != (size_t)cfLength) {
+#if OS(WINDOWS)
+ fprintf(stderr, "assertEqualsAsCharactersPtr failed: jsLength(%Iu) != cfLength(%Iu)\n", jsLength, (size_t)cfLength);
+#else
+ fprintf(stderr, "assertEqualsAsCharactersPtr failed: jsLength(%zu) != cfLength(%zu)\n", jsLength, (size_t)cfLength);
+#endif
+ failed = 1;
+ }
+
+ free(cfBuffer);
+ JSStringRelease(valueAsString);
+}
+
+static bool timeZoneIsPST()
+{
+ char timeZoneName[70];
+ struct tm gtm;
+ memset(&gtm, 0, sizeof(gtm));
+ strftime(timeZoneName, sizeof(timeZoneName), "%Z", &gtm);
+
+ return 0 == strcmp("PST", timeZoneName);
+}
+
+static JSValueRef jsGlobalValue; // non-stack value for testing JSValueProtect()
+
+/* MyObject pseudo-class */
+
+static bool MyObject_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "alwaysOne")
+ || JSStringIsEqualToUTF8CString(propertyName, "cantFind")
+ || JSStringIsEqualToUTF8CString(propertyName, "throwOnGet")
+ || JSStringIsEqualToUTF8CString(propertyName, "myPropertyName")
+ || JSStringIsEqualToUTF8CString(propertyName, "hasPropertyLie")
+ || JSStringIsEqualToUTF8CString(propertyName, "0")) {
+ return true;
+ }
+
+ return false;
+}
+
+static JSValueRef MyObject_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "alwaysOne")) {
+ return JSValueMakeNumber(context, 1);
+ }
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "myPropertyName")) {
+ return JSValueMakeNumber(context, 1);
+ }
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "cantFind")) {
+ return JSValueMakeUndefined(context);
+ }
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "hasPropertyLie")) {
+ return 0;
+ }
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "throwOnGet")) {
+ return JSEvaluateScript(context, JSStringCreateWithUTF8CString("throw 'an exception'"), object, JSStringCreateWithUTF8CString("test script"), 1, exception);
+ }
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "0")) {
+ *exception = JSValueMakeNumber(context, 1);
+ return JSValueMakeNumber(context, 1);
+ }
+
+ return JSValueMakeNull(context);
+}
+
+static bool MyObject_setProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(value);
+ UNUSED_PARAM(exception);
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "cantSet"))
+ return true; // pretend we set the property in order to swallow it
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "throwOnSet")) {
+ JSEvaluateScript(context, JSStringCreateWithUTF8CString("throw 'an exception'"), object, JSStringCreateWithUTF8CString("test script"), 1, exception);
+ }
+
+ return false;
+}
+
+static bool MyObject_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "cantDelete"))
+ return true;
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "throwOnDelete")) {
+ JSEvaluateScript(context, JSStringCreateWithUTF8CString("throw 'an exception'"), object, JSStringCreateWithUTF8CString("test script"), 1, exception);
+ return false;
+ }
+
+ return false;
+}
+
+static void MyObject_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+
+ JSStringRef propertyName;
+
+ propertyName = JSStringCreateWithUTF8CString("alwaysOne");
+ JSPropertyNameAccumulatorAddName(propertyNames, propertyName);
+ JSStringRelease(propertyName);
+
+ propertyName = JSStringCreateWithUTF8CString("myPropertyName");
+ JSPropertyNameAccumulatorAddName(propertyNames, propertyName);
+ JSStringRelease(propertyName);
+}
+
+static JSValueRef MyObject_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(exception);
+
+ if (argumentCount > 0 && JSValueIsString(context, arguments[0]) && JSStringIsEqualToUTF8CString(JSValueToStringCopy(context, arguments[0], 0), "throwOnCall")) {
+ JSEvaluateScript(context, JSStringCreateWithUTF8CString("throw 'an exception'"), object, JSStringCreateWithUTF8CString("test script"), 1, exception);
+ return JSValueMakeUndefined(context);
+ }
+
+ if (argumentCount > 0 && JSValueIsStrictEqual(context, arguments[0], JSValueMakeNumber(context, 0)))
+ return JSValueMakeNumber(context, 1);
+
+ return JSValueMakeUndefined(context);
+}
+
+static JSObjectRef MyObject_callAsConstructor(JSContextRef context, JSObjectRef object, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+
+ if (argumentCount > 0 && JSValueIsString(context, arguments[0]) && JSStringIsEqualToUTF8CString(JSValueToStringCopy(context, arguments[0], 0), "throwOnConstruct")) {
+ JSEvaluateScript(context, JSStringCreateWithUTF8CString("throw 'an exception'"), object, JSStringCreateWithUTF8CString("test script"), 1, exception);
+ return object;
+ }
+
+ if (argumentCount > 0 && JSValueIsStrictEqual(context, arguments[0], JSValueMakeNumber(context, 0)))
+ return JSValueToObject(context, JSValueMakeNumber(context, 1), exception);
+
+ return JSValueToObject(context, JSValueMakeNumber(context, 0), exception);
+}
+
+static bool MyObject_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleValue, JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(constructor);
+
+ if (JSValueIsString(context, possibleValue) && JSStringIsEqualToUTF8CString(JSValueToStringCopy(context, possibleValue, 0), "throwOnHasInstance")) {
+ JSEvaluateScript(context, JSStringCreateWithUTF8CString("throw 'an exception'"), constructor, JSStringCreateWithUTF8CString("test script"), 1, exception);
+ return false;
+ }
+
+ JSStringRef numberString = JSStringCreateWithUTF8CString("Number");
+ JSObjectRef numberConstructor = JSValueToObject(context, JSObjectGetProperty(context, JSContextGetGlobalObject(context), numberString, exception), exception);
+ JSStringRelease(numberString);
+
+ return JSValueIsInstanceOfConstructor(context, possibleValue, numberConstructor, exception);
+}
+
+static JSValueRef MyObject_convertToType(JSContextRef context, JSObjectRef object, JSType type, JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(exception);
+
+ switch (type) {
+ case kJSTypeNumber:
+ return JSValueMakeNumber(context, 1);
+ case kJSTypeString:
+ {
+ JSStringRef string = JSStringCreateWithUTF8CString("MyObjectAsString");
+ JSValueRef result = JSValueMakeString(context, string);
+ JSStringRelease(string);
+ return result;
+ }
+ default:
+ break;
+ }
+
+ // string conversion -- forward to default object class
+ return JSValueMakeNull(context);
+}
+
+static JSValueRef MyObject_convertToTypeWrapper(JSContextRef context, JSObjectRef object, JSType type, JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(type);
+ UNUSED_PARAM(exception);
+ // Forward to default object class
+ return 0;
+}
+
+static bool MyObject_set_nullGetForwardSet(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
+{
+ UNUSED_PARAM(ctx);
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(value);
+ UNUSED_PARAM(exception);
+ return false; // Forward to parent class.
+}
+
+static JSStaticValue evilStaticValues[] = {
+ { "nullGetSet", 0, 0, kJSPropertyAttributeNone },
+ { "nullGetForwardSet", 0, MyObject_set_nullGetForwardSet, kJSPropertyAttributeNone },
+ { 0, 0, 0, 0 }
+};
+
+static JSStaticFunction evilStaticFunctions[] = {
+ { "nullCall", 0, kJSPropertyAttributeNone },
+ { 0, 0, 0 }
+};
+
+JSClassDefinition MyObject_definition = {
+ 0,
+ kJSClassAttributeNone,
+
+ "MyObject",
+ NULL,
+
+ evilStaticValues,
+ evilStaticFunctions,
+
+ NULL,
+ NULL,
+ MyObject_hasProperty,
+ MyObject_getProperty,
+ MyObject_setProperty,
+ MyObject_deleteProperty,
+ MyObject_getPropertyNames,
+ MyObject_callAsFunction,
+ MyObject_callAsConstructor,
+ MyObject_hasInstance,
+ MyObject_convertToType,
+};
+
+JSClassDefinition MyObject_convertToTypeWrapperDefinition = {
+ 0,
+ kJSClassAttributeNone,
+
+ "MyObject",
+ NULL,
+
+ NULL,
+ NULL,
+
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ MyObject_convertToTypeWrapper,
+};
+
+JSClassDefinition MyObject_nullWrapperDefinition = {
+ 0,
+ kJSClassAttributeNone,
+
+ "MyObject",
+ NULL,
+
+ NULL,
+ NULL,
+
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+};
+
+static JSClassRef MyObject_class(JSContextRef context)
+{
+ UNUSED_PARAM(context);
+
+ static JSClassRef jsClass;
+ if (!jsClass) {
+ JSClassRef baseClass = JSClassCreate(&MyObject_definition);
+ MyObject_convertToTypeWrapperDefinition.parentClass = baseClass;
+ JSClassRef wrapperClass = JSClassCreate(&MyObject_convertToTypeWrapperDefinition);
+ MyObject_nullWrapperDefinition.parentClass = wrapperClass;
+ jsClass = JSClassCreate(&MyObject_nullWrapperDefinition);
+ }
+
+ return jsClass;
+}
+
+static JSValueRef PropertyCatchalls_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(exception);
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "x")) {
+ static size_t count;
+ if (count++ < 5)
+ return NULL;
+
+ // Swallow all .x gets after 5, returning null.
+ return JSValueMakeNull(context);
+ }
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "y")) {
+ static size_t count;
+ if (count++ < 5)
+ return NULL;
+
+ // Swallow all .y gets after 5, returning null.
+ return JSValueMakeNull(context);
+ }
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "z")) {
+ static size_t count;
+ if (count++ < 5)
+ return NULL;
+
+ // Swallow all .y gets after 5, returning null.
+ return JSValueMakeNull(context);
+ }
+
+ return NULL;
+}
+
+static bool PropertyCatchalls_setProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(value);
+ UNUSED_PARAM(exception);
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "x")) {
+ static size_t count;
+ if (count++ < 5)
+ return false;
+
+ // Swallow all .x sets after 4.
+ return true;
+ }
+
+ if (JSStringIsEqualToUTF8CString(propertyName, "make_throw") || JSStringIsEqualToUTF8CString(propertyName, "0")) {
+ *exception = JSValueMakeNumber(context, 5);
+ return true;
+ }
+
+ return false;
+}
+
+static void PropertyCatchalls_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef propertyNames)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(object);
+
+ static size_t count;
+ static const char* numbers[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
+
+ // Provide a property of a different name every time.
+ JSStringRef propertyName = JSStringCreateWithUTF8CString(numbers[count++ % 10]);
+ JSPropertyNameAccumulatorAddName(propertyNames, propertyName);
+ JSStringRelease(propertyName);
+}
+
+JSClassDefinition PropertyCatchalls_definition = {
+ 0,
+ kJSClassAttributeNone,
+
+ "PropertyCatchalls",
+ NULL,
+
+ NULL,
+ NULL,
+
+ NULL,
+ NULL,
+ NULL,
+ PropertyCatchalls_getProperty,
+ PropertyCatchalls_setProperty,
+ NULL,
+ PropertyCatchalls_getPropertyNames,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+};
+
+static JSClassRef PropertyCatchalls_class(JSContextRef context)
+{
+ UNUSED_PARAM(context);
+
+ static JSClassRef jsClass;
+ if (!jsClass)
+ jsClass = JSClassCreate(&PropertyCatchalls_definition);
+
+ return jsClass;
+}
+
+static bool EvilExceptionObject_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleValue, JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(constructor);
+
+ JSStringRef hasInstanceName = JSStringCreateWithUTF8CString("hasInstance");
+ JSValueRef hasInstance = JSObjectGetProperty(context, constructor, hasInstanceName, exception);
+ JSStringRelease(hasInstanceName);
+ if (!hasInstance)
+ return false;
+ JSObjectRef function = JSValueToObject(context, hasInstance, exception);
+ JSValueRef result = JSObjectCallAsFunction(context, function, constructor, 1, &possibleValue, exception);
+ return result && JSValueToBoolean(context, result);
+}
+
+static JSValueRef EvilExceptionObject_convertToType(JSContextRef context, JSObjectRef object, JSType type, JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(exception);
+ JSStringRef funcName;
+ switch (type) {
+ case kJSTypeNumber:
+ funcName = JSStringCreateWithUTF8CString("toNumber");
+ break;
+ case kJSTypeString:
+ funcName = JSStringCreateWithUTF8CString("toStringExplicit");
+ break;
+ default:
+ return JSValueMakeNull(context);
+ }
+
+ JSValueRef func = JSObjectGetProperty(context, object, funcName, exception);
+ JSStringRelease(funcName);
+ JSObjectRef function = JSValueToObject(context, func, exception);
+ if (!function)
+ return JSValueMakeNull(context);
+ JSValueRef value = JSObjectCallAsFunction(context, function, object, 0, NULL, exception);
+ if (!value) {
+ JSStringRef errorString = JSStringCreateWithUTF8CString("convertToType failed");
+ JSValueRef errorStringRef = JSValueMakeString(context, errorString);
+ JSStringRelease(errorString);
+ return errorStringRef;
+ }
+ return value;
+}
+
+JSClassDefinition EvilExceptionObject_definition = {
+ 0,
+ kJSClassAttributeNone,
+
+ "EvilExceptionObject",
+ NULL,
+
+ NULL,
+ NULL,
+
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ EvilExceptionObject_hasInstance,
+ EvilExceptionObject_convertToType,
+};
+
+static JSClassRef EvilExceptionObject_class(JSContextRef context)
+{
+ UNUSED_PARAM(context);
+
+ static JSClassRef jsClass;
+ if (!jsClass)
+ jsClass = JSClassCreate(&EvilExceptionObject_definition);
+
+ return jsClass;
+}
+
+JSClassDefinition EmptyObject_definition = {
+ 0,
+ kJSClassAttributeNone,
+
+ NULL,
+ NULL,
+
+ NULL,
+ NULL,
+
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+};
+
+static JSClassRef EmptyObject_class(JSContextRef context)
+{
+ UNUSED_PARAM(context);
+
+ static JSClassRef jsClass;
+ if (!jsClass)
+ jsClass = JSClassCreate(&EmptyObject_definition);
+
+ return jsClass;
+}
+
+
+static JSValueRef Base_get(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(exception);
+
+ return JSValueMakeNumber(ctx, 1); // distinguish base get form derived get
+}
+
+static bool Base_set(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(value);
+
+ *exception = JSValueMakeNumber(ctx, 1); // distinguish base set from derived set
+ return true;
+}
+
+static JSValueRef Base_callAsFunction(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(function);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ UNUSED_PARAM(exception);
+
+ return JSValueMakeNumber(ctx, 1); // distinguish base call from derived call
+}
+
+static JSValueRef Base_returnHardNull(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(ctx);
+ UNUSED_PARAM(function);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ UNUSED_PARAM(exception);
+
+ return 0; // should convert to undefined!
+}
+
+static JSStaticFunction Base_staticFunctions[] = {
+ { "baseProtoDup", NULL, kJSPropertyAttributeNone },
+ { "baseProto", Base_callAsFunction, kJSPropertyAttributeNone },
+ { "baseHardNull", Base_returnHardNull, kJSPropertyAttributeNone },
+ { 0, 0, 0 }
+};
+
+static JSStaticValue Base_staticValues[] = {
+ { "baseDup", Base_get, Base_set, kJSPropertyAttributeNone },
+ { "baseOnly", Base_get, Base_set, kJSPropertyAttributeNone },
+ { 0, 0, 0, 0 }
+};
+
+static bool TestInitializeFinalize;
+static void Base_initialize(JSContextRef context, JSObjectRef object)
+{
+ UNUSED_PARAM(context);
+
+ if (TestInitializeFinalize) {
+ ASSERT((void*)1 == JSObjectGetPrivate(object));
+ JSObjectSetPrivate(object, (void*)2);
+ }
+}
+
+static unsigned Base_didFinalize;
+static void Base_finalize(JSObjectRef object)
+{
+ UNUSED_PARAM(object);
+ if (TestInitializeFinalize) {
+ ASSERT((void*)4 == JSObjectGetPrivate(object));
+ Base_didFinalize = true;
+ }
+}
+
+static JSClassRef Base_class(JSContextRef context)
+{
+ UNUSED_PARAM(context);
+
+ static JSClassRef jsClass;
+ if (!jsClass) {
+ JSClassDefinition definition = kJSClassDefinitionEmpty;
+ definition.staticValues = Base_staticValues;
+ definition.staticFunctions = Base_staticFunctions;
+ definition.initialize = Base_initialize;
+ definition.finalize = Base_finalize;
+ jsClass = JSClassCreate(&definition);
+ }
+ return jsClass;
+}
+
+static JSValueRef Derived_get(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(exception);
+
+ return JSValueMakeNumber(ctx, 2); // distinguish base get form derived get
+}
+
+static bool Derived_set(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
+{
+ UNUSED_PARAM(ctx);
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(value);
+
+ *exception = JSValueMakeNumber(ctx, 2); // distinguish base set from derived set
+ return true;
+}
+
+static JSValueRef Derived_callAsFunction(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(function);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ UNUSED_PARAM(exception);
+
+ return JSValueMakeNumber(ctx, 2); // distinguish base call from derived call
+}
+
+static JSStaticFunction Derived_staticFunctions[] = {
+ { "protoOnly", Derived_callAsFunction, kJSPropertyAttributeNone },
+ { "protoDup", NULL, kJSPropertyAttributeNone },
+ { "baseProtoDup", Derived_callAsFunction, kJSPropertyAttributeNone },
+ { 0, 0, 0 }
+};
+
+static JSStaticValue Derived_staticValues[] = {
+ { "derivedOnly", Derived_get, Derived_set, kJSPropertyAttributeNone },
+ { "protoDup", Derived_get, Derived_set, kJSPropertyAttributeNone },
+ { "baseDup", Derived_get, Derived_set, kJSPropertyAttributeNone },
+ { 0, 0, 0, 0 }
+};
+
+static void Derived_initialize(JSContextRef context, JSObjectRef object)
+{
+ UNUSED_PARAM(context);
+
+ if (TestInitializeFinalize) {
+ ASSERT((void*)2 == JSObjectGetPrivate(object));
+ JSObjectSetPrivate(object, (void*)3);
+ }
+}
+
+static void Derived_finalize(JSObjectRef object)
+{
+ if (TestInitializeFinalize) {
+ ASSERT((void*)3 == JSObjectGetPrivate(object));
+ JSObjectSetPrivate(object, (void*)4);
+ }
+}
+
+static JSClassRef Derived_class(JSContextRef context)
+{
+ static JSClassRef jsClass;
+ if (!jsClass) {
+ JSClassDefinition definition = kJSClassDefinitionEmpty;
+ definition.parentClass = Base_class(context);
+ definition.staticValues = Derived_staticValues;
+ definition.staticFunctions = Derived_staticFunctions;
+ definition.initialize = Derived_initialize;
+ definition.finalize = Derived_finalize;
+ jsClass = JSClassCreate(&definition);
+ }
+ return jsClass;
+}
+
+static JSClassRef Derived2_class(JSContextRef context)
+{
+ static JSClassRef jsClass;
+ if (!jsClass) {
+ JSClassDefinition definition = kJSClassDefinitionEmpty;
+ definition.parentClass = Derived_class(context);
+ jsClass = JSClassCreate(&definition);
+ }
+ return jsClass;
+}
+
+static JSValueRef print_callAsFunction(JSContextRef ctx, JSObjectRef functionObject, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(functionObject);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(exception);
+
+ ASSERT(JSContextGetGlobalContext(ctx) == context);
+
+ if (argumentCount > 0) {
+ JSStringRef string = JSValueToStringCopy(ctx, arguments[0], NULL);
+ size_t sizeUTF8 = JSStringGetMaximumUTF8CStringSize(string);
+ char* stringUTF8 = (char*)malloc(sizeUTF8);
+ JSStringGetUTF8CString(string, stringUTF8, sizeUTF8);
+ printf("%s\n", stringUTF8);
+ free(stringUTF8);
+ JSStringRelease(string);
+ }
+
+ return JSValueMakeUndefined(ctx);
+}
+
+static JSObjectRef myConstructor_callAsConstructor(JSContextRef context, JSObjectRef constructorObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(constructorObject);
+ UNUSED_PARAM(exception);
+
+ JSObjectRef result = JSObjectMake(context, NULL, NULL);
+ if (argumentCount > 0) {
+ JSStringRef value = JSStringCreateWithUTF8CString("value");
+ JSObjectSetProperty(context, result, value, arguments[0], kJSPropertyAttributeNone, NULL);
+ JSStringRelease(value);
+ }
+
+ return result;
+}
+
+static JSObjectRef myBadConstructor_callAsConstructor(JSContextRef context, JSObjectRef constructorObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(context);
+ UNUSED_PARAM(constructorObject);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ UNUSED_PARAM(exception);
+
+ return 0;
+}
+
+
+static void globalObject_initialize(JSContextRef context, JSObjectRef object)
+{
+ UNUSED_PARAM(object);
+ // Ensure that an execution context is passed in
+ ASSERT(context);
+
+ JSObjectRef globalObject = JSContextGetGlobalObject(context);
+ ASSERT(globalObject);
+
+ // Ensure that the standard global properties have been set on the global object
+ JSStringRef array = JSStringCreateWithUTF8CString("Array");
+ JSObjectRef arrayConstructor = JSValueToObject(context, JSObjectGetProperty(context, globalObject, array, NULL), NULL);
+ JSStringRelease(array);
+
+ UNUSED_PARAM(arrayConstructor);
+ ASSERT(arrayConstructor);
+}
+
+static JSValueRef globalObject_get(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(exception);
+
+ return JSValueMakeNumber(ctx, 3);
+}
+
+static bool globalObject_set(JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception)
+{
+ UNUSED_PARAM(object);
+ UNUSED_PARAM(propertyName);
+ UNUSED_PARAM(value);
+
+ *exception = JSValueMakeNumber(ctx, 3);
+ return true;
+}
+
+static JSValueRef globalObject_call(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(function);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ UNUSED_PARAM(exception);
+
+ return JSValueMakeNumber(ctx, 3);
+}
+
+static JSValueRef functionGC(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(function);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ UNUSED_PARAM(exception);
+ JSGarbageCollect(context);
+ return JSValueMakeUndefined(context);
+}
+
+static JSStaticValue globalObject_staticValues[] = {
+ { "globalStaticValue", globalObject_get, globalObject_set, kJSPropertyAttributeNone },
+ { 0, 0, 0, 0 }
+};
+
+static JSStaticFunction globalObject_staticFunctions[] = {
+ { "globalStaticFunction", globalObject_call, kJSPropertyAttributeNone },
+ { "globalStaticFunction2", globalObject_call, kJSPropertyAttributeNone },
+ { "gc", functionGC, kJSPropertyAttributeNone },
+ { 0, 0, 0 }
+};
+
+static char* createStringWithContentsOfFile(const char* fileName);
+
+static void testInitializeFinalize()
+{
+ JSObjectRef o = JSObjectMake(context, Derived_class(context), (void*)1);
+ UNUSED_PARAM(o);
+ ASSERT(JSObjectGetPrivate(o) == (void*)3);
+}
+
+static JSValueRef jsNumberValue = NULL;
+
+static JSObjectRef aHeapRef = NULL;
+
+static void makeGlobalNumberValue(JSContextRef context) {
+ JSValueRef v = JSValueMakeNumber(context, 420);
+ JSValueProtect(context, v);
+ jsNumberValue = v;
+ v = NULL;
+}
+
+bool assertTrue(bool value, const char* message)
+{
+ if (!value) {
+ if (message)
+ fprintf(stderr, "assertTrue failed: '%s'\n", message);
+ else
+ fprintf(stderr, "assertTrue failed.\n");
+ failed = 1;
+ }
+ return value;
+}
+
+static bool checkForCycleInPrototypeChain()
+{
+ bool result = true;
+ JSGlobalContextRef context = JSGlobalContextCreate(0);
+ JSObjectRef object1 = JSObjectMake(context, /* jsClass */ 0, /* data */ 0);
+ JSObjectRef object2 = JSObjectMake(context, /* jsClass */ 0, /* data */ 0);
+ JSObjectRef object3 = JSObjectMake(context, /* jsClass */ 0, /* data */ 0);
+
+ JSObjectSetPrototype(context, object1, JSValueMakeNull(context));
+ ASSERT(JSValueIsNull(context, JSObjectGetPrototype(context, object1)));
+
+ // object1 -> object1
+ JSObjectSetPrototype(context, object1, object1);
+ result &= assertTrue(JSValueIsNull(context, JSObjectGetPrototype(context, object1)), "It is possible to assign self as a prototype");
+
+ // object1 -> object2 -> object1
+ JSObjectSetPrototype(context, object2, object1);
+ ASSERT(JSValueIsStrictEqual(context, JSObjectGetPrototype(context, object2), object1));
+ JSObjectSetPrototype(context, object1, object2);
+ result &= assertTrue(JSValueIsNull(context, JSObjectGetPrototype(context, object1)), "It is possible to close a prototype chain cycle");
+
+ // object1 -> object2 -> object3 -> object1
+ JSObjectSetPrototype(context, object2, object3);
+ ASSERT(JSValueIsStrictEqual(context, JSObjectGetPrototype(context, object2), object3));
+ JSObjectSetPrototype(context, object1, object2);
+ ASSERT(JSValueIsStrictEqual(context, JSObjectGetPrototype(context, object1), object2));
+ JSObjectSetPrototype(context, object3, object1);
+ result &= assertTrue(!JSValueIsStrictEqual(context, JSObjectGetPrototype(context, object3), object1), "It is possible to close a prototype chain cycle");
+
+ JSValueRef exception;
+ JSStringRef code = JSStringCreateWithUTF8CString("o = { }; p = { }; o.__proto__ = p; p.__proto__ = o");
+ JSStringRef file = JSStringCreateWithUTF8CString("");
+ result &= assertTrue(!JSEvaluateScript(context, code, /* thisObject*/ 0, file, 1, &exception)
+ , "An exception should be thrown");
+
+ JSStringRelease(code);
+ JSStringRelease(file);
+ JSGlobalContextRelease(context);
+ return result;
+}
+
+static JSValueRef valueToObjectExceptionCallAsFunction(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
+{
+ UNUSED_PARAM(function);
+ UNUSED_PARAM(thisObject);
+ UNUSED_PARAM(argumentCount);
+ UNUSED_PARAM(arguments);
+ JSValueRef jsUndefined = JSValueMakeUndefined(JSContextGetGlobalContext(ctx));
+ JSValueToObject(JSContextGetGlobalContext(ctx), jsUndefined, exception);
+
+ return JSValueMakeUndefined(ctx);
+}
+static bool valueToObjectExceptionTest()
+{
+ JSGlobalContextRef testContext;
+ JSClassDefinition globalObjectClassDefinition = kJSClassDefinitionEmpty;
+ globalObjectClassDefinition.initialize = globalObject_initialize;
+ globalObjectClassDefinition.staticValues = globalObject_staticValues;
+ globalObjectClassDefinition.staticFunctions = globalObject_staticFunctions;
+ globalObjectClassDefinition.attributes = kJSClassAttributeNoAutomaticPrototype;
+ JSClassRef globalObjectClass = JSClassCreate(&globalObjectClassDefinition);
+ testContext = JSGlobalContextCreateInGroup(NULL, globalObjectClass);
+ JSObjectRef globalObject = JSContextGetGlobalObject(testContext);
+
+ JSStringRef valueToObject = JSStringCreateWithUTF8CString("valueToObject");
+ JSObjectRef valueToObjectFunction = JSObjectMakeFunctionWithCallback(testContext, valueToObject, valueToObjectExceptionCallAsFunction);
+ JSObjectSetProperty(testContext, globalObject, valueToObject, valueToObjectFunction, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(valueToObject);
+
+ JSStringRef test = JSStringCreateWithUTF8CString("valueToObject();");
+ JSEvaluateScript(testContext, test, NULL, NULL, 1, NULL);
+
+ JSStringRelease(test);
+ JSClassRelease(globalObjectClass);
+ JSGlobalContextRelease(testContext);
+
+ return true;
+}
+
+static bool globalContextNameTest()
+{
+ bool result = true;
+ JSGlobalContextRef context = JSGlobalContextCreate(0);
+
+ JSStringRef str = JSGlobalContextCopyName(context);
+ result &= assertTrue(!str, "Default context name is NULL");
+
+ JSStringRef name1 = JSStringCreateWithUTF8CString("name1");
+ JSStringRef name2 = JSStringCreateWithUTF8CString("name2");
+
+ JSGlobalContextSetName(context, name1);
+ JSStringRef fetchName1 = JSGlobalContextCopyName(context);
+ JSGlobalContextSetName(context, name2);
+ JSStringRef fetchName2 = JSGlobalContextCopyName(context);
+ JSGlobalContextSetName(context, NULL);
+ JSStringRef fetchName3 = JSGlobalContextCopyName(context);
+
+ result &= assertTrue(JSStringIsEqual(name1, fetchName1), "Unexpected Context name");
+ result &= assertTrue(JSStringIsEqual(name2, fetchName2), "Unexpected Context name");
+ result &= assertTrue(!JSStringIsEqual(fetchName1, fetchName2), "Unexpected Context name");
+ result &= assertTrue(!fetchName3, "Unexpected Context name");
+
+ JSStringRelease(name1);
+ JSStringRelease(name2);
+ JSStringRelease(fetchName1);
+ JSStringRelease(fetchName2);
+
+ return result;
+}
+
+static void checkConstnessInJSObjectNames()
+{
+ JSStaticFunction fun;
+ fun.name = "something";
+ JSStaticValue val;
+ val.name = "something";
+}
+
+
+int main(int argc, char* argv[])
+{
+#if OS(WINDOWS)
+#if defined(_M_X64) || defined(__x86_64__)
+ // The VS2013 runtime has a bug where it mis-detects AVX-capable processors
+ // if the feature has been disabled in firmware. This causes us to crash
+ // in some of the math functions. For now, we disable those optimizations
+ // because Microsoft is not going to fix the problem in VS2013.
+ // FIXME: http://webkit.org/b/141449: Remove this workaround when we switch to VS2015+.
+ _set_FMA3_enable(0);
+#endif
+
+ // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
+ // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
+ // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
+ ::SetErrorMode(0);
+#endif
+
+ testCompareAndSwap();
+
+#if JSC_OBJC_API_ENABLED
+ testObjectiveCAPI();
+#endif
+
+ const char *scriptPath = "testapi.js";
+ if (argc > 1) {
+ scriptPath = argv[1];
+ }
+
+ // Test garbage collection with a fresh context
+ context = JSGlobalContextCreateInGroup(NULL, NULL);
+ TestInitializeFinalize = true;
+ testInitializeFinalize();
+ JSGlobalContextRelease(context);
+ TestInitializeFinalize = false;
+
+ ASSERT(Base_didFinalize);
+
+ JSClassDefinition globalObjectClassDefinition = kJSClassDefinitionEmpty;
+ globalObjectClassDefinition.initialize = globalObject_initialize;
+ globalObjectClassDefinition.staticValues = globalObject_staticValues;
+ globalObjectClassDefinition.staticFunctions = globalObject_staticFunctions;
+ globalObjectClassDefinition.attributes = kJSClassAttributeNoAutomaticPrototype;
+ JSClassRef globalObjectClass = JSClassCreate(&globalObjectClassDefinition);
+ context = JSGlobalContextCreateInGroup(NULL, globalObjectClass);
+
+ JSContextGroupRef contextGroup = JSContextGetGroup(context);
+
+ JSGlobalContextRetain(context);
+ JSGlobalContextRelease(context);
+ ASSERT(JSContextGetGlobalContext(context) == context);
+
+ JSReportExtraMemoryCost(context, 0);
+ JSReportExtraMemoryCost(context, 1);
+ JSReportExtraMemoryCost(context, 1024);
+
+ JSObjectRef globalObject = JSContextGetGlobalObject(context);
+ ASSERT(JSValueIsObject(context, globalObject));
+
+ JSValueRef jsUndefined = JSValueMakeUndefined(context);
+ JSValueRef jsNull = JSValueMakeNull(context);
+ JSValueRef jsTrue = JSValueMakeBoolean(context, true);
+ JSValueRef jsFalse = JSValueMakeBoolean(context, false);
+ JSValueRef jsZero = JSValueMakeNumber(context, 0);
+ JSValueRef jsOne = JSValueMakeNumber(context, 1);
+ JSValueRef jsOneThird = JSValueMakeNumber(context, 1.0 / 3.0);
+ JSObjectRef jsObjectNoProto = JSObjectMake(context, NULL, NULL);
+ JSObjectSetPrototype(context, jsObjectNoProto, JSValueMakeNull(context));
+
+ JSObjectSetPrivate(globalObject, (void*)123);
+ if (JSObjectGetPrivate(globalObject) != (void*)123) {
+ printf("FAIL: Didn't return private data when set by JSObjectSetPrivate().\n");
+ failed = 1;
+ } else
+ printf("PASS: returned private data when set by JSObjectSetPrivate().\n");
+
+ // FIXME: test funny utf8 characters
+ JSStringRef jsEmptyIString = JSStringCreateWithUTF8CString("");
+ JSValueRef jsEmptyString = JSValueMakeString(context, jsEmptyIString);
+
+ JSStringRef jsOneIString = JSStringCreateWithUTF8CString("1");
+ JSValueRef jsOneString = JSValueMakeString(context, jsOneIString);
+
+ UniChar singleUniChar = 65; // Capital A
+ CFMutableStringRef cfString =
+ CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorDefault,
+ &singleUniChar,
+ 1,
+ 1,
+ kCFAllocatorNull);
+
+ JSStringRef jsCFIString = JSStringCreateWithCFString(cfString);
+ JSValueRef jsCFString = JSValueMakeString(context, jsCFIString);
+
+ CFStringRef cfEmptyString = CFStringCreateWithCString(kCFAllocatorDefault, "", kCFStringEncodingUTF8);
+
+ JSStringRef jsCFEmptyIString = JSStringCreateWithCFString(cfEmptyString);
+ JSValueRef jsCFEmptyString = JSValueMakeString(context, jsCFEmptyIString);
+
+ CFIndex cfStringLength = CFStringGetLength(cfString);
+ UniChar* buffer = (UniChar*)malloc(cfStringLength * sizeof(UniChar));
+ CFStringGetCharacters(cfString,
+ CFRangeMake(0, cfStringLength),
+ buffer);
+ JSStringRef jsCFIStringWithCharacters = JSStringCreateWithCharacters((JSChar*)buffer, cfStringLength);
+ JSValueRef jsCFStringWithCharacters = JSValueMakeString(context, jsCFIStringWithCharacters);
+
+ JSStringRef jsCFEmptyIStringWithCharacters = JSStringCreateWithCharacters((JSChar*)buffer, CFStringGetLength(cfEmptyString));
+ free(buffer);
+ JSValueRef jsCFEmptyStringWithCharacters = JSValueMakeString(context, jsCFEmptyIStringWithCharacters);
+
+ JSChar constantString[] = { 'H', 'e', 'l', 'l', 'o', };
+ JSStringRef constantStringRef = JSStringCreateWithCharactersNoCopy(constantString, sizeof(constantString) / sizeof(constantString[0]));
+ ASSERT(JSStringGetCharactersPtr(constantStringRef) == constantString);
+ JSStringRelease(constantStringRef);
+
+ ASSERT(JSValueGetType(context, NULL) == kJSTypeNull);
+ ASSERT(JSValueGetType(context, jsUndefined) == kJSTypeUndefined);
+ ASSERT(JSValueGetType(context, jsNull) == kJSTypeNull);
+ ASSERT(JSValueGetType(context, jsTrue) == kJSTypeBoolean);
+ ASSERT(JSValueGetType(context, jsFalse) == kJSTypeBoolean);
+ ASSERT(JSValueGetType(context, jsZero) == kJSTypeNumber);
+ ASSERT(JSValueGetType(context, jsOne) == kJSTypeNumber);
+ ASSERT(JSValueGetType(context, jsOneThird) == kJSTypeNumber);
+ ASSERT(JSValueGetType(context, jsEmptyString) == kJSTypeString);
+ ASSERT(JSValueGetType(context, jsOneString) == kJSTypeString);
+ ASSERT(JSValueGetType(context, jsCFString) == kJSTypeString);
+ ASSERT(JSValueGetType(context, jsCFStringWithCharacters) == kJSTypeString);
+ ASSERT(JSValueGetType(context, jsCFEmptyString) == kJSTypeString);
+ ASSERT(JSValueGetType(context, jsCFEmptyStringWithCharacters) == kJSTypeString);
+
+ ASSERT(!JSValueIsBoolean(context, NULL));
+ ASSERT(!JSValueIsObject(context, NULL));
+ ASSERT(!JSValueIsArray(context, NULL));
+ ASSERT(!JSValueIsDate(context, NULL));
+ ASSERT(!JSValueIsString(context, NULL));
+ ASSERT(!JSValueIsNumber(context, NULL));
+ ASSERT(!JSValueIsUndefined(context, NULL));
+ ASSERT(JSValueIsNull(context, NULL));
+ ASSERT(!JSObjectCallAsFunction(context, NULL, NULL, 0, NULL, NULL));
+ ASSERT(!JSObjectCallAsConstructor(context, NULL, 0, NULL, NULL));
+ ASSERT(!JSObjectIsConstructor(context, NULL));
+ ASSERT(!JSObjectIsFunction(context, NULL));
+
+ JSStringRef nullString = JSStringCreateWithUTF8CString(0);
+ const JSChar* characters = JSStringGetCharactersPtr(nullString);
+ if (characters) {
+ printf("FAIL: Didn't return null when accessing character pointer of a null String.\n");
+ failed = 1;
+ } else
+ printf("PASS: returned null when accessing character pointer of a null String.\n");
+
+ JSStringRef emptyString = JSStringCreateWithCFString(CFSTR(""));
+ characters = JSStringGetCharactersPtr(emptyString);
+ if (!characters) {
+ printf("FAIL: Returned null when accessing character pointer of an empty String.\n");
+ failed = 1;
+ } else
+ printf("PASS: returned empty when accessing character pointer of an empty String.\n");
+
+ size_t length = JSStringGetLength(nullString);
+ if (length) {
+ printf("FAIL: Didn't return 0 length for null String.\n");
+ failed = 1;
+ } else
+ printf("PASS: returned 0 length for null String.\n");
+ JSStringRelease(nullString);
+
+ length = JSStringGetLength(emptyString);
+ if (length) {
+ printf("FAIL: Didn't return 0 length for empty String.\n");
+ failed = 1;
+ } else
+ printf("PASS: returned 0 length for empty String.\n");
+ JSStringRelease(emptyString);
+
+ JSObjectRef propertyCatchalls = JSObjectMake(context, PropertyCatchalls_class(context), NULL);
+ JSStringRef propertyCatchallsString = JSStringCreateWithUTF8CString("PropertyCatchalls");
+ JSObjectSetProperty(context, globalObject, propertyCatchallsString, propertyCatchalls, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(propertyCatchallsString);
+
+ JSObjectRef myObject = JSObjectMake(context, MyObject_class(context), NULL);
+ JSStringRef myObjectIString = JSStringCreateWithUTF8CString("MyObject");
+ JSObjectSetProperty(context, globalObject, myObjectIString, myObject, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(myObjectIString);
+
+ JSObjectRef EvilExceptionObject = JSObjectMake(context, EvilExceptionObject_class(context), NULL);
+ JSStringRef EvilExceptionObjectIString = JSStringCreateWithUTF8CString("EvilExceptionObject");
+ JSObjectSetProperty(context, globalObject, EvilExceptionObjectIString, EvilExceptionObject, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(EvilExceptionObjectIString);
+
+ JSObjectRef EmptyObject = JSObjectMake(context, EmptyObject_class(context), NULL);
+ JSStringRef EmptyObjectIString = JSStringCreateWithUTF8CString("EmptyObject");
+ JSObjectSetProperty(context, globalObject, EmptyObjectIString, EmptyObject, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(EmptyObjectIString);
+
+ JSStringRef lengthStr = JSStringCreateWithUTF8CString("length");
+ JSObjectRef aStackRef = JSObjectMakeArray(context, 0, 0, 0);
+ aHeapRef = aStackRef;
+ JSObjectSetProperty(context, aHeapRef, lengthStr, JSValueMakeNumber(context, 10), 0, 0);
+ JSStringRef privatePropertyName = JSStringCreateWithUTF8CString("privateProperty");
+ if (!JSObjectSetPrivateProperty(context, myObject, privatePropertyName, aHeapRef)) {
+ printf("FAIL: Could not set private property.\n");
+ failed = 1;
+ } else
+ printf("PASS: Set private property.\n");
+ aStackRef = 0;
+ if (JSObjectSetPrivateProperty(context, aHeapRef, privatePropertyName, aHeapRef)) {
+ printf("FAIL: JSObjectSetPrivateProperty should fail on non-API objects.\n");
+ failed = 1;
+ } else
+ printf("PASS: Did not allow JSObjectSetPrivateProperty on a non-API object.\n");
+ if (JSObjectGetPrivateProperty(context, myObject, privatePropertyName) != aHeapRef) {
+ printf("FAIL: Could not retrieve private property.\n");
+ failed = 1;
+ } else
+ printf("PASS: Retrieved private property.\n");
+ if (JSObjectGetPrivateProperty(context, aHeapRef, privatePropertyName)) {
+ printf("FAIL: JSObjectGetPrivateProperty should return NULL when called on a non-API object.\n");
+ failed = 1;
+ } else
+ printf("PASS: JSObjectGetPrivateProperty return NULL.\n");
+
+ if (JSObjectGetProperty(context, myObject, privatePropertyName, 0) == aHeapRef) {
+ printf("FAIL: Accessed private property through ordinary property lookup.\n");
+ failed = 1;
+ } else
+ printf("PASS: Cannot access private property through ordinary property lookup.\n");
+
+ JSGarbageCollect(context);
+
+ for (int i = 0; i < 10000; i++)
+ JSObjectMake(context, 0, 0);
+
+ aHeapRef = JSValueToObject(context, JSObjectGetPrivateProperty(context, myObject, privatePropertyName), 0);
+ if (JSValueToNumber(context, JSObjectGetProperty(context, aHeapRef, lengthStr, 0), 0) != 10) {
+ printf("FAIL: Private property has been collected.\n");
+ failed = 1;
+ } else
+ printf("PASS: Private property does not appear to have been collected.\n");
+ JSStringRelease(lengthStr);
+
+ if (!JSObjectSetPrivateProperty(context, myObject, privatePropertyName, 0)) {
+ printf("FAIL: Could not set private property to NULL.\n");
+ failed = 1;
+ } else
+ printf("PASS: Set private property to NULL.\n");
+ if (JSObjectGetPrivateProperty(context, myObject, privatePropertyName)) {
+ printf("FAIL: Could not retrieve private property.\n");
+ failed = 1;
+ } else
+ printf("PASS: Retrieved private property.\n");
+
+ JSStringRef nullJSON = JSStringCreateWithUTF8CString(0);
+ JSValueRef nullJSONObject = JSValueMakeFromJSONString(context, nullJSON);
+ if (nullJSONObject) {
+ printf("FAIL: Did not parse null String as JSON correctly\n");
+ failed = 1;
+ } else
+ printf("PASS: Parsed null String as JSON correctly.\n");
+ JSStringRelease(nullJSON);
+
+ JSStringRef validJSON = JSStringCreateWithUTF8CString("{\"aProperty\":true}");
+ JSValueRef jsonObject = JSValueMakeFromJSONString(context, validJSON);
+ JSStringRelease(validJSON);
+ if (!JSValueIsObject(context, jsonObject)) {
+ printf("FAIL: Did not parse valid JSON correctly\n");
+ failed = 1;
+ } else
+ printf("PASS: Parsed valid JSON string.\n");
+ JSStringRef propertyName = JSStringCreateWithUTF8CString("aProperty");
+ assertEqualsAsBoolean(JSObjectGetProperty(context, JSValueToObject(context, jsonObject, 0), propertyName, 0), true);
+ JSStringRelease(propertyName);
+ JSStringRef invalidJSON = JSStringCreateWithUTF8CString("fail!");
+ if (JSValueMakeFromJSONString(context, invalidJSON)) {
+ printf("FAIL: Should return null for invalid JSON data\n");
+ failed = 1;
+ } else
+ printf("PASS: Correctly returned null for invalid JSON data.\n");
+ JSValueRef exception;
+ JSStringRef str = JSValueCreateJSONString(context, jsonObject, 0, 0);
+ if (!JSStringIsEqualToUTF8CString(str, "{\"aProperty\":true}")) {
+ printf("FAIL: Did not correctly serialise with indent of 0.\n");
+ failed = 1;
+ } else
+ printf("PASS: Correctly serialised with indent of 0.\n");
+ JSStringRelease(str);
+
+ str = JSValueCreateJSONString(context, jsonObject, 4, 0);
+ if (!JSStringIsEqualToUTF8CString(str, "{\n \"aProperty\": true\n}")) {
+ printf("FAIL: Did not correctly serialise with indent of 4.\n");
+ failed = 1;
+ } else
+ printf("PASS: Correctly serialised with indent of 4.\n");
+ JSStringRelease(str);
+
+ str = JSStringCreateWithUTF8CString("({get a(){ throw '';}})");
+ JSValueRef unstringifiableObj = JSEvaluateScript(context, str, NULL, NULL, 1, NULL);
+ JSStringRelease(str);
+
+ str = JSValueCreateJSONString(context, unstringifiableObj, 4, 0);
+ if (str) {
+ printf("FAIL: Didn't return null when attempting to serialize unserializable value.\n");
+ JSStringRelease(str);
+ failed = 1;
+ } else
+ printf("PASS: returned null when attempting to serialize unserializable value.\n");
+
+ str = JSValueCreateJSONString(context, unstringifiableObj, 4, &exception);
+ if (str) {
+ printf("FAIL: Didn't return null when attempting to serialize unserializable value.\n");
+ JSStringRelease(str);
+ failed = 1;
+ } else
+ printf("PASS: returned null when attempting to serialize unserializable value.\n");
+ if (!exception) {
+ printf("FAIL: Did not set exception on serialisation error\n");
+ failed = 1;
+ } else
+ printf("PASS: set exception on serialisation error\n");
+ // Conversions that throw exceptions
+ exception = NULL;
+ ASSERT(NULL == JSValueToObject(context, jsNull, &exception));
+ ASSERT(exception);
+
+ exception = NULL;
+ // FIXME <rdar://4668451> - On i386 the isnan(double) macro tries to map to the isnan(float) function,
+ // causing a build break with -Wshorten-64-to-32 enabled. The issue is known by the appropriate team.
+ // After that's resolved, we can remove these casts
+ ASSERT(isnan((float)JSValueToNumber(context, jsObjectNoProto, &exception)));
+ ASSERT(exception);
+
+ exception = NULL;
+ ASSERT(!JSValueToStringCopy(context, jsObjectNoProto, &exception));
+ ASSERT(exception);
+
+ ASSERT(JSValueToBoolean(context, myObject));
+
+ exception = NULL;
+ ASSERT(!JSValueIsEqual(context, jsObjectNoProto, JSValueMakeNumber(context, 1), &exception));
+ ASSERT(exception);
+
+ exception = NULL;
+ JSObjectGetPropertyAtIndex(context, myObject, 0, &exception);
+ ASSERT(1 == JSValueToNumber(context, exception, NULL));
+
+ assertEqualsAsBoolean(jsUndefined, false);
+ assertEqualsAsBoolean(jsNull, false);
+ assertEqualsAsBoolean(jsTrue, true);
+ assertEqualsAsBoolean(jsFalse, false);
+ assertEqualsAsBoolean(jsZero, false);
+ assertEqualsAsBoolean(jsOne, true);
+ assertEqualsAsBoolean(jsOneThird, true);
+ assertEqualsAsBoolean(jsEmptyString, false);
+ assertEqualsAsBoolean(jsOneString, true);
+ assertEqualsAsBoolean(jsCFString, true);
+ assertEqualsAsBoolean(jsCFStringWithCharacters, true);
+ assertEqualsAsBoolean(jsCFEmptyString, false);
+ assertEqualsAsBoolean(jsCFEmptyStringWithCharacters, false);
+
+ assertEqualsAsNumber(jsUndefined, nan(""));
+ assertEqualsAsNumber(jsNull, 0);
+ assertEqualsAsNumber(jsTrue, 1);
+ assertEqualsAsNumber(jsFalse, 0);
+ assertEqualsAsNumber(jsZero, 0);
+ assertEqualsAsNumber(jsOne, 1);
+ assertEqualsAsNumber(jsOneThird, 1.0 / 3.0);
+ assertEqualsAsNumber(jsEmptyString, 0);
+ assertEqualsAsNumber(jsOneString, 1);
+ assertEqualsAsNumber(jsCFString, nan(""));
+ assertEqualsAsNumber(jsCFStringWithCharacters, nan(""));
+ assertEqualsAsNumber(jsCFEmptyString, 0);
+ assertEqualsAsNumber(jsCFEmptyStringWithCharacters, 0);
+ ASSERT(sizeof(JSChar) == sizeof(UniChar));
+
+ assertEqualsAsCharactersPtr(jsUndefined, "undefined");
+ assertEqualsAsCharactersPtr(jsNull, "null");
+ assertEqualsAsCharactersPtr(jsTrue, "true");
+ assertEqualsAsCharactersPtr(jsFalse, "false");
+ assertEqualsAsCharactersPtr(jsZero, "0");
+ assertEqualsAsCharactersPtr(jsOne, "1");
+ assertEqualsAsCharactersPtr(jsOneThird, "0.3333333333333333");
+ assertEqualsAsCharactersPtr(jsEmptyString, "");
+ assertEqualsAsCharactersPtr(jsOneString, "1");
+ assertEqualsAsCharactersPtr(jsCFString, "A");
+ assertEqualsAsCharactersPtr(jsCFStringWithCharacters, "A");
+ assertEqualsAsCharactersPtr(jsCFEmptyString, "");
+ assertEqualsAsCharactersPtr(jsCFEmptyStringWithCharacters, "");
+
+ assertEqualsAsUTF8String(jsUndefined, "undefined");
+ assertEqualsAsUTF8String(jsNull, "null");
+ assertEqualsAsUTF8String(jsTrue, "true");
+ assertEqualsAsUTF8String(jsFalse, "false");
+ assertEqualsAsUTF8String(jsZero, "0");
+ assertEqualsAsUTF8String(jsOne, "1");
+ assertEqualsAsUTF8String(jsOneThird, "0.3333333333333333");
+ assertEqualsAsUTF8String(jsEmptyString, "");
+ assertEqualsAsUTF8String(jsOneString, "1");
+ assertEqualsAsUTF8String(jsCFString, "A");
+ assertEqualsAsUTF8String(jsCFStringWithCharacters, "A");
+ assertEqualsAsUTF8String(jsCFEmptyString, "");
+ assertEqualsAsUTF8String(jsCFEmptyStringWithCharacters, "");
+
+ checkConstnessInJSObjectNames();
+
+ ASSERT(JSValueIsStrictEqual(context, jsTrue, jsTrue));
+ ASSERT(!JSValueIsStrictEqual(context, jsOne, jsOneString));
+
+ ASSERT(JSValueIsEqual(context, jsOne, jsOneString, NULL));
+ ASSERT(!JSValueIsEqual(context, jsTrue, jsFalse, NULL));
+
+ CFStringRef cfJSString = JSStringCopyCFString(kCFAllocatorDefault, jsCFIString);
+ CFStringRef cfJSEmptyString = JSStringCopyCFString(kCFAllocatorDefault, jsCFEmptyIString);
+ ASSERT(CFEqual(cfJSString, cfString));
+ ASSERT(CFEqual(cfJSEmptyString, cfEmptyString));
+ CFRelease(cfJSString);
+ CFRelease(cfJSEmptyString);
+
+ CFRelease(cfString);
+ CFRelease(cfEmptyString);
+
+ jsGlobalValue = JSObjectMake(context, NULL, NULL);
+ makeGlobalNumberValue(context);
+ JSValueProtect(context, jsGlobalValue);
+ JSGarbageCollect(context);
+ ASSERT(JSValueIsObject(context, jsGlobalValue));
+ JSValueUnprotect(context, jsGlobalValue);
+ JSValueUnprotect(context, jsNumberValue);
+
+ JSStringRef goodSyntax = JSStringCreateWithUTF8CString("x = 1;");
+ const char* badSyntaxConstant = "x := 1;";
+ JSStringRef badSyntax = JSStringCreateWithUTF8CString(badSyntaxConstant);
+ ASSERT(JSCheckScriptSyntax(context, goodSyntax, NULL, 0, NULL));
+ ASSERT(!JSCheckScriptSyntax(context, badSyntax, NULL, 0, NULL));
+ ASSERT(!JSScriptCreateFromString(contextGroup, 0, 0, badSyntax, 0, 0));
+ ASSERT(!JSScriptCreateReferencingImmortalASCIIText(contextGroup, 0, 0, badSyntaxConstant, strlen(badSyntaxConstant), 0, 0));
+
+ JSValueRef result;
+ JSValueRef v;
+ JSObjectRef o;
+ JSStringRef string;
+
+ result = JSEvaluateScript(context, goodSyntax, NULL, NULL, 1, NULL);
+ ASSERT(result);
+ ASSERT(JSValueIsEqual(context, result, jsOne, NULL));
+
+ exception = NULL;
+ result = JSEvaluateScript(context, badSyntax, NULL, NULL, 1, &exception);
+ ASSERT(!result);
+ ASSERT(JSValueIsObject(context, exception));
+
+ JSStringRef array = JSStringCreateWithUTF8CString("Array");
+ JSObjectRef arrayConstructor = JSValueToObject(context, JSObjectGetProperty(context, globalObject, array, NULL), NULL);
+ JSStringRelease(array);
+ result = JSObjectCallAsConstructor(context, arrayConstructor, 0, NULL, NULL);
+ ASSERT(result);
+ ASSERT(JSValueIsObject(context, result));
+ ASSERT(JSValueIsInstanceOfConstructor(context, result, arrayConstructor, NULL));
+ ASSERT(!JSValueIsInstanceOfConstructor(context, JSValueMakeNull(context), arrayConstructor, NULL));
+
+ o = JSValueToObject(context, result, NULL);
+ exception = NULL;
+ ASSERT(JSValueIsUndefined(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception)));
+ ASSERT(!exception);
+
+ JSObjectSetPropertyAtIndex(context, o, 0, JSValueMakeNumber(context, 1), &exception);
+ ASSERT(!exception);
+
+ exception = NULL;
+ ASSERT(1 == JSValueToNumber(context, JSObjectGetPropertyAtIndex(context, o, 0, &exception), &exception));
+ ASSERT(!exception);
+
+ JSStringRef functionBody;
+ JSObjectRef function;
+
+ exception = NULL;
+ functionBody = JSStringCreateWithUTF8CString("rreturn Array;");
+ JSStringRef line = JSStringCreateWithUTF8CString("line");
+ ASSERT(!JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception));
+ ASSERT(JSValueIsObject(context, exception));
+ v = JSObjectGetProperty(context, JSValueToObject(context, exception, NULL), line, NULL);
+ assertEqualsAsNumber(v, 2);
+ JSStringRelease(functionBody);
+ JSStringRelease(line);
+
+ exception = NULL;
+ functionBody = JSStringCreateWithUTF8CString("rreturn Array;");
+ line = JSStringCreateWithUTF8CString("line");
+ ASSERT(!JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, -42, &exception));
+ ASSERT(JSValueIsObject(context, exception));
+ v = JSObjectGetProperty(context, JSValueToObject(context, exception, NULL), line, NULL);
+ assertEqualsAsNumber(v, 2);
+ JSStringRelease(functionBody);
+ JSStringRelease(line);
+
+ exception = NULL;
+ functionBody = JSStringCreateWithUTF8CString("// Line one.\nrreturn Array;");
+ line = JSStringCreateWithUTF8CString("line");
+ ASSERT(!JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception));
+ ASSERT(JSValueIsObject(context, exception));
+ v = JSObjectGetProperty(context, JSValueToObject(context, exception, NULL), line, NULL);
+ assertEqualsAsNumber(v, 3);
+ JSStringRelease(functionBody);
+ JSStringRelease(line);
+
+ exception = NULL;
+ functionBody = JSStringCreateWithUTF8CString("return Array;");
+ function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, &exception);
+ JSStringRelease(functionBody);
+ ASSERT(!exception);
+ ASSERT(JSObjectIsFunction(context, function));
+ v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
+ ASSERT(v);
+ ASSERT(JSValueIsEqual(context, v, arrayConstructor, NULL));
+
+ exception = NULL;
+ function = JSObjectMakeFunction(context, NULL, 0, NULL, jsEmptyIString, NULL, 0, &exception);
+ ASSERT(!exception);
+ v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, &exception);
+ ASSERT(v && !exception);
+ ASSERT(JSValueIsUndefined(context, v));
+
+ exception = NULL;
+ v = NULL;
+ JSStringRef foo = JSStringCreateWithUTF8CString("foo");
+ JSStringRef argumentNames[] = { foo };
+ functionBody = JSStringCreateWithUTF8CString("return foo;");
+ function = JSObjectMakeFunction(context, foo, 1, argumentNames, functionBody, NULL, 1, &exception);
+ ASSERT(function && !exception);
+ JSValueRef arguments[] = { JSValueMakeNumber(context, 2) };
+ JSObjectCallAsFunction(context, function, NULL, 1, arguments, &exception);
+ JSStringRelease(foo);
+ JSStringRelease(functionBody);
+
+ string = JSValueToStringCopy(context, function, NULL);
+ assertEqualsAsUTF8String(JSValueMakeString(context, string), "function foo(foo) {\nreturn foo;\n}");
+ JSStringRelease(string);
+
+ JSStringRef print = JSStringCreateWithUTF8CString("print");
+ JSObjectRef printFunction = JSObjectMakeFunctionWithCallback(context, print, print_callAsFunction);
+ JSObjectSetProperty(context, globalObject, print, printFunction, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(print);
+
+ ASSERT(!JSObjectSetPrivate(printFunction, (void*)1));
+ ASSERT(!JSObjectGetPrivate(printFunction));
+
+ JSStringRef myConstructorIString = JSStringCreateWithUTF8CString("MyConstructor");
+ JSObjectRef myConstructor = JSObjectMakeConstructor(context, NULL, myConstructor_callAsConstructor);
+ JSObjectSetProperty(context, globalObject, myConstructorIString, myConstructor, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(myConstructorIString);
+
+ JSStringRef myBadConstructorIString = JSStringCreateWithUTF8CString("MyBadConstructor");
+ JSObjectRef myBadConstructor = JSObjectMakeConstructor(context, NULL, myBadConstructor_callAsConstructor);
+ JSObjectSetProperty(context, globalObject, myBadConstructorIString, myBadConstructor, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(myBadConstructorIString);
+
+ ASSERT(!JSObjectSetPrivate(myConstructor, (void*)1));
+ ASSERT(!JSObjectGetPrivate(myConstructor));
+
+ string = JSStringCreateWithUTF8CString("Base");
+ JSObjectRef baseConstructor = JSObjectMakeConstructor(context, Base_class(context), NULL);
+ JSObjectSetProperty(context, globalObject, string, baseConstructor, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(string);
+
+ string = JSStringCreateWithUTF8CString("Derived");
+ JSObjectRef derivedConstructor = JSObjectMakeConstructor(context, Derived_class(context), NULL);
+ JSObjectSetProperty(context, globalObject, string, derivedConstructor, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(string);
+
+ string = JSStringCreateWithUTF8CString("Derived2");
+ JSObjectRef derived2Constructor = JSObjectMakeConstructor(context, Derived2_class(context), NULL);
+ JSObjectSetProperty(context, globalObject, string, derived2Constructor, kJSPropertyAttributeNone, NULL);
+ JSStringRelease(string);
+
+ o = JSObjectMake(context, NULL, NULL);
+ JSObjectSetProperty(context, o, jsOneIString, JSValueMakeNumber(context, 1), kJSPropertyAttributeNone, NULL);
+ JSObjectSetProperty(context, o, jsCFIString, JSValueMakeNumber(context, 1), kJSPropertyAttributeDontEnum, NULL);
+ JSPropertyNameArrayRef nameArray = JSObjectCopyPropertyNames(context, o);
+ size_t expectedCount = JSPropertyNameArrayGetCount(nameArray);
+ size_t count;
+ for (count = 0; count < expectedCount; ++count)
+ JSPropertyNameArrayGetNameAtIndex(nameArray, count);
+ JSPropertyNameArrayRelease(nameArray);
+ ASSERT(count == 1); // jsCFString should not be enumerated
+
+ JSValueRef argumentsArrayValues[] = { JSValueMakeNumber(context, 10), JSValueMakeNumber(context, 20) };
+ o = JSObjectMakeArray(context, sizeof(argumentsArrayValues) / sizeof(JSValueRef), argumentsArrayValues, NULL);
+ string = JSStringCreateWithUTF8CString("length");
+ v = JSObjectGetProperty(context, o, string, NULL);
+ assertEqualsAsNumber(v, 2);
+ v = JSObjectGetPropertyAtIndex(context, o, 0, NULL);
+ assertEqualsAsNumber(v, 10);
+ v = JSObjectGetPropertyAtIndex(context, o, 1, NULL);
+ assertEqualsAsNumber(v, 20);
+
+ o = JSObjectMakeArray(context, 0, NULL, NULL);
+ v = JSObjectGetProperty(context, o, string, NULL);
+ assertEqualsAsNumber(v, 0);
+ JSStringRelease(string);
+
+ JSValueRef argumentsDateValues[] = { JSValueMakeNumber(context, 0) };
+ o = JSObjectMakeDate(context, 1, argumentsDateValues, NULL);
+ if (timeZoneIsPST())
+ assertEqualsAsUTF8String(o, "Wed Dec 31 1969 16:00:00 GMT-0800 (PST)");
+
+ string = JSStringCreateWithUTF8CString("an error message");
+ JSValueRef argumentsErrorValues[] = { JSValueMakeString(context, string) };
+ o = JSObjectMakeError(context, 1, argumentsErrorValues, NULL);
+ assertEqualsAsUTF8String(o, "Error: an error message");
+ JSStringRelease(string);
+
+ string = JSStringCreateWithUTF8CString("foo");
+ JSStringRef string2 = JSStringCreateWithUTF8CString("gi");
+ JSValueRef argumentsRegExpValues[] = { JSValueMakeString(context, string), JSValueMakeString(context, string2) };
+ o = JSObjectMakeRegExp(context, 2, argumentsRegExpValues, NULL);
+ assertEqualsAsUTF8String(o, "/foo/gi");
+ JSStringRelease(string);
+ JSStringRelease(string2);
+
+ JSClassDefinition nullDefinition = kJSClassDefinitionEmpty;
+ nullDefinition.attributes = kJSClassAttributeNoAutomaticPrototype;
+ JSClassRef nullClass = JSClassCreate(&nullDefinition);
+ JSClassRelease(nullClass);
+
+ nullDefinition = kJSClassDefinitionEmpty;
+ nullClass = JSClassCreate(&nullDefinition);
+ JSClassRelease(nullClass);
+
+ functionBody = JSStringCreateWithUTF8CString("return this;");
+ function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, NULL);
+ JSStringRelease(functionBody);
+ v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
+ ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
+ v = JSObjectCallAsFunction(context, function, o, 0, NULL, NULL);
+ ASSERT(JSValueIsEqual(context, v, o, NULL));
+
+ functionBody = JSStringCreateWithUTF8CString("return eval(\"this\");");
+ function = JSObjectMakeFunction(context, NULL, 0, NULL, functionBody, NULL, 1, NULL);
+ JSStringRelease(functionBody);
+ v = JSObjectCallAsFunction(context, function, NULL, 0, NULL, NULL);
+ ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
+ v = JSObjectCallAsFunction(context, function, o, 0, NULL, NULL);
+ ASSERT(JSValueIsEqual(context, v, o, NULL));
+
+ const char* thisScript = "this;";
+ JSStringRef script = JSStringCreateWithUTF8CString(thisScript);
+ v = JSEvaluateScript(context, script, NULL, NULL, 1, NULL);
+ ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
+ v = JSEvaluateScript(context, script, o, NULL, 1, NULL);
+ ASSERT(JSValueIsEqual(context, v, o, NULL));
+ JSStringRelease(script);
+
+ JSScriptRef scriptObject = JSScriptCreateReferencingImmortalASCIIText(contextGroup, 0, 0, thisScript, strlen(thisScript), 0, 0);
+ v = JSScriptEvaluate(context, scriptObject, NULL, NULL);
+ ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
+ v = JSScriptEvaluate(context, scriptObject, o, NULL);
+ ASSERT(JSValueIsEqual(context, v, o, NULL));
+ JSScriptRelease(scriptObject);
+
+ script = JSStringCreateWithUTF8CString("eval(this);");
+ v = JSEvaluateScript(context, script, NULL, NULL, 1, NULL);
+ ASSERT(JSValueIsEqual(context, v, globalObject, NULL));
+ v = JSEvaluateScript(context, script, o, NULL, 1, NULL);
+ ASSERT(JSValueIsEqual(context, v, o, NULL));
+ JSStringRelease(script);
+
+ script = JSStringCreateWithUTF8CString("[ ]");
+ v = JSEvaluateScript(context, script, NULL, NULL, 1, NULL);
+ ASSERT(JSValueIsArray(context, v));
+ JSStringRelease(script);
+
+ script = JSStringCreateWithUTF8CString("new Date");
+ v = JSEvaluateScript(context, script, NULL, NULL, 1, NULL);
+ ASSERT(JSValueIsDate(context, v));
+ JSStringRelease(script);
+
+ exception = NULL;
+ script = JSStringCreateWithUTF8CString("rreturn Array;");
+ JSStringRef sourceURL = JSStringCreateWithUTF8CString("file:///foo/bar.js");
+ JSStringRef sourceURLKey = JSStringCreateWithUTF8CString("sourceURL");
+ JSEvaluateScript(context, script, NULL, sourceURL, 1, &exception);
+ ASSERT(exception);
+ v = JSObjectGetProperty(context, JSValueToObject(context, exception, NULL), sourceURLKey, NULL);
+ assertEqualsAsUTF8String(v, "file:///foo/bar.js");
+ JSStringRelease(script);
+ JSStringRelease(sourceURL);
+ JSStringRelease(sourceURLKey);
+
+ // Verify that creating a constructor for a class with no static functions does not trigger
+ // an assert inside putDirect or lead to a crash during GC. <https://bugs.webkit.org/show_bug.cgi?id=25785>
+ nullDefinition = kJSClassDefinitionEmpty;
+ nullClass = JSClassCreate(&nullDefinition);
+ JSObjectMakeConstructor(context, nullClass, 0);
+ JSClassRelease(nullClass);
+
+ char* scriptUTF8 = createStringWithContentsOfFile(scriptPath);
+ if (!scriptUTF8) {
+ printf("FAIL: Test script could not be loaded.\n");
+ failed = 1;
+ } else {
+ JSStringRef url = JSStringCreateWithUTF8CString(scriptPath);
+ JSStringRef script = JSStringCreateWithUTF8CString(scriptUTF8);
+ JSStringRef errorMessage = 0;
+ int errorLine = 0;
+ JSScriptRef scriptObject = JSScriptCreateFromString(contextGroup, url, 1, script, &errorMessage, &errorLine);
+ ASSERT((!scriptObject) != (!errorMessage));
+ if (!scriptObject) {
+ printf("FAIL: Test script did not parse\n\t%s:%d\n\t", scriptPath, errorLine);
+ CFStringRef errorCF = JSStringCopyCFString(kCFAllocatorDefault, errorMessage);
+ CFShow(errorCF);
+ CFRelease(errorCF);
+ JSStringRelease(errorMessage);
+ failed = 1;
+ }
+
+ JSStringRelease(script);
+ exception = NULL;
+ result = scriptObject ? JSScriptEvaluate(context, scriptObject, 0, &exception) : 0;
+ if (result && JSValueIsUndefined(context, result))
+ printf("PASS: Test script executed successfully.\n");
+ else {
+ printf("FAIL: Test script returned unexpected value:\n");
+ JSStringRef exceptionIString = JSValueToStringCopy(context, exception, NULL);
+ CFStringRef exceptionCF = JSStringCopyCFString(kCFAllocatorDefault, exceptionIString);
+ CFShow(exceptionCF);
+ CFRelease(exceptionCF);
+ JSStringRelease(exceptionIString);
+ failed = 1;
+ }
+ JSScriptRelease(scriptObject);
+ free(scriptUTF8);
+ }
+
+ // Check Promise is not exposed.
+ {
+ JSObjectRef globalObject = JSContextGetGlobalObject(context);
+ {
+ JSStringRef promiseProperty = JSStringCreateWithUTF8CString("Promise");
+ ASSERT(JSObjectHasProperty(context, globalObject, promiseProperty));
+ JSStringRelease(promiseProperty);
+ }
+ {
+ JSStringRef script = JSStringCreateWithUTF8CString("typeof Promise");
+ JSStringRef function = JSStringCreateWithUTF8CString("function");
+ JSValueRef value = JSEvaluateScript(context, script, NULL, NULL, 1, NULL);
+ ASSERT(JSValueIsString(context, value));
+ JSStringRef valueAsString = JSValueToStringCopy(context, value, NULL);
+ ASSERT(JSStringIsEqual(valueAsString, function));
+ JSStringRelease(valueAsString);
+ JSStringRelease(function);
+ JSStringRelease(script);
+ }
+ printf("PASS: Promise is exposed under JSContext API.\n");
+ }
+
+ // Check microtasks.
+ {
+ JSGlobalContextRef context = JSGlobalContextCreateInGroup(NULL, NULL);
+ {
+ JSObjectRef globalObject = JSContextGetGlobalObject(context);
+ JSValueRef exception;
+ JSStringRef code = JSStringCreateWithUTF8CString("result = 0; Promise.resolve(42).then(function (value) { result = value; });");
+ JSStringRef file = JSStringCreateWithUTF8CString("");
+ assertTrue(JSEvaluateScript(context, code, globalObject, file, 1, &exception), "An exception should not be thrown");
+ JSStringRelease(code);
+ JSStringRelease(file);
+
+ JSStringRef resultProperty = JSStringCreateWithUTF8CString("result");
+ ASSERT(JSObjectHasProperty(context, globalObject, resultProperty));
+
+ JSValueRef resultValue = JSObjectGetProperty(context, globalObject, resultProperty, &exception);
+ assertEqualsAsNumber(resultValue, 42);
+ JSStringRelease(resultProperty);
+ }
+ JSGlobalContextRelease(context);
+ }
+
+ failed = testExecutionTimeLimit() || failed;
+ failed = testGlobalContextWithFinalizer() || failed;
+
+ // Clear out local variables pointing at JSObjectRefs to allow their values to be collected
+ function = NULL;
+ v = NULL;
+ o = NULL;
+ globalObject = NULL;
+ myConstructor = NULL;
+
+ JSStringRelease(jsEmptyIString);
+ JSStringRelease(jsOneIString);
+ JSStringRelease(jsCFIString);
+ JSStringRelease(jsCFEmptyIString);
+ JSStringRelease(jsCFIStringWithCharacters);
+ JSStringRelease(jsCFEmptyIStringWithCharacters);
+ JSStringRelease(goodSyntax);
+ JSStringRelease(badSyntax);
+
+ JSGlobalContextRelease(context);
+ JSClassRelease(globalObjectClass);
+
+ // Test for an infinite prototype chain that used to be created. This test
+ // passes if the call to JSObjectHasProperty() does not hang.
+
+ JSClassDefinition prototypeLoopClassDefinition = kJSClassDefinitionEmpty;
+ prototypeLoopClassDefinition.staticFunctions = globalObject_staticFunctions;
+ JSClassRef prototypeLoopClass = JSClassCreate(&prototypeLoopClassDefinition);
+ JSGlobalContextRef prototypeLoopContext = JSGlobalContextCreateInGroup(NULL, prototypeLoopClass);
+
+ JSStringRef nameProperty = JSStringCreateWithUTF8CString("name");
+ JSObjectHasProperty(prototypeLoopContext, JSContextGetGlobalObject(prototypeLoopContext), nameProperty);
+
+ JSGlobalContextRelease(prototypeLoopContext);
+ JSClassRelease(prototypeLoopClass);
+
+ printf("PASS: Infinite prototype chain does not occur.\n");
+
+ if (checkForCycleInPrototypeChain())
+ printf("PASS: A cycle in a prototype chain can't be created.\n");
+ else {
+ printf("FAIL: A cycle in a prototype chain can be created.\n");
+ failed = true;
+ }
+ if (valueToObjectExceptionTest())
+ printf("PASS: throwException did not crash when handling an error with appendMessageToError set and no codeBlock available.\n");
+
+ if (globalContextNameTest())
+ printf("PASS: global context name behaves as expected.\n");
+
+ customGlobalObjectClassTest();
+ globalObjectSetPrototypeTest();
+ globalObjectPrivatePropertyTest();
+
+ if (failed) {
+ printf("FAIL: Some tests failed.\n");
+ return 1;
+ }
+
+ printf("PASS: Program exited normally.\n");
+ return 0;
+}
+
+static char* createStringWithContentsOfFile(const char* fileName)
+{
+ char* buffer;
+
+ size_t buffer_size = 0;
+ size_t buffer_capacity = 1024;
+ buffer = (char*)malloc(buffer_capacity);
+
+ FILE* f = fopen(fileName, "r");
+ if (!f) {
+ fprintf(stderr, "Could not open file: %s\n", fileName);
+ free(buffer);
+ return 0;
+ }
+
+ while (!feof(f) && !ferror(f)) {
+ buffer_size += fread(buffer + buffer_size, 1, buffer_capacity - buffer_size, f);
+ if (buffer_size == buffer_capacity) { // guarantees space for trailing '\0'
+ buffer_capacity *= 2;
+ buffer = (char*)realloc(buffer, buffer_capacity);
+ ASSERT(buffer);
+ }
+
+ ASSERT(buffer_size < buffer_capacity);
+ }
+ fclose(f);
+ buffer[buffer_size] = '\0';
+
+ return buffer;
+}
+
+#if OS(WINDOWS)
+extern "C" __declspec(dllexport) int WINAPI dllLauncherEntryPoint(int argc, const char* argv[])
+{
+ return main(argc, const_cast<char**>(argv));
+}
+#endif
diff --git a/Source/JavaScriptCore/API/tests/testapi.js b/Source/JavaScriptCore/API/tests/testapi.js
new file mode 100644
index 000000000..88d3701c2
--- /dev/null
+++ b/Source/JavaScriptCore/API/tests/testapi.js
@@ -0,0 +1,307 @@
+/*
+ * Copyright (C) 2006 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+function bludgeonArguments() { if (0) arguments; return function g() {} }
+h = bludgeonArguments();
+gc();
+
+var failed = false;
+function pass(msg)
+{
+ print("PASS: " + msg, "green");
+}
+
+function fail(msg)
+{
+ print("FAIL: " + msg, "red");
+ failed = true;
+}
+
+function shouldBe(a, b)
+{
+ var evalA;
+ try {
+ evalA = eval(a);
+ } catch(e) {
+ evalA = e;
+ }
+
+ if (evalA == b || isNaN(evalA) && typeof evalA == 'number' && isNaN(b) && typeof b == 'number')
+ pass(a + " should be " + b + " and is.");
+ else
+ fail(a + " should be " + b + " but instead is " + evalA + ".");
+}
+
+function shouldThrow(a)
+{
+ var evalA;
+ try {
+ eval(a);
+ } catch(e) {
+ pass(a + " threw: " + e);
+ return;
+ }
+
+ fail(a + " did not throw an exception.");
+}
+
+function globalStaticFunction()
+{
+ return 4;
+}
+
+shouldBe("globalStaticValue", 3);
+shouldBe("globalStaticFunction()", 4);
+shouldBe("this.globalStaticFunction()", 4);
+
+function globalStaticFunction2() {
+ return 10;
+}
+shouldBe("globalStaticFunction2();", 10);
+this.globalStaticFunction2 = function() { return 20; }
+shouldBe("globalStaticFunction2();", 20);
+shouldBe("this.globalStaticFunction2();", 20);
+
+function iAmNotAStaticFunction() { return 10; }
+shouldBe("iAmNotAStaticFunction();", 10);
+this.iAmNotAStaticFunction = function() { return 20; }
+shouldBe("iAmNotAStaticFunction();", 20);
+
+shouldBe("typeof MyObject", "function"); // our object implements 'call'
+MyObject.cantFind = 1;
+shouldBe("MyObject.cantFind", undefined);
+MyObject.regularType = 1;
+shouldBe("MyObject.regularType", 1);
+MyObject.alwaysOne = 2;
+shouldBe("MyObject.alwaysOne", 1);
+MyObject.cantDelete = 1;
+delete MyObject.cantDelete;
+shouldBe("MyObject.cantDelete", 1);
+shouldBe("delete MyObject.throwOnDelete", "an exception");
+MyObject.cantSet = 1;
+shouldBe("MyObject.cantSet", undefined);
+shouldBe("MyObject.throwOnGet", "an exception");
+shouldBe("MyObject.throwOnSet = 5", "an exception");
+shouldBe("MyObject('throwOnCall')", "an exception");
+shouldBe("new MyObject('throwOnConstruct')", "an exception");
+shouldBe("'throwOnHasInstance' instanceof MyObject", "an exception");
+
+MyObject.nullGetForwardSet = 1;
+shouldBe("MyObject.nullGetForwardSet", 1);
+
+var foundMyPropertyName = false;
+var foundRegularType = false;
+for (var p in MyObject) {
+ if (p == "myPropertyName")
+ foundMyPropertyName = true;
+ if (p == "regularType")
+ foundRegularType = true;
+}
+
+if (foundMyPropertyName)
+ pass("MyObject.myPropertyName was enumerated");
+else
+ fail("MyObject.myPropertyName was not enumerated");
+
+if (foundRegularType)
+ pass("MyObject.regularType was enumerated");
+else
+ fail("MyObject.regularType was not enumerated");
+
+var alwaysOneDescriptor = Object.getOwnPropertyDescriptor(MyObject, "alwaysOne");
+shouldBe('typeof alwaysOneDescriptor', "object");
+shouldBe('alwaysOneDescriptor.value', MyObject.alwaysOne);
+shouldBe('alwaysOneDescriptor.configurable', true);
+shouldBe('alwaysOneDescriptor.enumerable', false); // Actually it is.
+var cantFindDescriptor = Object.getOwnPropertyDescriptor(MyObject, "cantFind");
+shouldBe('typeof cantFindDescriptor', "object");
+shouldBe('cantFindDescriptor.value', MyObject.cantFind);
+shouldBe('cantFindDescriptor.configurable', true);
+shouldBe('cantFindDescriptor.enumerable', false);
+try {
+ // If getOwnPropertyDescriptor() returned an access descriptor, this wouldn't throw.
+ Object.getOwnPropertyDescriptor(MyObject, "throwOnGet");
+} catch (e) {
+ pass("getting property descriptor of throwOnGet threw exception");
+}
+var myPropertyNameDescriptor = Object.getOwnPropertyDescriptor(MyObject, "myPropertyName");
+shouldBe('typeof myPropertyNameDescriptor', "object");
+shouldBe('myPropertyNameDescriptor.value', MyObject.myPropertyName);
+shouldBe('myPropertyNameDescriptor.configurable', true);
+shouldBe('myPropertyNameDescriptor.enumerable', false); // Actually it is.
+try {
+ // if getOwnPropertyDescriptor() returned an access descriptor, this wouldn't throw.
+ Object.getOwnPropertyDescriptor(MyObject, "hasPropertyLie");
+} catch (e) {
+ pass("getting property descriptor of hasPropertyLie threw exception");
+}
+shouldBe('Object.getOwnPropertyDescriptor(MyObject, "doesNotExist")', undefined);
+
+myObject = new MyObject();
+
+shouldBe("delete MyObject.regularType", true);
+shouldBe("MyObject.regularType", undefined);
+shouldBe("MyObject(0)", 1);
+shouldBe("MyObject()", undefined);
+shouldBe("typeof myObject", "object");
+shouldBe("MyObject ? 1 : 0", true); // toBoolean
+shouldBe("+MyObject", 1); // toNumber
+shouldBe("(Object.prototype.toString.call(MyObject))", "[object MyObject]"); // Object.prototype.toString
+shouldBe("(MyObject.toString())", "[object MyObject]"); // toString
+shouldBe("String(MyObject)", "MyObjectAsString"); // toString
+shouldBe("MyObject - 0", 1); // toNumber
+shouldBe("MyObject.valueOf()", 1); // valueOf
+
+shouldBe("typeof MyConstructor", "object");
+constructedObject = new MyConstructor(1);
+shouldBe("typeof constructedObject", "object");
+shouldBe("constructedObject.value", 1);
+shouldBe("myObject instanceof MyObject", true);
+shouldBe("(new Object()) instanceof MyObject", false);
+
+shouldThrow("new MyBadConstructor()");
+
+MyObject.nullGetSet = 1;
+shouldBe("MyObject.nullGetSet", 1);
+shouldThrow("MyObject.nullCall()");
+shouldThrow("MyObject.hasPropertyLie");
+
+derived = new Derived();
+
+shouldBe("derived instanceof Derived", true);
+shouldBe("derived instanceof Base", true);
+
+// base properties and functions return 1 when called/gotten; derived, 2
+shouldBe("derived.baseProtoDup()", 2);
+shouldBe("derived.baseProto()", 1);
+shouldBe("derived.baseDup", 2);
+shouldBe("derived.baseOnly", 1);
+shouldBe("derived.protoOnly()", 2);
+shouldBe("derived.protoDup", 2);
+shouldBe("derived.derivedOnly", 2)
+
+shouldBe("derived.baseHardNull()", undefined)
+
+// base properties throw 1 when set; derived, 2
+shouldBe("derived.baseDup = 0", 2);
+shouldBe("derived.baseOnly = 0", 1);
+shouldBe("derived.derivedOnly = 0", 2)
+shouldBe("derived.protoDup = 0", 2);
+
+derived2 = new Derived2();
+
+shouldBe("derived2 instanceof Derived2", true);
+shouldBe("derived2 instanceof Derived", true);
+shouldBe("derived2 instanceof Base", true);
+
+// base properties and functions return 1 when called/gotten; derived, 2
+shouldBe("derived2.baseProtoDup()", 2);
+shouldBe("derived2.baseProto()", 1);
+shouldBe("derived2.baseDup", 2);
+shouldBe("derived2.baseOnly", 1);
+shouldBe("derived2.protoOnly()", 2);
+shouldBe("derived2.protoDup", 2);
+shouldBe("derived2.derivedOnly", 2)
+
+// base properties throw 1 when set; derived, 2
+shouldBe("derived2.baseDup = 0", 2);
+shouldBe("derived2.baseOnly = 0", 1);
+shouldBe("derived2.derivedOnly = 0", 2)
+shouldBe("derived2.protoDup = 0", 2);
+
+shouldBe('Object.getOwnPropertyDescriptor(derived, "baseProto")', undefined);
+shouldBe('Object.getOwnPropertyDescriptor(derived, "baseProtoDup")', undefined);
+var baseDupDescriptor = Object.getOwnPropertyDescriptor(derived, "baseDup");
+shouldBe('typeof baseDupDescriptor', "object");
+shouldBe('baseDupDescriptor.value', derived.baseDup);
+shouldBe('baseDupDescriptor.configurable', true);
+shouldBe('baseDupDescriptor.enumerable', false);
+var baseOnlyDescriptor = Object.getOwnPropertyDescriptor(derived, "baseOnly");
+shouldBe('typeof baseOnlyDescriptor', "object");
+shouldBe('baseOnlyDescriptor.value', derived.baseOnly);
+shouldBe('baseOnlyDescriptor.configurable', true);
+shouldBe('baseOnlyDescriptor.enumerable', false);
+shouldBe('Object.getOwnPropertyDescriptor(derived, "protoOnly")', undefined);
+var protoDupDescriptor = Object.getOwnPropertyDescriptor(derived, "protoDup");
+shouldBe('typeof protoDupDescriptor', "object");
+shouldBe('protoDupDescriptor.value', derived.protoDup);
+shouldBe('protoDupDescriptor.configurable', true);
+shouldBe('protoDupDescriptor.enumerable', false);
+var derivedOnlyDescriptor = Object.getOwnPropertyDescriptor(derived, "derivedOnly");
+shouldBe('typeof derivedOnlyDescriptor', "object");
+shouldBe('derivedOnlyDescriptor.value', derived.derivedOnly);
+shouldBe('derivedOnlyDescriptor.configurable', true);
+shouldBe('derivedOnlyDescriptor.enumerable', false);
+
+shouldBe("undefined instanceof MyObject", false);
+EvilExceptionObject.hasInstance = function f() { return f(); };
+EvilExceptionObject.__proto__ = undefined;
+shouldThrow("undefined instanceof EvilExceptionObject");
+EvilExceptionObject.hasInstance = function () { return true; };
+shouldBe("undefined instanceof EvilExceptionObject", true);
+
+EvilExceptionObject.toNumber = function f() { return f(); }
+shouldThrow("EvilExceptionObject*5");
+EvilExceptionObject.toStringExplicit = function f() { return f(); }
+shouldThrow("String(EvilExceptionObject)");
+
+shouldBe("console", "[object Console]");
+shouldBe("typeof console.log", "function");
+
+shouldBe("EmptyObject", "[object CallbackObject]");
+
+for (var i = 0; i < 6; ++i)
+ PropertyCatchalls.x = i;
+shouldBe("PropertyCatchalls.x", 4);
+
+for (var i = 0; i < 6; ++i)
+ var x = PropertyCatchalls.x;
+shouldBe("x", null);
+var make_throw = 'make_throw';
+shouldThrow("PropertyCatchalls[make_throw]=1");
+make_throw = 0;
+shouldThrow("PropertyCatchalls[make_throw]=1");
+
+for (var i = 0; i < 10; ++i) {
+ for (var p in PropertyCatchalls) {
+ if (p == "x")
+ continue;
+ shouldBe("p", i % 10);
+ break;
+ }
+}
+
+PropertyCatchalls.__proto__ = { y: 1 };
+for (var i = 0; i < 6; ++i)
+ var y = PropertyCatchalls.y;
+shouldBe("y", null);
+
+var o = { __proto__: PropertyCatchalls };
+for (var i = 0; i < 6; ++i)
+ var z = PropertyCatchalls.z;
+shouldBe("z", null);
+
+if (failed)
+ throw "Some tests failed";