JavaScriptCore-7603.1.30.0.34

This commit is contained in:
Andrew Hyatt 2017-08-12 09:48:01 -07:00
parent 8a4186c7fc
commit feef99e6ab
2604 changed files with 1177641 additions and 0 deletions

113
API/APICallbackFunction.h Normal file
View File

@ -0,0 +1,113 @@
/*
* Copyright (C) 2013, 2016 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)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSContextRef execRef = toRef(exec);
JSObjectRef functionRef = toRef(exec->jsCallee());
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)
throwException(exec, scope, 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)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* constructor = exec->jsCallee();
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) {
throwException(exec, scope, toJS(exec, exception));
return JSValue::encode(toJS(exec, exception));
}
// result must be a valid JSValue.
if (!result)
return throwVMTypeError(exec, scope);
return JSValue::encode(toJS(result));
}
return JSValue::encode(toJS(JSObjectMake(ctx, jsCast<JSCallbackConstructor*>(constructor)->classRef(), 0)));
}
} // namespace JSC
#endif // APICallbackFunction_h

171
API/APICast.h Normal file
View File

@ -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

65
API/APIUtils.h Normal file
View File

@ -0,0 +1,65 @@
/*
* Copyright (C) 2016 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 APIUtils_h
#define APIUtils_h
#include "Exception.h"
#include "JSCJSValue.h"
#include "JSGlobalObjectInspectorController.h"
#include "JSValueRef.h"
enum class ExceptionStatus {
DidThrow,
DidNotThrow
};
inline ExceptionStatus handleExceptionIfNeeded(JSC::ExecState* exec, JSValueRef* returnedExceptionRef)
{
JSC::VM& vm = exec->vm();
auto scope = DECLARE_CATCH_SCOPE(vm);
if (UNLIKELY(scope.exception())) {
JSC::Exception* exception = scope.exception();
if (returnedExceptionRef)
*returnedExceptionRef = toRef(exec, exception->value());
scope.clearException();
#if ENABLE(REMOTE_INSPECTOR)
exec->vmEntryGlobalObject()->inspectorController().reportAPIException(exec, exception);
#endif
return ExceptionStatus::DidThrow;
}
return ExceptionStatus::DidNotThrow;
}
inline void setException(JSC::ExecState* exec, JSValueRef* returnedExceptionRef, JSC::JSValue exception)
{
if (returnedExceptionRef)
*returnedExceptionRef = toRef(exec, exception);
#if ENABLE(REMOTE_INSPECTOR)
exec->vmEntryGlobalObject()->inspectorController().reportAPIException(exec, JSC::Exception::create(exec->vm(), exception));
#endif
}
#endif /* APIUtils_h */

58
API/JSAPIWrapperObject.h Normal file
View File

@ -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

111
API/JSAPIWrapperObject.mm Normal file
View File

@ -0,0 +1,111 @@
/*
* 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.
*/
#include "config.h"
#include "JSAPIWrapperObject.h"
#include "JSCInlines.h"
#include "JSCallbackObject.h"
#include "JSVirtualMachineInternal.h"
#include "Structure.h"
#include <wtf/NeverDestroyed.h>
#if JSC_OBJC_API_ENABLED
class JSAPIWrapperObjectHandleOwner : public JSC::WeakHandleOwner {
public:
void finalize(JSC::Handle<JSC::Unknown>, void*) override;
bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::SlotVisitor&) override;
};
static JSAPIWrapperObjectHandleOwner* jsAPIWrapperObjectHandleOwner()
{
static NeverDestroyed<JSAPIWrapperObjectHandleOwner> jsWrapperObjectHandleOwner;
return &jsWrapperObjectHandleOwner.get();
}
void JSAPIWrapperObjectHandleOwner::finalize(JSC::Handle<JSC::Unknown> handle, void*)
{
JSC::JSAPIWrapperObject* wrapperObject = static_cast<JSC::JSAPIWrapperObject*>(handle.get().asCell());
if (!wrapperObject->wrappedObject())
return;
JSC::Heap::heap(wrapperObject)->releaseSoon(adoptNS(static_cast<id>(wrapperObject->wrappedObject())));
JSC::WeakSet::deallocate(JSC::WeakImpl::asWeakImpl(handle.slot()));
}
bool JSAPIWrapperObjectHandleOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, JSC::SlotVisitor& visitor)
{
JSC::JSAPIWrapperObject* wrapperObject = JSC::jsCast<JSC::JSAPIWrapperObject*>(handle.get().asCell());
// We use the JSGlobalObject when processing weak handles to prevent the situation where using
// the same Objective-C object in multiple global objects keeps all of the global objects alive.
if (!wrapperObject->wrappedObject())
return false;
return JSC::Heap::isMarked(wrapperObject->structure()->globalObject()) && visitor.containsOpaqueRoot(wrapperObject->wrappedObject());
}
namespace JSC {
template <> const ClassInfo JSCallbackObject<JSAPIWrapperObject>::s_info = { "JSAPIWrapperObject", &Base::s_info, 0, CREATE_METHOD_TABLE(JSCallbackObject) };
template<> const bool JSCallbackObject<JSAPIWrapperObject>::needsDestruction = true;
template <>
Structure* JSCallbackObject<JSAPIWrapperObject>::createStructure(VM& vm, JSGlobalObject* globalObject, JSValue proto)
{
return Structure::create(vm, globalObject, proto, TypeInfo(ObjectType, StructureFlags), &s_info);
}
JSAPIWrapperObject::JSAPIWrapperObject(VM& vm, Structure* structure)
: Base(vm, structure)
, m_wrappedObject(0)
{
}
void JSAPIWrapperObject::finishCreation(VM& vm)
{
Base::finishCreation(vm);
WeakSet::allocate(this, jsAPIWrapperObjectHandleOwner(), 0); // Balanced in JSAPIWrapperObjectHandleOwner::finalize.
}
void JSAPIWrapperObject::setWrappedObject(void* wrappedObject)
{
ASSERT(!m_wrappedObject);
m_wrappedObject = [static_cast<id>(wrappedObject) retain];
}
void JSAPIWrapperObject::visitChildren(JSCell* cell, JSC::SlotVisitor& visitor)
{
JSAPIWrapperObject* thisObject = JSC::jsCast<JSAPIWrapperObject*>(cell);
Base::visitChildren(cell, visitor);
void* wrappedObject = thisObject->wrappedObject();
if (wrappedObject)
scanExternalObjectGraph(visitor.vm(), visitor, wrappedObject);
}
} // namespace JSC
#endif // JSC_OBJC_API_ENABLED

191
API/JSBase.cpp Normal file
View File

@ -0,0 +1,191 @@
/*
* Copyright (C) 2006, 2007, 2013, 2016 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()));
NakedPtr<Exception> evaluationException;
JSValue returnValue = profiledEvaluate(globalObject->globalExec(), ProfilingReason::API, 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()));
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.collectSync(CollectionScope::Eden);
}
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

144
API/JSBase.h Normal file
View File

@ -0,0 +1,144 @@
/*
* 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;
/*! @typedef JSTypedArrayBytesDeallocator A function used to deallocate bytes passed to a Typed Array constructor. The function should take two arguments. The first is a pointer to the bytes that were originally passed to the Typed Array constructor. The second is a pointer to additional information desired at the time the bytes are to be freed. */
typedef void (*JSTypedArrayBytesDeallocator)(void* bytes, void* deallocatorContext);
/* 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) && !defined(__i386__)) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)))
#endif
#endif /* JSBase_h */

54
API/JSBasePrivate.h Normal file
View File

@ -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 */

View File

@ -0,0 +1,65 @@
/*
* 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 failNextNewCodeBlock(JSContextRef context)
{
ExecState* exec= toJS(context);
JSLockHolder holder(exec);
return toRef(exec, failNextNewCodeBlock(exec));
}
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)));
}
JSValueRef setNeverOptimize(JSContextRef context, JSValueRef theFunctionValueRef)
{
ExecState* exec= toJS(context);
JSLockHolder holder(exec);
return toRef(exec, setNeverOptimize(toJS(exec, theFunctionValueRef)));
}
} // namespace JSC

41
API/JSCTestRunnerUtils.h Normal file
View File

@ -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 JSCTestRunnerUtils_h
#define JSCTestRunnerUtils_h
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSValueRef.h>
namespace JSC {
JS_EXPORT_PRIVATE JSValueRef failNextNewCodeBlock(JSContextRef);
JS_EXPORT_PRIVATE JSValueRef numberOfDFGCompiles(JSContextRef, JSValueRef theFunction);
JS_EXPORT_PRIVATE JSValueRef setNeverInline(JSContextRef, JSValueRef theFunction);
JS_EXPORT_PRIVATE JSValueRef setNeverOptimize(JSContextRef, JSValueRef theFunction);
} // namespace JSC
#endif // JSCTestRunnerUtils_h

View File

@ -0,0 +1,73 @@
/*
* 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"
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 ConstructType::Host;
}
} // namespace JSC

View File

@ -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 | ImplementsDefaultHasInstance;
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

View File

@ -0,0 +1,72 @@
/*
* Copyright (C) 2006, 2008, 2016 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"
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)
{
Structure* structure = globalObject->callbackFunctionStructure();
JSCallbackFunction* function = new (NotNull, allocateCell<JSCallbackFunction>(vm.heap)) JSCallbackFunction(vm, structure, callback);
function->finishCreation(vm, name);
return function;
}
CallType JSCallbackFunction::getCallData(JSCell*, CallData& callData)
{
callData.native.function = APICallbackFunction::call<JSCallbackFunction>;
return CallType::Host;
}
} // namespace JSC

63
API/JSCallbackFunction.h Normal file
View File

@ -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

64
API/JSCallbackObject.cpp Normal file
View File

@ -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

243
API/JSCallbackObject.h Normal file
View File

@ -0,0 +1,243 @@
/*
* Copyright (C) 2006-2016 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)
{
JSPrivatePropertyMap* properties = m_privateProperties.get();
if (!properties)
return;
properties->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)
{
LockHolder locker(m_lock);
WriteBarrier<Unknown> empty;
m_propertyMap.add(propertyName.impl(), empty).iterator->value.set(vm, owner, value);
}
void deletePrivateProperty(const Identifier& propertyName)
{
LockHolder locker(m_lock);
m_propertyMap.remove(propertyName.impl());
}
void visitChildren(SlotVisitor& visitor)
{
LockHolder locker(m_lock);
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;
Lock m_lock;
};
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 | 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();
// FIXME: We should fix the warnings for extern-template in JSObject template classes: https://bugs.webkit.org/show_bug.cgi?id=161979
#if COMPILER(CLANG)
#if __has_warning("-Wundefined-var-template")
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundefined-var-template"
#endif
#endif
DECLARE_INFO;
#if COMPILER(CLANG)
#if __has_warning("-Wundefined-var-template")
#pragma clang diagnostic pop
#endif
#endif
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 bool put(JSCell*, ExecState*, PropertyName, JSValue, PutPropertySlot&);
static bool 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*, EncodedJSValue, PropertyName);
static EncodedJSValue callbackGetter(ExecState*, EncodedJSValue, PropertyName);
std::unique_ptr<JSCallbackObjectData> m_callbackObjectData;
const ClassInfo* m_classInfo;
};
} // namespace JSC
// include the actual template class implementation
#include "JSCallbackObjectFunctions.h"
#endif // JSCallbackObject_h

View File

@ -0,0 +1,701 @@
/*
* Copyright (C) 2006, 2008, 2016 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()
{
VM* vm = this->HeapCell::vm();
vm->currentlyDestructingCallbackObject = this;
ASSERT(m_classInfo);
vm->currentlyDestructingCallbackObjectClassInfo = m_classInfo;
JSObjectRef thisRef = toRef(static_cast<JSObject*>(this));
for (JSClassRef jsClass = classRef(); jsClass; jsClass = jsClass->parentClass) {
if (JSObjectFinalizeCallback finalize = jsClass->finalize)
finalize(thisRef);
}
vm->currentlyDestructingCallbackObject = nullptr;
vm->currentlyDestructingCallbackObjectClassInfo = nullptr;
}
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));
}
m_classInfo = this->classInfo();
}
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)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
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) {
throwException(exec, scope, 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)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
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) {
throwException(exec, scope, toJS(exec, exception));
return jsUndefined();
}
if (result)
return toJS(exec, result);
}
}
return Parent::defaultValue(object, exec, hint);
}
template <class Parent>
bool JSCallbackObject<Parent>::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
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)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return result;
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (StaticValueEntry* entry = staticValues->get(name)) {
if (entry->attributes & kJSPropertyAttributeReadOnly)
return false;
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)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return result;
}
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(name)) {
PropertySlot getSlot(thisObject, PropertySlot::InternalMethodType::VMInquiry);
if (Parent::getOwnPropertySlot(thisObject, exec, propertyName, getSlot))
return Parent::put(thisObject, exec, propertyName, value, slot);
if (entry->attributes & kJSPropertyAttributeReadOnly)
return false;
return thisObject->JSCallbackObject<Parent>::putDirect(vm, propertyName, value); // put as override property
}
}
}
}
return Parent::put(thisObject, exec, propertyName, value, slot);
}
template <class Parent>
bool JSCallbackObject<Parent>::putByIndex(JSCell* cell, ExecState* exec, unsigned propertyIndex, JSValue value, bool shouldThrow)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
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)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return result;
}
if (OpaqueJSClassStaticValuesTable* staticValues = jsClass->staticValues(exec)) {
if (StaticValueEntry* entry = staticValues->get(propertyName.impl())) {
if (entry->attributes & kJSPropertyAttributeReadOnly)
return false;
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)
throwException(exec, scope, toJS(exec, exception));
if (result || exception)
return result;
}
}
}
if (OpaqueJSClassStaticFunctionsTable* staticFunctions = jsClass->staticFunctions(exec)) {
if (StaticFunctionEntry* entry = staticFunctions->get(propertyName.impl())) {
if (entry->attributes & kJSPropertyAttributeReadOnly)
return false;
break;
}
}
}
return Parent::putByIndex(thisObject, exec, propertyIndex, value, shouldThrow);
}
template <class Parent>
bool JSCallbackObject<Parent>::deleteProperty(JSCell* cell, ExecState* exec, PropertyName propertyName)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
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)
throwException(exec, scope, 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 ConstructType::Host;
}
}
return ConstructType::None;
}
template <class Parent>
EncodedJSValue JSCallbackObject<Parent>::construct(ExecState* exec)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* constructor = exec->jsCallee();
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)
throwException(exec, scope, 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)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
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)
throwException(exec, scope, 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 CallType::Host;
}
}
return CallType::None;
}
template <class Parent>
EncodedJSValue JSCallbackObject<Parent>::call(ExecState* exec)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSContextRef execRef = toRef(exec);
JSObjectRef functionRef = toRef(exec->jsCallee());
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)
throwException(exec, scope, 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)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
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) {
throwException(exec, scope, toJS(exec, exception));
return jsUndefined();
}
if (value)
return toJS(exec, value);
}
}
}
}
}
return JSValue();
}
template <class Parent>
EncodedJSValue JSCallbackObject<Parent>::staticFunctionGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName propertyName)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObj = asCallbackObject(thisValue);
// Check for cached or override property.
PropertySlot slot2(thisObj, PropertySlot::InternalMethodType::VMInquiry);
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) {
JSObject* o = JSCallbackFunction::create(vm, thisObj->globalObject(), callAsFunction, name);
thisObj->putDirect(vm, propertyName, o, entry->attributes);
return JSValue::encode(o);
}
}
}
}
}
return JSValue::encode(throwException(exec, scope, createReferenceError(exec, ASCIILiteral("Static function property defined with NULL callAsFunction callback."))));
}
template <class Parent>
EncodedJSValue JSCallbackObject<Parent>::callbackGetter(ExecState* exec, EncodedJSValue thisValue, PropertyName propertyName)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSCallbackObject* thisObj = asCallbackObject(thisValue);
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) {
throwException(exec, scope, toJS(exec, exception));
return JSValue::encode(jsUndefined());
}
if (value)
return JSValue::encode(toJS(exec, value));
}
}
}
return JSValue::encode(throwException(exec, scope, createReferenceError(exec, ASCIILiteral("hasProperty callback returned true for a property that doesn't exist."))));
}
} // namespace JSC

204
API/JSClassRef.cpp Normal file
View File

@ -0,0 +1,204 @@
/*
* 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();
}
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->setPrototypeDirect(exec->vm(), parentPrototype);
}
jsClassData.cachedPrototype = Weak<JSObject>(prototype);
return prototype;
}

127
API/JSClassRef.h Normal file
View File

@ -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

238
API/JSContext.h Normal file
View File

@ -0,0 +1,238 @@
/*
* 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 A JSContext is a JavaScript execution environment. All
JavaScript execution takes place within a context, and all JavaScript values
are tied to a context.
*/
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;
/*!
@functiongroup 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).
*/
@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 uncaught exceptions
occurring within a callback from JavaScript to be rethrown upon return.
Setting this value to nil will cause all exceptions occurring
within a callback from JavaScript to be silently caught.
*/
@property (copy) void(^exceptionHandler)(JSContext *context, JSValue *exception);
/*!
@property
@discussion All instances of JSContext are associated with a JSVirtualMachine.
*/
@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.
@result The JSValue for the global object's property.
*/
- (JSValue *)objectForKeyedSubscript:(id)key;
/*!
@method
@abstract Set a particular property on the global object.
*/
- (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.
@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

354
API/JSContext.mm Normal file
View File

@ -0,0 +1,354 @@
/*
* 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"
#import "APICast.h"
#import "JSCInlines.h"
#import "JSContextInternal.h"
#import "JSContextPrivate.h"
#import "JSContextRefInternal.h"
#import "JSGlobalObject.h"
#import "JSValueInternal.h"
#import "JSVirtualMachineInternal.h"
#import "JSWrapperMap.h"
#import "JavaScriptCore.h"
#import "ObjcRuntimeExtras.h"
#import "StrongInlines.h"
#if JSC_OBJC_API_ENABLED
@implementation JSContext {
JSVirtualMachine *m_virtualMachine;
JSGlobalContextRef m_context;
JSWrapperMap *m_wrapperMap;
JSC::Strong<JSC::JSObject> m_exception;
}
@synthesize exceptionHandler;
- (JSGlobalContextRef)JSGlobalContextRef
{
return m_context;
}
- (instancetype)init
{
return [self initWithVirtualMachine:[[[JSVirtualMachine alloc] init] autorelease]];
}
- (instancetype)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine
{
self = [super init];
if (!self)
return nil;
m_virtualMachine = [virtualMachine retain];
m_context = JSGlobalContextCreateInGroup(getGroupFromVirtualMachine(virtualMachine), 0);
m_wrapperMap = [[JSWrapperMap alloc] initWithContext:self];
self.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
};
[m_virtualMachine addContext:self forGlobalContextRef:m_context];
return self;
}
- (void)dealloc
{
m_exception.clear();
[m_wrapperMap release];
JSGlobalContextRelease(m_context);
[m_virtualMachine release];
[self.exceptionHandler release];
[super dealloc];
}
- (JSValue *)evaluateScript:(NSString *)script
{
return [self evaluateScript:script withSourceURL:nil];
}
- (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL
{
JSValueRef exceptionValue = nullptr;
JSStringRef scriptJS = JSStringCreateWithCFString((CFStringRef)script);
JSStringRef sourceURLJS = sourceURL ? JSStringCreateWithCFString((CFStringRef)[sourceURL absoluteString]) : nullptr;
JSValueRef result = JSEvaluateScript(m_context, scriptJS, nullptr, sourceURLJS, 0, &exceptionValue);
if (sourceURLJS)
JSStringRelease(sourceURLJS);
JSStringRelease(scriptJS);
if (exceptionValue)
return [self valueFromNotifyException:exceptionValue];
return [JSValue valueWithJSValueRef:result inContext:self];
}
- (void)setException:(JSValue *)value
{
JSC::JSLockHolder locker(toJS(m_context));
if (value)
m_exception.set(toJS(m_context)->vm(), toJS(JSValueToObject(m_context, valueInternalValue(value), 0)));
else
m_exception.clear();
}
- (JSValue *)exception
{
if (!m_exception)
return nil;
return [JSValue valueWithJSValueRef:toRef(m_exception.get()) inContext:self];
}
- (JSWrapperMap *)wrapperMap
{
return m_wrapperMap;
}
- (JSValue *)globalObject
{
return [JSValue valueWithJSValueRef:JSContextGetGlobalObject(m_context) inContext:self];
}
+ (JSContext *)currentContext
{
WTFThreadData& threadData = wtfThreadData();
CallbackData *entry = (CallbackData *)threadData.m_apiData;
return entry ? entry->context : nil;
}
+ (JSValue *)currentThis
{
WTFThreadData& threadData = wtfThreadData();
CallbackData *entry = (CallbackData *)threadData.m_apiData;
if (!entry)
return nil;
return [JSValue valueWithJSValueRef:entry->thisValue inContext:[JSContext currentContext]];
}
+ (JSValue *)currentCallee
{
WTFThreadData& threadData = wtfThreadData();
CallbackData *entry = (CallbackData *)threadData.m_apiData;
if (!entry)
return nil;
return [JSValue valueWithJSValueRef:entry->calleeValue inContext:[JSContext currentContext]];
}
+ (NSArray *)currentArguments
{
WTFThreadData& threadData = wtfThreadData();
CallbackData *entry = (CallbackData *)threadData.m_apiData;
if (!entry)
return nil;
if (!entry->currentArguments) {
JSContext *context = [JSContext currentContext];
size_t count = entry->argumentCount;
JSValue * argumentArray[count];
for (size_t i =0; i < count; ++i)
argumentArray[i] = [JSValue valueWithJSValueRef:entry->arguments[i] inContext:context];
entry->currentArguments = [[NSArray alloc] initWithObjects:argumentArray count:count];
}
return entry->currentArguments;
}
- (JSVirtualMachine *)virtualMachine
{
return m_virtualMachine;
}
- (NSString *)name
{
JSStringRef name = JSGlobalContextCopyName(m_context);
if (!name)
return nil;
return (NSString *)adoptCF(JSStringCopyCFString(kCFAllocatorDefault, name)).autorelease();
}
- (void)setName:(NSString *)name
{
JSStringRef nameJS = name ? JSStringCreateWithCFString((CFStringRef)[[name copy] autorelease]) : nullptr;
JSGlobalContextSetName(m_context, nameJS);
if (nameJS)
JSStringRelease(nameJS);
}
- (BOOL)_remoteInspectionEnabled
{
return JSGlobalContextGetRemoteInspectionEnabled(m_context);
}
- (void)_setRemoteInspectionEnabled:(BOOL)enabled
{
JSGlobalContextSetRemoteInspectionEnabled(m_context, enabled);
}
- (BOOL)_includesNativeCallStackWhenReportingExceptions
{
return JSGlobalContextGetIncludesNativeCallStackWhenReportingExceptions(m_context);
}
- (void)_setIncludesNativeCallStackWhenReportingExceptions:(BOOL)includeNativeCallStack
{
JSGlobalContextSetIncludesNativeCallStackWhenReportingExceptions(m_context, includeNativeCallStack);
}
- (CFRunLoopRef)_debuggerRunLoop
{
return JSGlobalContextGetDebuggerRunLoop(m_context);
}
- (void)_setDebuggerRunLoop:(CFRunLoopRef)runLoop
{
JSGlobalContextSetDebuggerRunLoop(m_context, runLoop);
}
@end
@implementation JSContext(SubscriptSupport)
- (JSValue *)objectForKeyedSubscript:(id)key
{
return [self globalObject][key];
}
- (void)setObject:(id)object forKeyedSubscript:(NSObject <NSCopying> *)key
{
[self globalObject][key] = object;
}
@end
@implementation JSContext (Internal)
- (instancetype)initWithGlobalContextRef:(JSGlobalContextRef)context
{
self = [super init];
if (!self)
return nil;
JSC::JSGlobalObject* globalObject = toJS(context)->lexicalGlobalObject();
m_virtualMachine = [[JSVirtualMachine virtualMachineWithContextGroupRef:toRef(&globalObject->vm())] retain];
ASSERT(m_virtualMachine);
m_context = JSGlobalContextRetain(context);
m_wrapperMap = [[JSWrapperMap alloc] initWithContext:self];
self.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
};
[m_virtualMachine addContext:self forGlobalContextRef:m_context];
return self;
}
- (void)notifyException:(JSValueRef)exceptionValue
{
self.exceptionHandler(self, [JSValue valueWithJSValueRef:exceptionValue inContext:self]);
}
- (JSValue *)valueFromNotifyException:(JSValueRef)exceptionValue
{
[self notifyException:exceptionValue];
return [JSValue valueWithUndefinedInContext:self];
}
- (BOOL)boolFromNotifyException:(JSValueRef)exceptionValue
{
[self notifyException:exceptionValue];
return NO;
}
- (void)beginCallbackWithData:(CallbackData *)callbackData calleeValue:(JSValueRef)calleeValue thisValue:(JSValueRef)thisValue argumentCount:(size_t)argumentCount arguments:(const JSValueRef *)arguments
{
WTFThreadData& threadData = wtfThreadData();
[self retain];
CallbackData *prevStack = (CallbackData *)threadData.m_apiData;
*callbackData = (CallbackData){ prevStack, self, [self.exception retain], calleeValue, thisValue, argumentCount, arguments, nil };
threadData.m_apiData = callbackData;
self.exception = nil;
}
- (void)endCallbackWithData:(CallbackData *)callbackData
{
WTFThreadData& threadData = wtfThreadData();
self.exception = callbackData->preservedException;
[callbackData->preservedException release];
[callbackData->currentArguments release];
threadData.m_apiData = callbackData->next;
[self release];
}
- (JSValue *)wrapperForObjCObject:(id)object
{
JSC::JSLockHolder locker(toJS(m_context));
return [m_wrapperMap jsWrapperForObject:object];
}
- (JSValue *)wrapperForJSObject:(JSValueRef)value
{
JSC::JSLockHolder locker(toJS(m_context));
return [m_wrapperMap objcWrapperForJSValueRef:value];
}
+ (JSContext *)contextWithJSGlobalContextRef:(JSGlobalContextRef)globalContext
{
JSVirtualMachine *virtualMachine = [JSVirtualMachine virtualMachineWithContextGroupRef:toRef(&toJS(globalContext)->vm())];
JSContext *context = [virtualMachine contextForGlobalContextRef:globalContext];
if (!context)
context = [[[JSContext alloc] initWithGlobalContextRef:globalContext] autorelease];
return context;
}
@end
WeakContextRef::WeakContextRef(JSContext *context)
{
objc_initWeak(&m_weakContext, context);
}
WeakContextRef::~WeakContextRef()
{
objc_destroyWeak(&m_weakContext);
}
JSContext * WeakContextRef::get()
{
return objc_loadWeak(&m_weakContext);
}
void WeakContextRef::set(JSContext *context)
{
objc_storeWeak(&m_weakContext, context);
}
#endif

80
API/JSContextInternal.h Normal file
View File

@ -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

57
API/JSContextPrivate.h Normal file
View File

@ -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

431
API/JSContextRef.cpp Normal file
View File

@ -0,0 +1,431 @@
/*
* Copyright (C) 2006, 2007, 2013, 2016 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) const
{
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.
JSCell* 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->hasLineAndColumnInfo()) {
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;
mutable 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().targetRunLoop();
#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().setTargetRunLoop(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

158
API/JSContextRef.h Normal file
View File

@ -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 */

View File

@ -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

View File

@ -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 runLoop) CF_AVAILABLE(10_10, 8_0);
#endif
#ifdef __cplusplus
}
#endif
#endif // JSContextRefInternal_h

135
API/JSContextRefPrivate.h Normal file
View File

@ -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 group, double limit, JSShouldTerminateCallback callback, 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 group) 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 includesNativeCallStack 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 */

146
API/JSExport.h Normal file
View File

@ -0,0 +1,146 @@
/*
* 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 objects and
classes -- including properties, instance methods, class methods, and
initializers -- to JavaScript.
@discussion When an Objective-C object is exported to JavaScript, a JavaScript
wrapper object is created.
In JavaScript, inheritance works via a chain of prototype objects.
For each Objective-C class in each JSContext, an object appropriate for use
as a prototype will be provided. For the class NSObject the prototype
will be the Object prototype. For all other Objective-C
classes a prototype will be created. The prototype for a given
Objective-C class will have its internal [Prototype] property set to point to
the prototype created for 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.
JavaScriptCore also produces a constructor for each Objective-C class. The
constructor has a property named 'prototype' that references the prototype,
and the prototype has a property named 'constructor' that references the
constructor.
By default JavaScriptCore does not export any methods or properties from an
Objective-C class to JavaScript; however methods and properties may be exported
explicitly using JSExport. For each protocol that a class conforms to, if the
protocol incorporates the protocol JSExport, JavaScriptCore exports the methods
and properties in that protocol to JavaScript
For each exported instance method JavaScriptCore will assign a corresponding
JavaScript function to the prototype. For each exported Objective-C property
JavaScriptCore will assign a corresponding JavaScript accessor to the prototype.
For each exported class method JavaScriptCore will assign a corresponding
JavaScript function to the constructor. 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.
JSExport supports properties, arguments, and return values of the following types:
Primitive numbers: signed values up to 32-bits convert using JSValue's
valueWithInt32/toInt32. Unsigned values up to 32-bits convert using JSValue's
valueWithUInt32/toUInt32. All other numeric values convert using JSValue's
valueWithDouble/toDouble.
BOOL: values convert using JSValue's valueWithBool/toBool.
id: values convert using JSValue's valueWithObject/toObject.
Objective-C instance pointers: Pointers convert using JSValue's
valueWithObjectOfClass/toObject.
C structs: C structs for CGPoint, NSRange, CGRect, and CGSize convert using
JSValue's appropriate methods. Other C structs are not supported.
Blocks: Blocks convert using JSValue's valueWithObject/toObject.
All objects that conform to JSExport convert to JavaScript wrapper objects,
even if they subclass classes that would otherwise behave differently. For
example, if a subclass of NSString conforms to JSExport, it converts to
JavaScript as a wrapper object rather than a JavaScript string.
*/
@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

81
API/JSManagedValue.h Normal file
View File

@ -0,0 +1,81 @@
/*
* 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 the JSManagedValue's
JSValue is reachable through the JavaScript object graph,
or through the Objective-C object graph reported to the JSVirtualMachine using
addManagedReference:withOwner:, the corresponding JSValue will
be retained. However, if neither graph reaches the JSManagedValue, the
corresponding JSValue will be released and set to nil.
The primary use for a JSManagedValue is to store a JSValue in an Objective-C
or Swift object that is exported to JavaScript. It is incorrect to store a JSValue
in an object that is exported to JavaScript, since doing so creates a retain cycle.
*/
NS_CLASS_AVAILABLE(10_9, 7_0)
@interface JSManagedValue : NSObject
/*!
@method
@abstract Create a JSManagedValue from a JSValue.
@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.
@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

311
API/JSManagedValue.mm Normal file
View File

@ -0,0 +1,311 @@
/*
* Copyright (C) 2013, 2016 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 "config.h"
#import "JSManagedValue.h"
#if JSC_OBJC_API_ENABLED
#import "APICast.h"
#import "Heap.h"
#import "JSContextInternal.h"
#import "JSValueInternal.h"
#import "Weak.h"
#import "WeakHandleOwner.h"
#import "ObjcRuntimeExtras.h"
#import "JSCInlines.h"
#import <wtf/NeverDestroyed.h>
#import <wtf/spi/cocoa/NSMapTableSPI.h>
class JSManagedValueHandleOwner : public JSC::WeakHandleOwner {
public:
void finalize(JSC::Handle<JSC::Unknown>, void* context) override;
bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::SlotVisitor&) override;
};
static JSManagedValueHandleOwner* managedValueHandleOwner()
{
static NeverDestroyed<JSManagedValueHandleOwner> jsManagedValueHandleOwner;
return &jsManagedValueHandleOwner.get();
}
class WeakValueRef {
public:
WeakValueRef()
: m_tag(NotSet)
{
}
~WeakValueRef()
{
clear();
}
void clear()
{
switch (m_tag) {
case NotSet:
return;
case Primitive:
u.m_primitive = JSC::JSValue();
return;
case Object:
u.m_object.clear();
return;
case String:
u.m_string.clear();
return;
}
RELEASE_ASSERT_NOT_REACHED();
}
bool isClear() const
{
switch (m_tag) {
case NotSet:
return true;
case Primitive:
return !u.m_primitive;
case Object:
return !u.m_object;
case String:
return !u.m_string;
}
RELEASE_ASSERT_NOT_REACHED();
}
bool isSet() const { return m_tag != NotSet; }
bool isPrimitive() const { return m_tag == Primitive; }
bool isObject() const { return m_tag == Object; }
bool isString() const { return m_tag == String; }
void setPrimitive(JSC::JSValue primitive)
{
ASSERT(!isSet());
ASSERT(!u.m_primitive);
ASSERT(primitive.isPrimitive());
m_tag = Primitive;
u.m_primitive = primitive;
}
void setObject(JSC::JSObject* object, void* context)
{
ASSERT(!isSet());
ASSERT(!u.m_object);
m_tag = Object;
JSC::Weak<JSC::JSObject> weak(object, managedValueHandleOwner(), context);
u.m_object.swap(weak);
}
void setString(JSC::JSString* string, void* context)
{
ASSERT(!isSet());
ASSERT(!u.m_object);
m_tag = String;
JSC::Weak<JSC::JSString> weak(string, managedValueHandleOwner(), context);
u.m_string.swap(weak);
}
JSC::JSObject* object()
{
ASSERT(isObject());
return u.m_object.get();
}
JSC::JSValue primitive()
{
ASSERT(isPrimitive());
return u.m_primitive;
}
JSC::JSString* string()
{
ASSERT(isString());
return u.m_string.get();
}
private:
enum WeakTypeTag { NotSet, Primitive, Object, String };
WeakTypeTag m_tag;
union WeakValueUnion {
public:
WeakValueUnion ()
: m_primitive(JSC::JSValue())
{
}
~WeakValueUnion()
{
ASSERT(!m_primitive);
}
JSC::JSValue m_primitive;
JSC::Weak<JSC::JSObject> m_object;
JSC::Weak<JSC::JSString> m_string;
} u;
};
@implementation JSManagedValue {
JSC::Weak<JSC::JSGlobalObject> m_globalObject;
RefPtr<JSC::JSLock> m_lock;
WeakValueRef m_weakValue;
NSMapTable *m_owners;
}
+ (JSManagedValue *)managedValueWithValue:(JSValue *)value
{
return [[[self alloc] initWithValue:value] autorelease];
}
+ (JSManagedValue *)managedValueWithValue:(JSValue *)value andOwner:(id)owner
{
JSManagedValue *managedValue = [[self alloc] initWithValue:value];
[value.context.virtualMachine addManagedReference:managedValue withOwner:owner];
return [managedValue autorelease];
}
- (instancetype)init
{
return [self initWithValue:nil];
}
- (instancetype)initWithValue:(JSValue *)value
{
self = [super init];
if (!self)
return nil;
if (!value)
return self;
JSC::ExecState* exec = toJS([value.context JSGlobalContextRef]);
JSC::JSGlobalObject* globalObject = exec->lexicalGlobalObject();
JSC::Weak<JSC::JSGlobalObject> weak(globalObject, managedValueHandleOwner(), self);
m_globalObject.swap(weak);
m_lock = &exec->vm().apiLock();
NSPointerFunctionsOptions weakIDOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
NSPointerFunctionsOptions integerOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsIntegerPersonality;
m_owners = [[NSMapTable alloc] initWithKeyOptions:weakIDOptions valueOptions:integerOptions capacity:1];
JSC::JSValue jsValue = toJS(exec, [value JSValueRef]);
if (jsValue.isObject())
m_weakValue.setObject(JSC::jsCast<JSC::JSObject*>(jsValue.asCell()), self);
else if (jsValue.isString())
m_weakValue.setString(JSC::jsCast<JSC::JSString*>(jsValue.asCell()), self);
else
m_weakValue.setPrimitive(jsValue);
return self;
}
- (void)dealloc
{
JSVirtualMachine *virtualMachine = [[[self value] context] virtualMachine];
if (virtualMachine) {
NSMapTable *copy = [m_owners copy];
for (id owner in [copy keyEnumerator]) {
size_t count = reinterpret_cast<size_t>(NSMapGet(m_owners, owner));
while (count--)
[virtualMachine removeManagedReference:self withOwner:owner];
}
[copy release];
}
[self disconnectValue];
[m_owners release];
[super dealloc];
}
- (void)didAddOwner:(id)owner
{
size_t count = reinterpret_cast<size_t>(NSMapGet(m_owners, owner));
NSMapInsert(m_owners, owner, reinterpret_cast<void*>(count + 1));
}
- (void)didRemoveOwner:(id)owner
{
size_t count = reinterpret_cast<size_t>(NSMapGet(m_owners, owner));
if (!count)
return;
if (count == 1) {
NSMapRemove(m_owners, owner);
return;
}
NSMapInsert(m_owners, owner, reinterpret_cast<void*>(count - 1));
}
- (JSValue *)value
{
WTF::Locker<JSC::JSLock> locker(m_lock.get());
if (!m_lock->vm())
return nil;
JSC::JSLockHolder apiLocker(m_lock->vm());
if (!m_globalObject)
return nil;
if (m_weakValue.isClear())
return nil;
JSC::ExecState* exec = m_globalObject->globalExec();
JSContext *context = [JSContext contextWithJSGlobalContextRef:toGlobalRef(exec)];
JSC::JSValue value;
if (m_weakValue.isPrimitive())
value = m_weakValue.primitive();
else if (m_weakValue.isString())
value = m_weakValue.string();
else
value = m_weakValue.object();
return [JSValue valueWithJSValueRef:toRef(exec, value) inContext:context];
}
- (void)disconnectValue
{
m_globalObject.clear();
m_weakValue.clear();
}
@end
@interface JSManagedValue (PrivateMethods)
- (void)disconnectValue;
@end
bool JSManagedValueHandleOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::SlotVisitor& visitor)
{
JSManagedValue *managedValue = static_cast<JSManagedValue *>(context);
return visitor.containsOpaqueRoot(managedValue);
}
void JSManagedValueHandleOwner::finalize(JSC::Handle<JSC::Unknown>, void* context)
{
JSManagedValue *managedValue = static_cast<JSManagedValue *>(context);
[managedValue disconnectValue];
}
#endif // JSC_OBJC_API_ENABLED

View File

@ -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

669
API/JSObjectRef.cpp Normal file
View File

@ -0,0 +1,669 @@
/*
* Copyright (C) 2006, 2007, 2008, 2016 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 "APIUtils.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 "JSCInlines.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 "PropertyNameArray.h"
#include "RegExpConstructor.h"
#if ENABLE(REMOTE_INSPECTOR)
#include "JSGlobalObjectInspectorController.h"
#endif
using namespace JSC;
JSClassRef JSClassCreate(const JSClassDefinition* definition)
{
initializeThreading();
auto jsClass = (definition->attributes & kJSClassAttributeNoAutomaticPrototype)
? OpaqueJSClass::createNoAutomaticPrototype(definition)
: OpaqueJSClass::create(definition);
return &jsClass.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->setPrototypeDirect(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()));
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(), JSValue(), 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->getPrototypeDirect());
}
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->setPrototype(exec->vm(), 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);
VM& vm = exec->vm();
JSLockHolder locker(vm);
auto scope = DECLARE_CATCH_SCOPE(vm);
JSObject* jsObject = toJS(object);
Identifier name(propertyName->identifier(&exec->vm()));
JSValue jsValue = toJS(exec, value);
bool doesNotHaveProperty = attributes && !jsObject->hasProperty(exec, name);
if (LIKELY(!scope.exception())) {
if (doesNotHaveProperty) {
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;
}
// API objects have private properties, which may get accessed during destruction. This
// helper lets us get the ClassInfo of an API object from a function that may get called
// during destruction.
static const ClassInfo* classInfoPrivate(JSObject* jsObject)
{
VM* vm = jsObject->vm();
if (vm->currentlyDestructingCallbackObject != jsObject)
return jsObject->classInfo();
return vm->currentlyDestructingCallbackObjectClassInfo;
}
void* JSObjectGetPrivate(JSObjectRef object)
{
JSObject* jsObject = uncheckedToJS(object);
const ClassInfo* classInfo = classInfoPrivate(jsObject);
// Get wrapped object if proxied
if (classInfo->isSubClassOf(JSProxy::info())) {
jsObject = static_cast<JSProxy*>(jsObject)->target();
classInfo = jsObject->classInfo();
}
if (classInfo->isSubClassOf(JSCallbackObject<JSGlobalObject>::info()))
return static_cast<JSCallbackObject<JSGlobalObject>*>(jsObject)->getPrivate();
if (classInfo->isSubClassOf(JSCallbackObject<JSDestructibleObject>::info()))
return static_cast<JSCallbackObject<JSDestructibleObject>*>(jsObject)->getPrivate();
#if JSC_OBJC_API_ENABLED
if (classInfo->isSubClassOf(JSCallbackObject<JSAPIWrapperObject>::info()))
return static_cast<JSCallbackObject<JSAPIWrapperObject>*>(jsObject)->getPrivate();
#endif
return 0;
}
bool JSObjectSetPrivate(JSObjectRef object, void* data)
{
JSObject* jsObject = uncheckedToJS(object);
const ClassInfo* classInfo = classInfoPrivate(jsObject);
// Get wrapped object if proxied
if (classInfo->isSubClassOf(JSProxy::info())) {
jsObject = static_cast<JSProxy*>(jsObject)->target();
classInfo = jsObject->classInfo();
}
if (classInfo->isSubClassOf(JSCallbackObject<JSGlobalObject>::info())) {
static_cast<JSCallbackObject<JSGlobalObject>*>(jsObject)->setPrivate(data);
return true;
}
if (classInfo->isSubClassOf(JSCallbackObject<JSDestructibleObject>::info())) {
static_cast<JSCallbackObject<JSDestructibleObject>*>(jsObject)->setPrivate(data);
return true;
}
#if JSC_OBJC_API_ENABLED
if (classInfo->isSubClassOf(JSCallbackObject<JSAPIWrapperObject>::info())) {
static_cast<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) != CallType::None;
}
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 == CallType::None)
return 0;
JSValueRef result = toRef(exec, profiledCall(exec, ProfilingReason::API, 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) != ConstructType::None;
}
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 == ConstructType::None)
return 0;
MarkedArgumentBuffer argList;
for (size_t i = 0; i < argumentCount; i++)
argList.append(toJS(exec, arguments[i]));
JSObjectRef result = toRef(profiledConstruct(exec, ProfilingReason::API, 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()));
}

694
API/JSObjectRef.h Normal file
View File

@ -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 propertyNames 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 */

74
API/JSObjectRefPrivate.h Normal file
View File

@ -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

78
API/JSRemoteInspector.cpp Normal file
View File

@ -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;
}

49
API/JSRemoteInspector.h Normal file
View File

@ -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 */

215
API/JSRetainPtr.h Normal file
View File

@ -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

163
API/JSScriptRef.cpp Normal file
View File

@ -0,0 +1,163 @@
/*
* 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));
}
unsigned hash() const override
{
return m_source.get().hash();
}
StringView source() const override
{
return m_source.get();
}
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()), SourceProviderSourceType::Program)
, m_vm(vm)
, m_source(source.isNull() ? *StringImpl::empty() : *source.impl())
{
}
virtual ~OpaqueJSScript() { }
VM* m_vm;
Ref<StringImpl> m_source;
};
static bool parseScript(VM* vm, const SourceCode& source, ParserError& error)
{
return !!JSC::parse<JSC::ProgramNode>(
vm, source, Identifier(), JSParserBuiltinMode::NotBuiltin,
JSParserStrictMode::NotStrict, JSParserScriptMode::Classic, SourceParseMode::ProgramMode, SuperBinding::NotNeeded,
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);
auto 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.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);
auto 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.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);
}
}

99
API/JSScriptRefPrivate.h Normal file
View File

@ -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 */

133
API/JSStringRef.cpp Normal file
View File

@ -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;
}

148
API/JSStringRef.h Normal file
View File

@ -0,0 +1,148 @@
/*
* 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(_NATIVE_WCHAR_T_DEFINED) /* MSVC */ \
&& (!defined(__WCHAR_MAX__) || (__WCHAR_MAX__ > 0xffffU)) /* ISO C/C++ */ \
&& (!defined(WCHAR_MAX) || (WCHAR_MAX > 0xffffU)) /* RVCT */
/*!
@typedef JSChar
@abstract A UTF-16 code unit. One, or a sequence of two, can encode any Unicode
character. As with all scalar types, endianness depends on the underlying
architecture.
*/
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 */

42
API/JSStringRefBSTR.cpp Normal file
View File

@ -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));
}

62
API/JSStringRefBSTR.h Normal file
View File

@ -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 */

67
API/JSStringRefCF.cpp Normal file
View File

@ -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());
}

60
API/JSStringRefCF.h Normal file
View File

@ -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 */

41
API/JSStringRefPrivate.h Normal file
View File

@ -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 */

331
API/JSTypedArray.cpp Normal file
View File

@ -0,0 +1,331 @@
/*
* Copyright (C) 2015 Dominic Szablewski (dominic@phoboslab.org)
* Copyright (C) 2016 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 COMPUTER, 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 COMPUTER, 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 "JSTypedArray.h"
#include "APICast.h"
#include "APIUtils.h"
#include "ClassInfo.h"
#include "Error.h"
#include "JSArrayBufferViewInlines.h"
#include "JSCInlines.h"
#include "JSDataView.h"
#include "JSGenericTypedArrayViewInlines.h"
#include "JSTypedArrays.h"
#include "TypedArrayController.h"
#include <wtf/RefPtr.h>
using namespace JSC;
// Helper functions.
inline JSTypedArrayType toJSTypedArrayType(TypedArrayType type)
{
switch (type) {
case JSC::TypeDataView:
case NotTypedArray:
return kJSTypedArrayTypeNone;
case TypeInt8:
return kJSTypedArrayTypeInt8Array;
case TypeUint8:
return kJSTypedArrayTypeUint8Array;
case TypeUint8Clamped:
return kJSTypedArrayTypeUint8ClampedArray;
case TypeInt16:
return kJSTypedArrayTypeInt16Array;
case TypeUint16:
return kJSTypedArrayTypeUint16Array;
case TypeInt32:
return kJSTypedArrayTypeInt32Array;
case TypeUint32:
return kJSTypedArrayTypeUint32Array;
case TypeFloat32:
return kJSTypedArrayTypeFloat32Array;
case TypeFloat64:
return kJSTypedArrayTypeFloat64Array;
}
RELEASE_ASSERT_NOT_REACHED();
}
inline TypedArrayType toTypedArrayType(JSTypedArrayType type)
{
switch (type) {
case kJSTypedArrayTypeArrayBuffer:
case kJSTypedArrayTypeNone:
return NotTypedArray;
case kJSTypedArrayTypeInt8Array:
return TypeInt8;
case kJSTypedArrayTypeUint8Array:
return TypeUint8;
case kJSTypedArrayTypeUint8ClampedArray:
return TypeUint8Clamped;
case kJSTypedArrayTypeInt16Array:
return TypeInt16;
case kJSTypedArrayTypeUint16Array:
return TypeUint16;
case kJSTypedArrayTypeInt32Array:
return TypeInt32;
case kJSTypedArrayTypeUint32Array:
return TypeUint32;
case kJSTypedArrayTypeFloat32Array:
return TypeFloat32;
case kJSTypedArrayTypeFloat64Array:
return TypeFloat64;
}
RELEASE_ASSERT_NOT_REACHED();
}
static JSObject* createTypedArray(ExecState* exec, JSTypedArrayType type, RefPtr<ArrayBuffer>&& buffer, size_t offset, size_t length)
{
VM& vm = exec->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSGlobalObject* globalObject = exec->lexicalGlobalObject();
if (!buffer) {
throwOutOfMemoryError(exec, scope);
return nullptr;
}
switch (type) {
case kJSTypedArrayTypeInt8Array:
return JSInt8Array::create(exec, globalObject->typedArrayStructure(TypeInt8), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeInt16Array:
return JSInt16Array::create(exec, globalObject->typedArrayStructure(TypeInt16), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeInt32Array:
return JSInt32Array::create(exec, globalObject->typedArrayStructure(TypeInt32), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeUint8Array:
return JSUint8Array::create(exec, globalObject->typedArrayStructure(TypeUint8), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeUint8ClampedArray:
return JSUint8ClampedArray::create(exec, globalObject->typedArrayStructure(TypeUint8Clamped), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeUint16Array:
return JSUint16Array::create(exec, globalObject->typedArrayStructure(TypeUint16), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeUint32Array:
return JSUint32Array::create(exec, globalObject->typedArrayStructure(TypeUint32), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeFloat32Array:
return JSFloat32Array::create(exec, globalObject->typedArrayStructure(TypeFloat32), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeFloat64Array:
return JSFloat64Array::create(exec, globalObject->typedArrayStructure(TypeFloat64), WTFMove(buffer), offset, length);
case kJSTypedArrayTypeArrayBuffer:
case kJSTypedArrayTypeNone:
RELEASE_ASSERT_NOT_REACHED();
}
return nullptr;
}
// Implementations of the API functions.
JSTypedArrayType JSValueGetTypedArrayType(JSContextRef ctx, JSValueRef valueRef, JSValueRef*)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
JSValue value = toJS(exec, valueRef);
if (!value.isObject())
return kJSTypedArrayTypeNone;
JSObject* object = value.getObject();
if (jsDynamicCast<JSArrayBuffer*>(object))
return kJSTypedArrayTypeArrayBuffer;
return toJSTypedArrayType(object->classInfo()->typedArrayStorageType);
}
JSObjectRef JSObjectMakeTypedArray(JSContextRef ctx, JSTypedArrayType arrayType, size_t length, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
if (arrayType == kJSTypedArrayTypeNone || arrayType == kJSTypedArrayTypeArrayBuffer)
return nullptr;
unsigned elementByteSize = elementSize(toTypedArrayType(arrayType));
auto buffer = ArrayBuffer::tryCreate(length, elementByteSize);
JSObject* result = createTypedArray(exec, arrayType, WTFMove(buffer), 0, length);
if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
return nullptr;
return toRef(result);
}
JSObjectRef JSObjectMakeTypedArrayWithBytesNoCopy(JSContextRef ctx, JSTypedArrayType arrayType, void* bytes, size_t length, JSTypedArrayBytesDeallocator destructor, void* destructorContext, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
if (arrayType == kJSTypedArrayTypeNone || arrayType == kJSTypedArrayTypeArrayBuffer)
return nullptr;
unsigned elementByteSize = elementSize(toTypedArrayType(arrayType));
RefPtr<ArrayBuffer> buffer = ArrayBuffer::createFromBytes(bytes, length, [=](void* p) {
if (destructor)
destructor(p, destructorContext);
});
JSObject* result = createTypedArray(exec, arrayType, WTFMove(buffer), 0, length / elementByteSize);
if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
return nullptr;
return toRef(result);
}
JSObjectRef JSObjectMakeTypedArrayWithArrayBuffer(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef jsBufferRef, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
if (arrayType == kJSTypedArrayTypeNone || arrayType == kJSTypedArrayTypeArrayBuffer)
return nullptr;
JSArrayBuffer* jsBuffer = jsDynamicCast<JSArrayBuffer*>(toJS(jsBufferRef));
if (!jsBuffer) {
setException(exec, exception, createTypeError(exec, "JSObjectMakeTypedArrayWithArrayBuffer expects buffer to be an Array Buffer object"));
return nullptr;
}
RefPtr<ArrayBuffer> buffer = jsBuffer->impl();
unsigned elementByteSize = elementSize(toTypedArrayType(arrayType));
JSObject* result = createTypedArray(exec, arrayType, WTFMove(buffer), 0, buffer->byteLength() / elementByteSize);
if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
return nullptr;
return toRef(result);
}
JSObjectRef JSObjectMakeTypedArrayWithArrayBufferAndOffset(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef jsBufferRef, size_t offset, size_t length, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
if (arrayType == kJSTypedArrayTypeNone || arrayType == kJSTypedArrayTypeArrayBuffer)
return nullptr;
JSArrayBuffer* jsBuffer = jsDynamicCast<JSArrayBuffer*>(toJS(jsBufferRef));
if (!jsBuffer) {
setException(exec, exception, createTypeError(exec, "JSObjectMakeTypedArrayWithArrayBuffer expects buffer to be an Array Buffer object"));
return nullptr;
}
JSObject* result = createTypedArray(exec, arrayType, jsBuffer->impl(), offset, length);
if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
return nullptr;
return toRef(result);
}
void* JSObjectGetTypedArrayBytesPtr(JSContextRef ctx, JSObjectRef objectRef, JSValueRef*)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
JSObject* object = toJS(objectRef);
if (JSArrayBufferView* typedArray = jsDynamicCast<JSArrayBufferView*>(object)) {
ArrayBuffer* buffer = typedArray->possiblySharedBuffer();
buffer->pinAndLock();
return buffer->data();
}
return nullptr;
}
size_t JSObjectGetTypedArrayLength(JSContextRef, JSObjectRef objectRef, JSValueRef*)
{
JSObject* object = toJS(objectRef);
if (JSArrayBufferView* typedArray = jsDynamicCast<JSArrayBufferView*>(object))
return typedArray->length();
return 0;
}
size_t JSObjectGetTypedArrayByteLength(JSContextRef, JSObjectRef objectRef, JSValueRef*)
{
JSObject* object = toJS(objectRef);
if (JSArrayBufferView* typedArray = jsDynamicCast<JSArrayBufferView*>(object))
return typedArray->length() * elementSize(typedArray->classInfo()->typedArrayStorageType);
return 0;
}
size_t JSObjectGetTypedArrayByteOffset(JSContextRef, JSObjectRef objectRef, JSValueRef*)
{
JSObject* object = toJS(objectRef);
if (JSArrayBufferView* typedArray = jsDynamicCast<JSArrayBufferView*>(object))
return typedArray->byteOffset();
return 0;
}
JSObjectRef JSObjectGetTypedArrayBuffer(JSContextRef ctx, JSObjectRef objectRef, JSValueRef*)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
JSObject* object = toJS(objectRef);
if (JSArrayBufferView* typedArray = jsDynamicCast<JSArrayBufferView*>(object))
return toRef(exec->vm().m_typedArrayController->toJS(exec, typedArray->globalObject(), typedArray->possiblySharedBuffer()));
return nullptr;
}
JSObjectRef JSObjectMakeArrayBufferWithBytesNoCopy(JSContextRef ctx, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
auto buffer = ArrayBuffer::createFromBytes(bytes, byteLength, [=](void* p) {
if (bytesDeallocator)
bytesDeallocator(p, deallocatorContext);
});
JSArrayBuffer* jsBuffer = JSArrayBuffer::create(exec->vm(), exec->lexicalGlobalObject()->arrayBufferStructure(ArrayBufferSharingMode::Default), WTFMove(buffer));
if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
return nullptr;
return toRef(jsBuffer);
}
void* JSObjectGetArrayBufferBytesPtr(JSContextRef ctx, JSObjectRef objectRef, JSValueRef*)
{
ExecState* exec = toJS(ctx);
JSLockHolder locker(exec);
JSObject* object = toJS(objectRef);
if (JSArrayBuffer* jsBuffer = jsDynamicCast<JSArrayBuffer*>(object)) {
ArrayBuffer* buffer = jsBuffer->impl();
buffer->pinAndLock();
return buffer->data();
}
return nullptr;
}
size_t JSObjectGetArrayBufferByteLength(JSContextRef, JSObjectRef objectRef, JSValueRef*)
{
JSObject* object = toJS(objectRef);
if (JSArrayBuffer* jsBuffer = jsDynamicCast<JSArrayBuffer*>(object))
return jsBuffer->impl()->byteLength();
return 0;
}

180
API/JSTypedArray.h Normal file
View File

@ -0,0 +1,180 @@
/*
* Copyright (C) 2015 Dominic Szablewski (dominic@phoboslab.org)
* Copyright (C) 2015-2016 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 COMPUTER, 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 COMPUTER, 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 JSTypedArray_h
#define JSTypedArray_h
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSValueRef.h>
#ifdef __cplusplus
extern "C" {
#endif
// ------------- Typed Array functions --------------
/*!
@function
@abstract Creates a JavaScript Typed Array object with the given number of elements.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param length The number of elements to be in the new Typed Array.
@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 JSObjectRef that is a Typed Array with all elements set to zero or NULL if there was an error.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArray(JSContextRef ctx, JSTypedArrayType arrayType, size_t length, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing pointer.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
@param byteLength The number of bytes pointed to by the parameter bytes.
@param bytesDeallocator The allocator to use to deallocate the external buffer when the JSTypedArrayData object is deallocated.
@param deallocatorContext A pointer to pass back to the deallocator.
@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 JSObjectRef Typed Array whose backing store is the same as the one pointed to by bytes or NULL if there was an error.
@discussion If an exception is thrown during this function the bytesDeallocator will always be called.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithBytesNoCopy(JSContextRef ctx, JSTypedArrayType arrayType, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing JavaScript Array Buffer object.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param buffer An Array Buffer object that should be used as the backing store for the created JavaScript Typed Array object.
@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 JSObjectRef that is a Typed Array or NULL if there was an error. The backing store of the Typed Array will be buffer.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithArrayBuffer(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef buffer, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Creates a JavaScript Typed Array object from an existing JavaScript Array Buffer object with the given offset and length.
@param ctx The execution context to use.
@param arrayType A value identifying the type of array to create. If arrayType is kJSTypedArrayTypeNone or kJSTypedArrayTypeArrayBuffer then NULL will be returned.
@param buffer An Array Buffer object that should be used as the backing store for the created JavaScript Typed Array object.
@param byteOffset The byte offset for the created Typed Array. byteOffset should aligned with the element size of arrayType.
@param length The number of elements to include in the Typed Array.
@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 JSObjectRef that is a Typed Array or NULL if there was an error. The backing store of the Typed Array will be buffer.
*/
JS_EXPORT JSObjectRef JSObjectMakeTypedArrayWithArrayBufferAndOffset(JSContextRef ctx, JSTypedArrayType arrayType, JSObjectRef buffer, size_t byteOffset, size_t length, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns a temporary pointer to the backing store of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose backing store pointer to return.
@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 pointer to the raw data buffer that serves as object's backing store or NULL if object is not a Typed Array object.
@discussion The pointer returned by this function is temporary and is not guaranteed to remain valid across JavaScriptCore API calls.
*/
JS_EXPORT void* JSObjectGetTypedArrayBytesPtr(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the length of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose length to return.
@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 length of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the byte length of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose byte length to return.
@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 byte length of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayByteLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the byte offset of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The Typed Array object whose byte offset to return.
@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 byte offset of the Typed Array object or 0 if the object is not a Typed Array object.
*/
JS_EXPORT size_t JSObjectGetTypedArrayByteOffset(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the JavaScript Array Buffer object that is used as the backing of a JavaScript Typed Array object.
@param ctx The execution context to use.
@param object The JSObjectRef whose Typed Array type data pointer to obtain.
@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 JSObjectRef with a JSTypedArrayType of kJSTypedArrayTypeArrayBuffer or NULL if object is not a Typed Array.
*/
JS_EXPORT JSObjectRef JSObjectGetTypedArrayBuffer(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
// ------------- Array Buffer functions -------------
/*!
@function
@abstract Creates a JavaScript Array Buffer object from an existing pointer.
@param ctx The execution context to use.
@param bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
@param byteLength The number of bytes pointed to by the parameter bytes.
@param bytesDeallocator The allocator to use to deallocate the external buffer when the Typed Array data object is deallocated.
@param deallocatorContext A pointer to pass back to the deallocator.
@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 JSObjectRef Array Buffer whose backing store is the same as the one pointed to by bytes or NULL if there was an error.
@discussion If an exception is thrown during this function the bytesDeallocator will always be called.
*/
JS_EXPORT JSObjectRef JSObjectMakeArrayBufferWithBytesNoCopy(JSContextRef ctx, void* bytes, size_t byteLength, JSTypedArrayBytesDeallocator bytesDeallocator, void* deallocatorContext, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns a pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object.
@param object The Array Buffer object whose internal backing store pointer to return.
@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 pointer to the raw data buffer that serves as object's backing store or NULL if object is not an Array Buffer object.
@discussion The pointer returned by this function is temporary and is not guaranteed to remain valid across JavaScriptCore API calls.
*/
JS_EXPORT void* JSObjectGetArrayBufferBytesPtr(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
/*!
@function
@abstract Returns the number of bytes in a JavaScript data object.
@param ctx The execution context to use.
@param object The JS Arary Buffer object whose length in bytes to return.
@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 number of bytes stored in the data object.
*/
JS_EXPORT size_t JSObjectGetArrayBufferByteLength(JSContextRef ctx, JSObjectRef object, JSValueRef* exception) CF_AVAILABLE(10_12, 10_0);
#ifdef __cplusplus
}
#endif
#endif /* JSTypedArray_h */

668
API/JSValue.h Normal file
View File

@ -0,0 +1,668 @@
/*
* 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 JavaScript value. Every JSValue
originates from a JSContext and holds a strong reference to it.
When a JSValue instance method creates a new JSValue, the new value
originates from the same JSContext.
All JSValues values also originate from a JSVirtualMachine
(available indirectly via the context property). It is an error to pass a
JSValue to a method or property of a JSValue or JSContext originating from a
different JSVirtualMachine. Doing so will raise an Objective-C exception.
*/
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 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 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 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 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;
/*!
@functiongroup Checking JavaScript Types
*/
/*!
@property
@abstract Check if a JSValue corresponds to the JavaScript value <code>undefined</code>.
*/
@property (readonly) BOOL isUndefined;
/*!
@property
@abstract Check if a JSValue corresponds to the JavaScript value <code>null</code>.
*/
@property (readonly) BOOL isNull;
/*!
@property
@abstract Check if a JSValue is a boolean.
*/
@property (readonly) BOOL isBoolean;
/*!
@property
@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;
/*!
@property
@abstract Check if a JSValue is a string.
*/
@property (readonly) BOOL isString;
/*!
@property
@abstract Check if a JSValue is an object.
*/
@property (readonly) BOOL isObject;
/*!
@property
@abstract Check if a JSValue is an array.
*/
@property (readonly) BOOL isArray NS_AVAILABLE(10_11, 9_0);
/*!
@property
@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.
@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

1181
API/JSValue.mm Normal file

File diff suppressed because it is too large Load Diff

58
API/JSValueInternal.h Normal file
View File

@ -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

452
API/JSValueRef.cpp Normal file
View File

@ -0,0 +1,452 @@
/*
* Copyright (C) 2006, 2007, 2016 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 "APIUtils.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;
#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);
auto stringRef(OpaqueJSString::create(jsValue.toWTFString(exec)));
if (handleExceptionIfNeeded(exec, exception) == ExceptionStatus::DidThrow)
stringRef = nullptr;
return stringRef.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);
}

359
API/JSValueRef.h Normal file
View File

@ -0,0 +1,359 @@
/*
* 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;
/*!
@enum JSTypedArrayType
@abstract A constant identifying the Typed Array type of a JSObjectRef.
@constant kJSTypedArrayTypeInt8Array Int8Array
@constant kJSTypedArrayTypeInt16Array Int16Array
@constant kJSTypedArrayTypeInt32Array Int32Array
@constant kJSTypedArrayTypeUint8Array Uint8Array
@constant kJSTypedArrayTypeUint8ClampedArray Uint8ClampedArray
@constant kJSTypedArrayTypeUint16Array Uint16Array
@constant kJSTypedArrayTypeUint32Array Uint32Array
@constant kJSTypedArrayTypeFloat32Array Float32Array
@constant kJSTypedArrayTypeFloat64Array Float64Array
@constant kJSTypedArrayTypeArrayBuffer ArrayBuffer
@constant kJSTypedArrayTypeNone Not a Typed Array
*/
typedef enum {
kJSTypedArrayTypeInt8Array,
kJSTypedArrayTypeInt16Array,
kJSTypedArrayTypeInt32Array,
kJSTypedArrayTypeUint8Array,
kJSTypedArrayTypeUint8ClampedArray,
kJSTypedArrayTypeUint16Array,
kJSTypedArrayTypeUint32Array,
kJSTypedArrayTypeFloat32Array,
kJSTypedArrayTypeFloat64Array,
kJSTypedArrayTypeArrayBuffer,
kJSTypedArrayTypeNone,
} JSTypedArrayType CF_ENUM_AVAILABLE(10_12, 10_0);
#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 value);
/*!
@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);
/*!
@function
@abstract Returns a JavaScript value's Typed Array type.
@param ctx The execution context to use.
@param value The JSValue whose Typed Array type to return.
@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 value of type JSTypedArrayType that identifies value's Typed Array type, or kJSTypedArrayTypeNone if the value is not a Typed Array object.
*/
JS_EXPORT JSTypedArrayType JSValueGetTypedArrayType(JSContextRef ctx, JSValueRef value, JSValueRef* exception) CF_AVAILABLE(10_12, 10_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 */

82
API/JSVirtualMachine.h Normal file
View File

@ -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

339
API/JSVirtualMachine.mm Normal file
View File

@ -0,0 +1,339 @@
/*
* Copyright (C) 2013-2017 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"
#import "JavaScriptCore.h"
#if JSC_OBJC_API_ENABLED
#import "APICast.h"
#import "JSManagedValueInternal.h"
#import "JSVirtualMachine.h"
#import "JSVirtualMachineInternal.h"
#import "JSWrapperMap.h"
#import "SigillCrashAnalyzer.h"
#import "SlotVisitorInlines.h"
#import <mutex>
#import <wtf/Lock.h>
#import <wtf/spi/cocoa/NSMapTableSPI.h>
static NSMapTable *globalWrapperCache = 0;
static StaticLock wrapperCacheMutex;
static void initWrapperCache()
{
ASSERT(!globalWrapperCache);
NSPointerFunctionsOptions keyOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality;
NSPointerFunctionsOptions valueOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
globalWrapperCache = [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:valueOptions capacity:0];
}
static NSMapTable *wrapperCache()
{
if (!globalWrapperCache)
initWrapperCache();
return globalWrapperCache;
}
@interface JSVMWrapperCache : NSObject
+ (void)addWrapper:(JSVirtualMachine *)wrapper forJSContextGroupRef:(JSContextGroupRef)group;
+ (JSVirtualMachine *)wrapperForJSContextGroupRef:(JSContextGroupRef)group;
@end
@implementation JSVMWrapperCache
+ (void)addWrapper:(JSVirtualMachine *)wrapper forJSContextGroupRef:(JSContextGroupRef)group
{
std::lock_guard<StaticLock> lock(wrapperCacheMutex);
NSMapInsert(wrapperCache(), group, wrapper);
}
+ (JSVirtualMachine *)wrapperForJSContextGroupRef:(JSContextGroupRef)group
{
std::lock_guard<StaticLock> lock(wrapperCacheMutex);
return static_cast<JSVirtualMachine *>(NSMapGet(wrapperCache(), group));
}
@end
@implementation JSVirtualMachine {
JSContextGroupRef m_group;
Lock m_externalDataMutex;
NSMapTable *m_contextCache;
NSMapTable *m_externalObjectGraph;
NSMapTable *m_externalRememberedSet;
}
- (instancetype)init
{
JSContextGroupRef group = JSContextGroupCreate();
self = [self initWithContextGroupRef:group];
// The extra JSContextGroupRetain is balanced here.
JSContextGroupRelease(group);
return self;
}
- (instancetype)initWithContextGroupRef:(JSContextGroupRef)group
{
self = [super init];
if (!self)
return nil;
m_group = JSContextGroupRetain(group);
NSPointerFunctionsOptions keyOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality;
NSPointerFunctionsOptions valueOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
m_contextCache = [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:valueOptions capacity:0];
NSPointerFunctionsOptions weakIDOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
NSPointerFunctionsOptions strongIDOptions = NSPointerFunctionsStrongMemory | NSPointerFunctionsObjectPersonality;
m_externalObjectGraph = [[NSMapTable alloc] initWithKeyOptions:weakIDOptions valueOptions:strongIDOptions capacity:0];
NSPointerFunctionsOptions integerOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsIntegerPersonality;
m_externalRememberedSet = [[NSMapTable alloc] initWithKeyOptions:weakIDOptions valueOptions:integerOptions capacity:0];
[JSVMWrapperCache addWrapper:self forJSContextGroupRef:group];
return self;
}
- (void)dealloc
{
JSContextGroupRelease(m_group);
[m_contextCache release];
[m_externalObjectGraph release];
[m_externalRememberedSet release];
[super dealloc];
}
static id getInternalObjcObject(id object)
{
if ([object isKindOfClass:[JSManagedValue class]]) {
JSValue* value = [static_cast<JSManagedValue *>(object) value];
if (!value)
return nil;
id temp = tryUnwrapObjcObject([value.context JSGlobalContextRef], [value JSValueRef]);
if (temp)
return temp;
return object;
}
if ([object isKindOfClass:[JSValue class]]) {
JSValue *value = static_cast<JSValue *>(object);
object = tryUnwrapObjcObject([value.context JSGlobalContextRef], [value JSValueRef]);
}
return object;
}
- (bool)isOldExternalObject:(id)object
{
JSC::VM* vm = toJS(m_group);
return vm->heap.collectorSlotVisitor().containsOpaqueRoot(object);
}
- (void)addExternalRememberedObject:(id)object
{
auto locker = holdLock(m_externalDataMutex);
ASSERT([self isOldExternalObject:object]);
[m_externalRememberedSet setObject:@YES forKey:object];
}
- (void)addManagedReference:(id)object withOwner:(id)owner
{
if ([object isKindOfClass:[JSManagedValue class]])
[object didAddOwner:owner];
object = getInternalObjcObject(object);
owner = getInternalObjcObject(owner);
if (!object || !owner)
return;
JSC::JSLockHolder locker(toJS(m_group));
if ([self isOldExternalObject:owner] && ![self isOldExternalObject:object])
[self addExternalRememberedObject:owner];
auto externalDataMutexLocker = holdLock(m_externalDataMutex);
NSMapTable *ownedObjects = [m_externalObjectGraph objectForKey:owner];
if (!ownedObjects) {
NSPointerFunctionsOptions weakIDOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
NSPointerFunctionsOptions integerOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsIntegerPersonality;
ownedObjects = [[NSMapTable alloc] initWithKeyOptions:weakIDOptions valueOptions:integerOptions capacity:1];
[m_externalObjectGraph setObject:ownedObjects forKey:owner];
[ownedObjects release];
}
size_t count = reinterpret_cast<size_t>(NSMapGet(ownedObjects, object));
NSMapInsert(ownedObjects, object, reinterpret_cast<void*>(count + 1));
}
- (void)removeManagedReference:(id)object withOwner:(id)owner
{
if ([object isKindOfClass:[JSManagedValue class]])
[object didRemoveOwner:owner];
object = getInternalObjcObject(object);
owner = getInternalObjcObject(owner);
if (!object || !owner)
return;
JSC::JSLockHolder locker(toJS(m_group));
auto externalDataMutexLocker = holdLock(m_externalDataMutex);
NSMapTable *ownedObjects = [m_externalObjectGraph objectForKey:owner];
if (!ownedObjects)
return;
size_t count = reinterpret_cast<size_t>(NSMapGet(ownedObjects, object));
if (count > 1) {
NSMapInsert(ownedObjects, object, reinterpret_cast<void*>(count - 1));
return;
}
if (count == 1)
NSMapRemove(ownedObjects, object);
if (![ownedObjects count]) {
[m_externalObjectGraph removeObjectForKey:owner];
[m_externalRememberedSet removeObjectForKey:owner];
}
}
- (void)enableSigillCrashAnalyzer
{
JSC::enableSigillCrashAnalyzer();
}
@end
@implementation JSVirtualMachine(Internal)
JSContextGroupRef getGroupFromVirtualMachine(JSVirtualMachine *virtualMachine)
{
return virtualMachine->m_group;
}
+ (JSVirtualMachine *)virtualMachineWithContextGroupRef:(JSContextGroupRef)group
{
JSVirtualMachine *virtualMachine = [JSVMWrapperCache wrapperForJSContextGroupRef:group];
if (!virtualMachine)
virtualMachine = [[[JSVirtualMachine alloc] initWithContextGroupRef:group] autorelease];
return virtualMachine;
}
- (JSContext *)contextForGlobalContextRef:(JSGlobalContextRef)globalContext
{
return static_cast<JSContext *>(NSMapGet(m_contextCache, globalContext));
}
- (void)addContext:(JSContext *)wrapper forGlobalContextRef:(JSGlobalContextRef)globalContext
{
NSMapInsert(m_contextCache, globalContext, wrapper);
}
- (Lock&)externalDataMutex
{
return m_externalDataMutex;
}
- (NSMapTable *)externalObjectGraph
{
return m_externalObjectGraph;
}
- (NSMapTable *)externalRememberedSet
{
return m_externalRememberedSet;
}
@end
static void scanExternalObjectGraph(JSC::VM& vm, JSC::SlotVisitor& visitor, void* root, bool lockAcquired)
{
@autoreleasepool {
JSVirtualMachine *virtualMachine = [JSVMWrapperCache wrapperForJSContextGroupRef:toRef(&vm)];
if (!virtualMachine)
return;
NSMapTable *externalObjectGraph = [virtualMachine externalObjectGraph];
Lock& externalDataMutex = [virtualMachine externalDataMutex];
Vector<void*> stack;
stack.append(root);
while (!stack.isEmpty()) {
void* nextRoot = stack.last();
stack.removeLast();
if (visitor.containsOpaqueRootTriState(nextRoot) == TrueTriState)
continue;
visitor.addOpaqueRoot(nextRoot);
auto appendOwnedObjects = [&] {
NSMapTable *ownedObjects = [externalObjectGraph objectForKey:static_cast<id>(nextRoot)];
for (id ownedObject in ownedObjects)
stack.append(static_cast<void*>(ownedObject));
};
if (lockAcquired)
appendOwnedObjects();
else {
auto locker = holdLock(externalDataMutex);
appendOwnedObjects();
}
}
}
}
void scanExternalObjectGraph(JSC::VM& vm, JSC::SlotVisitor& visitor, void* root)
{
bool lockAcquired = false;
scanExternalObjectGraph(vm, visitor, root, lockAcquired);
}
void scanExternalRememberedSet(JSC::VM& vm, JSC::SlotVisitor& visitor)
{
@autoreleasepool {
JSVirtualMachine *virtualMachine = [JSVMWrapperCache wrapperForJSContextGroupRef:toRef(&vm)];
if (!virtualMachine)
return;
Lock& externalDataMutex = [virtualMachine externalDataMutex];
auto locker = holdLock(externalDataMutex);
NSMapTable *externalObjectGraph = [virtualMachine externalObjectGraph];
NSMapTable *externalRememberedSet = [virtualMachine externalRememberedSet];
for (id key in externalRememberedSet) {
NSMapTable *ownedObjects = [externalObjectGraph objectForKey:key];
bool lockAcquired = true;
for (id ownedObject in ownedObjects)
scanExternalObjectGraph(vm, visitor, ownedObject, lockAcquired);
}
[externalRememberedSet removeAllObjects];
}
visitor.mergeIfNecessary();
}
#endif // JSC_OBJC_API_ENABLED

View File

@ -0,0 +1,58 @@
/*
* Copyright (C) 2013, 2017 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;
@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

View File

@ -0,0 +1,45 @@
/*
* Copyright (C) 2017 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 JSVirtualMachinePrivate_h
#define JSVirtualMachinePrivate_h
#if JSC_OBJC_API_ENABLED
@interface JSVirtualMachine(Private)
/*!
@method
@abstract Enables SIGILL crash analysis for all JSVirtualMachines.
@discussion Installs a SIGILL crash handler that will collect additional
non-user identifying information about the crash site via os_log_info.
*/
- (void)enableSigillCrashAnalyzer;
@end
#endif
#endif // JSVirtualMachinePrivate_h

View File

@ -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

View File

@ -0,0 +1,101 @@
/*
* 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"
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

View File

@ -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 object);
/*!
@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

48
API/JSWrapperMap.h Normal file
View File

@ -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

691
API/JSWrapperMap.mm Normal file
View File

@ -0,0 +1,691 @@
/*
* Copyright (C) 2013-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"
#import "JavaScriptCore.h"
#if JSC_OBJC_API_ENABLED
#import "APICast.h"
#import "JSAPIWrapperObject.h"
#import "JSCInlines.h"
#import "JSCallbackObject.h"
#import "JSContextInternal.h"
#import "JSWrapperMap.h"
#import "ObjCCallbackFunction.h"
#import "ObjcRuntimeExtras.h"
#import "WeakGCMap.h"
#import "WeakGCMapInlines.h"
#import <wtf/Vector.h>
#import <wtf/spi/cocoa/NSMapTableSPI.h>
#import <wtf/spi/darwin/dyldSPI.h>
#include <mach-o/dyld.h>
#if PLATFORM(APPLETV)
#else
static const int32_t firstJavaScriptCoreVersionWithInitConstructorSupport = 0x21A0400; // 538.4.0
#if PLATFORM(IOS)
static const uint32_t firstSDKVersionWithInitConstructorSupport = DYLD_IOS_VERSION_10_0;
#elif PLATFORM(MAC)
static const uint32_t firstSDKVersionWithInitConstructorSupport = 0xA0A00; // OSX 10.10.0
#endif
#endif
@class JSObjCClassInfo;
@interface JSWrapperMap ()
- (JSObjCClassInfo*)classInfoForClass:(Class)cls;
@end
// Default conversion of selectors to property names.
// All semicolons are removed, lowercase letters following a semicolon are capitalized.
static NSString *selectorToPropertyName(const char* start)
{
// Use 'index' to check for colons, if there are none, this is easy!
const char* firstColon = strchr(start, ':');
if (!firstColon)
return [NSString stringWithUTF8String:start];
// 'header' is the length of string up to the first colon.
size_t header = firstColon - start;
// The new string needs to be long enough to hold 'header', plus the remainder of the string, excluding
// at least one ':', but including a '\0'. (This is conservative if there are more than one ':').
char* buffer = static_cast<char*>(malloc(header + strlen(firstColon + 1) + 1));
// Copy 'header' characters, set output to point to the end of this & input to point past the first ':'.
memcpy(buffer, start, header);
char* output = buffer + header;
const char* input = start + header + 1;
// On entry to the loop, we have already skipped over a ':' from the input.
while (true) {
char c;
// Skip over any additional ':'s. We'll leave c holding the next character after the
// last ':', and input pointing past c.
while ((c = *(input++)) == ':');
// Copy the character, converting to upper case if necessary.
// If the character we copy is '\0', then we're done!
if (!(*(output++) = toupper(c)))
goto done;
// Loop over characters other than ':'.
while ((c = *(input++)) != ':') {
// Copy the character.
// If the character we copy is '\0', then we're done!
if (!(*(output++) = c))
goto done;
}
// If we get here, we've consumed a ':' - wash, rinse, repeat.
}
done:
NSString *result = [NSString stringWithUTF8String:buffer];
free(buffer);
return result;
}
static bool constructorHasInstance(JSContextRef ctx, JSObjectRef constructorRef, JSValueRef possibleInstance, JSValueRef*)
{
JSC::ExecState* exec = toJS(ctx);
JSC::JSLockHolder locker(exec);
JSC::JSObject* constructor = toJS(constructorRef);
JSC::JSValue instance = toJS(exec, possibleInstance);
return JSC::JSObject::defaultHasInstance(exec, instance, constructor->get(exec, exec->propertyNames().prototype));
}
static JSC::JSObject* makeWrapper(JSContextRef ctx, JSClassRef jsClass, id wrappedObject)
{
JSC::ExecState* exec = toJS(ctx);
JSC::JSLockHolder locker(exec);
ASSERT(jsClass);
JSC::JSCallbackObject<JSC::JSAPIWrapperObject>* object = JSC::JSCallbackObject<JSC::JSAPIWrapperObject>::create(exec, exec->lexicalGlobalObject(), exec->lexicalGlobalObject()->objcWrapperObjectStructure(), jsClass, 0);
object->setWrappedObject(wrappedObject);
if (JSC::JSObject* prototype = jsClass->prototype(exec))
object->setPrototypeDirect(exec->vm(), prototype);
return object;
}
// Make an object that is in all ways a completely vanilla JavaScript object,
// other than that it has a native brand set that will be displayed by the default
// Object.prototype.toString conversion.
static JSC::JSObject *objectWithCustomBrand(JSContext *context, NSString *brand, Class cls = 0)
{
JSClassDefinition definition;
definition = kJSClassDefinitionEmpty;
definition.className = [brand UTF8String];
JSClassRef classRef = JSClassCreate(&definition);
JSC::JSObject* result = makeWrapper([context JSGlobalContextRef], classRef, cls);
JSClassRelease(classRef);
return result;
}
static JSC::JSObject *constructorWithCustomBrand(JSContext *context, NSString *brand, Class cls)
{
JSClassDefinition definition;
definition = kJSClassDefinitionEmpty;
definition.className = [brand UTF8String];
definition.hasInstance = constructorHasInstance;
JSClassRef classRef = JSClassCreate(&definition);
JSC::JSObject* result = makeWrapper([context JSGlobalContextRef], classRef, cls);
JSClassRelease(classRef);
return result;
}
// Look for @optional properties in the prototype containing a selector to property
// name mapping, separated by a __JS_EXPORT_AS__ delimiter.
static NSMutableDictionary *createRenameMap(Protocol *protocol, BOOL isInstanceMethod)
{
NSMutableDictionary *renameMap = [[NSMutableDictionary alloc] init];
forEachMethodInProtocol(protocol, NO, isInstanceMethod, ^(SEL sel, const char*){
NSString *rename = @(sel_getName(sel));
NSRange range = [rename rangeOfString:@"__JS_EXPORT_AS__"];
if (range.location == NSNotFound)
return;
NSString *selector = [rename substringToIndex:range.location];
NSUInteger begin = range.location + range.length;
NSUInteger length = [rename length] - begin - 1;
NSString *name = [rename substringWithRange:(NSRange){ begin, length }];
renameMap[selector] = name;
});
return renameMap;
}
inline void putNonEnumerable(JSValue *base, NSString *propertyName, JSValue *value)
{
[base defineProperty:propertyName descriptor:@{
JSPropertyDescriptorValueKey: value,
JSPropertyDescriptorWritableKey: @YES,
JSPropertyDescriptorEnumerableKey: @NO,
JSPropertyDescriptorConfigurableKey: @YES
}];
}
static bool isInitFamilyMethod(NSString *name)
{
NSUInteger i = 0;
// Skip over initial underscores.
for (; i < [name length]; ++i) {
if ([name characterAtIndex:i] != '_')
break;
}
// Match 'init'.
NSUInteger initIndex = 0;
NSString* init = @"init";
for (; i < [name length] && initIndex < [init length]; ++i, ++initIndex) {
if ([name characterAtIndex:i] != [init characterAtIndex:initIndex])
return false;
}
// We didn't match all of 'init'.
if (initIndex < [init length])
return false;
// If we're at the end or the next character is a capital letter then this is an init-family selector.
return i == [name length] || [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[name characterAtIndex:i]];
}
static bool shouldSkipMethodWithName(NSString *name)
{
// For clients that don't support init-based constructors just copy
// over the init method as we would have before.
if (!supportsInitMethodConstructors())
return false;
// Skip over init family methods because we handle those specially
// for the purposes of hooking up the constructor correctly.
return isInitFamilyMethod(name);
}
// This method will iterate over the set of required methods in the protocol, and:
// * Determine a property name (either via a renameMap or default conversion).
// * If an accessorMap is provided, and contains this name, store the method in the map.
// * Otherwise, if the object doesn't already contain a property with name, create it.
static void copyMethodsToObject(JSContext *context, Class objcClass, Protocol *protocol, BOOL isInstanceMethod, JSValue *object, NSMutableDictionary *accessorMethods = nil)
{
NSMutableDictionary *renameMap = createRenameMap(protocol, isInstanceMethod);
forEachMethodInProtocol(protocol, YES, isInstanceMethod, ^(SEL sel, const char* types){
const char* nameCStr = sel_getName(sel);
NSString *name = @(nameCStr);
if (shouldSkipMethodWithName(name))
return;
if (accessorMethods && accessorMethods[name]) {
JSObjectRef method = objCCallbackFunctionForMethod(context, objcClass, protocol, isInstanceMethod, sel, types);
if (!method)
return;
accessorMethods[name] = [JSValue valueWithJSValueRef:method inContext:context];
} else {
name = renameMap[name];
if (!name)
name = selectorToPropertyName(nameCStr);
if ([object hasProperty:name])
return;
JSObjectRef method = objCCallbackFunctionForMethod(context, objcClass, protocol, isInstanceMethod, sel, types);
if (method)
putNonEnumerable(object, name, [JSValue valueWithJSValueRef:method inContext:context]);
}
});
[renameMap release];
}
static bool parsePropertyAttributes(objc_property_t property, char*& getterName, char*& setterName)
{
bool readonly = false;
unsigned attributeCount;
objc_property_attribute_t* attributes = property_copyAttributeList(property, &attributeCount);
if (attributeCount) {
for (unsigned i = 0; i < attributeCount; ++i) {
switch (*(attributes[i].name)) {
case 'G':
getterName = strdup(attributes[i].value);
break;
case 'S':
setterName = strdup(attributes[i].value);
break;
case 'R':
readonly = true;
break;
default:
break;
}
}
free(attributes);
}
return readonly;
}
static char* makeSetterName(const char* name)
{
size_t nameLength = strlen(name);
char* setterName = (char*)malloc(nameLength + 5); // "set" Name ":\0"
setterName[0] = 's';
setterName[1] = 'e';
setterName[2] = 't';
setterName[3] = toupper(*name);
memcpy(setterName + 4, name + 1, nameLength - 1);
setterName[nameLength + 3] = ':';
setterName[nameLength + 4] = '\0';
return setterName;
}
static void copyPrototypeProperties(JSContext *context, Class objcClass, Protocol *protocol, JSValue *prototypeValue)
{
// First gather propreties into this list, then handle the methods (capturing the accessor methods).
struct Property {
const char* name;
char* getterName;
char* setterName;
};
__block Vector<Property> propertyList;
// Map recording the methods used as getters/setters.
NSMutableDictionary *accessorMethods = [NSMutableDictionary dictionary];
// Useful value.
JSValue *undefined = [JSValue valueWithUndefinedInContext:context];
forEachPropertyInProtocol(protocol, ^(objc_property_t property){
char* getterName = 0;
char* setterName = 0;
bool readonly = parsePropertyAttributes(property, getterName, setterName);
const char* name = property_getName(property);
// Add the names of the getter & setter methods to
if (!getterName)
getterName = strdup(name);
accessorMethods[@(getterName)] = undefined;
if (!readonly) {
if (!setterName)
setterName = makeSetterName(name);
accessorMethods[@(setterName)] = undefined;
}
// Add the properties to a list.
propertyList.append((Property){ name, getterName, setterName });
});
// Copy methods to the prototype, capturing accessors in the accessorMethods map.
copyMethodsToObject(context, objcClass, protocol, YES, prototypeValue, accessorMethods);
// Iterate the propertyList & generate accessor properties.
for (size_t i = 0; i < propertyList.size(); ++i) {
Property& property = propertyList[i];
JSValue *getter = accessorMethods[@(property.getterName)];
free(property.getterName);
ASSERT(![getter isUndefined]);
JSValue *setter = undefined;
if (property.setterName) {
setter = accessorMethods[@(property.setterName)];
free(property.setterName);
ASSERT(![setter isUndefined]);
}
[prototypeValue defineProperty:@(property.name) descriptor:@{
JSPropertyDescriptorGetKey: getter,
JSPropertyDescriptorSetKey: setter,
JSPropertyDescriptorEnumerableKey: @NO,
JSPropertyDescriptorConfigurableKey: @YES
}];
}
}
@interface JSObjCClassInfo : NSObject {
JSContext *m_context;
Class m_class;
bool m_block;
JSClassRef m_classRef;
JSC::Weak<JSC::JSObject> m_prototype;
JSC::Weak<JSC::JSObject> m_constructor;
}
- (id)initWithContext:(JSContext *)context forClass:(Class)cls;
- (JSC::JSObject *)wrapperForObject:(id)object;
- (JSC::JSObject *)constructor;
- (JSC::JSObject *)prototype;
@end
@implementation JSObjCClassInfo
- (id)initWithContext:(JSContext *)context forClass:(Class)cls
{
self = [super init];
if (!self)
return nil;
const char* className = class_getName(cls);
m_context = context;
m_class = cls;
m_block = [cls isSubclassOfClass:getNSBlockClass()];
JSClassDefinition definition;
definition = kJSClassDefinitionEmpty;
definition.className = className;
m_classRef = JSClassCreate(&definition);
return self;
}
- (void)dealloc
{
JSClassRelease(m_classRef);
[super dealloc];
}
static JSC::JSObject* allocateConstructorForCustomClass(JSContext *context, const char* className, Class cls)
{
if (!supportsInitMethodConstructors())
return constructorWithCustomBrand(context, [NSString stringWithFormat:@"%sConstructor", className], cls);
// For each protocol that the class implements, gather all of the init family methods into a hash table.
__block HashMap<String, Protocol *> initTable;
Protocol *exportProtocol = getJSExportProtocol();
for (Class currentClass = cls; currentClass; currentClass = class_getSuperclass(currentClass)) {
forEachProtocolImplementingProtocol(currentClass, exportProtocol, ^(Protocol *protocol) {
forEachMethodInProtocol(protocol, YES, YES, ^(SEL selector, const char*) {
const char* name = sel_getName(selector);
if (!isInitFamilyMethod(@(name)))
return;
initTable.set(name, protocol);
});
});
}
for (Class currentClass = cls; currentClass; currentClass = class_getSuperclass(currentClass)) {
__block unsigned numberOfInitsFound = 0;
__block SEL initMethod = 0;
__block Protocol *initProtocol = 0;
__block const char* types = 0;
forEachMethodInClass(currentClass, ^(Method method) {
SEL selector = method_getName(method);
const char* name = sel_getName(selector);
auto iter = initTable.find(name);
if (iter == initTable.end())
return;
numberOfInitsFound++;
initMethod = selector;
initProtocol = iter->value;
types = method_getTypeEncoding(method);
});
if (!numberOfInitsFound)
continue;
if (numberOfInitsFound > 1) {
NSLog(@"ERROR: Class %@ exported more than one init family method via JSExport. Class %@ will not have a callable JavaScript constructor function.", cls, cls);
break;
}
JSObjectRef method = objCCallbackFunctionForInit(context, cls, initProtocol, initMethod, types);
return toJS(method);
}
return constructorWithCustomBrand(context, [NSString stringWithFormat:@"%sConstructor", className], cls);
}
typedef std::pair<JSC::JSObject*, JSC::JSObject*> ConstructorPrototypePair;
- (ConstructorPrototypePair)allocateConstructorAndPrototype
{
JSObjCClassInfo* superClassInfo = [m_context.wrapperMap classInfoForClass:class_getSuperclass(m_class)];
ASSERT(!m_constructor || !m_prototype);
ASSERT((m_class == [NSObject class]) == !superClassInfo);
JSC::JSObject* jsPrototype = m_prototype.get();
JSC::JSObject* jsConstructor = m_constructor.get();
if (!superClassInfo) {
JSContextRef cContext = [m_context JSGlobalContextRef];
JSValue *constructor = m_context[@"Object"];
if (!jsConstructor)
jsConstructor = toJS(JSValueToObject(cContext, valueInternalValue(constructor), 0));
if (!jsPrototype) {
JSValue *prototype = constructor[@"prototype"];
jsPrototype = toJS(JSValueToObject(cContext, valueInternalValue(prototype), 0));
}
} else {
const char* className = class_getName(m_class);
// Create or grab the prototype/constructor pair.
if (!jsPrototype)
jsPrototype = objectWithCustomBrand(m_context, [NSString stringWithFormat:@"%sPrototype", className]);
if (!jsConstructor)
jsConstructor = allocateConstructorForCustomClass(m_context, className, m_class);
JSValue* prototype = [JSValue valueWithJSValueRef:toRef(jsPrototype) inContext:m_context];
JSValue* constructor = [JSValue valueWithJSValueRef:toRef(jsConstructor) inContext:m_context];
putNonEnumerable(prototype, @"constructor", constructor);
putNonEnumerable(constructor, @"prototype", prototype);
Protocol *exportProtocol = getJSExportProtocol();
forEachProtocolImplementingProtocol(m_class, exportProtocol, ^(Protocol *protocol){
copyPrototypeProperties(m_context, m_class, protocol, prototype);
copyMethodsToObject(m_context, m_class, protocol, NO, constructor);
});
// Set [Prototype].
JSC::JSObject* superClassPrototype = [superClassInfo prototype];
JSObjectSetPrototype([m_context JSGlobalContextRef], toRef(jsPrototype), toRef(superClassPrototype));
}
m_prototype = jsPrototype;
m_constructor = jsConstructor;
return ConstructorPrototypePair(jsConstructor, jsPrototype);
}
- (JSC::JSObject*)wrapperForObject:(id)object
{
ASSERT([object isKindOfClass:m_class]);
ASSERT(m_block == [object isKindOfClass:getNSBlockClass()]);
if (m_block) {
if (JSObjectRef method = objCCallbackFunctionForBlock(m_context, object)) {
JSValue *constructor = [JSValue valueWithJSValueRef:method inContext:m_context];
JSValue *prototype = [JSValue valueWithNewObjectInContext:m_context];
putNonEnumerable(constructor, @"prototype", prototype);
putNonEnumerable(prototype, @"constructor", constructor);
return toJS(method);
}
}
JSC::JSObject* prototype = [self prototype];
JSC::JSObject* wrapper = makeWrapper([m_context JSGlobalContextRef], m_classRef, object);
JSObjectSetPrototype([m_context JSGlobalContextRef], toRef(wrapper), toRef(prototype));
return wrapper;
}
- (JSC::JSObject*)constructor
{
JSC::JSObject* constructor = m_constructor.get();
if (!constructor)
constructor = [self allocateConstructorAndPrototype].first;
ASSERT(!!constructor);
return constructor;
}
- (JSC::JSObject*)prototype
{
JSC::JSObject* prototype = m_prototype.get();
if (!prototype)
prototype = [self allocateConstructorAndPrototype].second;
ASSERT(!!prototype);
return prototype;
}
@end
@implementation JSWrapperMap {
JSContext *m_context;
NSMutableDictionary *m_classMap;
std::unique_ptr<JSC::WeakGCMap<id, JSC::JSObject>> m_cachedJSWrappers;
NSMapTable *m_cachedObjCWrappers;
}
- (id)initWithContext:(JSContext *)context
{
self = [super init];
if (!self)
return nil;
NSPointerFunctionsOptions keyOptions = NSPointerFunctionsOpaqueMemory | NSPointerFunctionsOpaquePersonality;
NSPointerFunctionsOptions valueOptions = NSPointerFunctionsWeakMemory | NSPointerFunctionsObjectPersonality;
m_cachedObjCWrappers = [[NSMapTable alloc] initWithKeyOptions:keyOptions valueOptions:valueOptions capacity:0];
m_cachedJSWrappers = std::make_unique<JSC::WeakGCMap<id, JSC::JSObject>>(toJS([context JSGlobalContextRef])->vm());
m_context = context;
m_classMap = [[NSMutableDictionary alloc] init];
return self;
}
- (void)dealloc
{
[m_cachedObjCWrappers release];
[m_classMap release];
[super dealloc];
}
- (JSObjCClassInfo*)classInfoForClass:(Class)cls
{
if (!cls)
return nil;
// Check if we've already created a JSObjCClassInfo for this Class.
if (JSObjCClassInfo* classInfo = (JSObjCClassInfo*)m_classMap[cls])
return classInfo;
// Skip internal classes beginning with '_' - just copy link to the parent class's info.
if ('_' == *class_getName(cls))
return m_classMap[cls] = [self classInfoForClass:class_getSuperclass(cls)];
return m_classMap[cls] = [[[JSObjCClassInfo alloc] initWithContext:m_context forClass:cls] autorelease];
}
- (JSValue *)jsWrapperForObject:(id)object
{
JSC::JSObject* jsWrapper = m_cachedJSWrappers->get(object);
if (jsWrapper)
return [JSValue valueWithJSValueRef:toRef(jsWrapper) inContext:m_context];
if (class_isMetaClass(object_getClass(object)))
jsWrapper = [[self classInfoForClass:(Class)object] constructor];
else {
JSObjCClassInfo* classInfo = [self classInfoForClass:[object class]];
jsWrapper = [classInfo wrapperForObject:object];
}
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=105891
// This general approach to wrapper caching is pretty effective, but there are a couple of problems:
// (1) For immortal objects JSValues will effectively leak and this results in error output being logged - we should avoid adding associated objects to immortal objects.
// (2) A long lived object may rack up many JSValues. When the contexts are released these will unprotect the associated JavaScript objects,
// but still, would probably nicer if we made it so that only one associated object was required, broadcasting object dealloc.
m_cachedJSWrappers->set(object, jsWrapper);
return [JSValue valueWithJSValueRef:toRef(jsWrapper) inContext:m_context];
}
- (JSValue *)objcWrapperForJSValueRef:(JSValueRef)value
{
JSValue *wrapper = static_cast<JSValue *>(NSMapGet(m_cachedObjCWrappers, value));
if (!wrapper) {
wrapper = [[[JSValue alloc] initWithValue:value inContext:m_context] autorelease];
NSMapInsert(m_cachedObjCWrappers, value, wrapper);
}
return wrapper;
}
@end
id tryUnwrapObjcObject(JSGlobalContextRef context, JSValueRef value)
{
if (!JSValueIsObject(context, value))
return nil;
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject(context, value, &exception);
ASSERT(!exception);
JSC::JSLockHolder locker(toJS(context));
if (toJS(object)->inherits(JSC::JSCallbackObject<JSC::JSAPIWrapperObject>::info()))
return (id)JSC::jsCast<JSC::JSAPIWrapperObject*>(toJS(object))->wrappedObject();
if (id target = tryUnwrapConstructor(object))
return target;
return nil;
}
// This class ensures that the JSExport protocol is registered with the runtime.
NS_ROOT_CLASS @interface JSExport <JSExport>
@end
@implementation JSExport
@end
bool supportsInitMethodConstructors()
{
#if PLATFORM(APPLETV)
// There are no old clients on Apple TV, so there's no need for backwards compatibility.
return true;
#else
// First check to see the version of JavaScriptCore we directly linked against.
static int32_t versionOfLinkTimeJavaScriptCore = 0;
if (!versionOfLinkTimeJavaScriptCore)
versionOfLinkTimeJavaScriptCore = NSVersionOfLinkTimeLibrary("JavaScriptCore");
// Only do the link time version comparison if we linked directly with JavaScriptCore
if (versionOfLinkTimeJavaScriptCore != -1)
return versionOfLinkTimeJavaScriptCore >= firstJavaScriptCoreVersionWithInitConstructorSupport;
// If we didn't link directly with JavaScriptCore,
// base our check on what SDK was used to build the application.
static uint32_t programSDKVersion = 0;
if (!programSDKVersion)
programSDKVersion = dyld_get_program_sdk_version();
return programSDKVersion >= firstSDKVersionWithInitConstructorSupport;
#endif
}
Protocol *getJSExportProtocol()
{
static Protocol *protocol = objc_getProtocol("JSExport");
return protocol;
}
Class getNSBlockClass()
{
static Class cls = objc_getClass("NSBlock");
return cls;
}
#endif

37
API/JavaScript.h Normal file
View File

@ -0,0 +1,37 @@
/*
* 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/JSTypedArray.h>
#include <JavaScriptCore/JSValueRef.h>
#endif /* JavaScript_h */

42
API/JavaScriptCore.h Normal file
View File

@ -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 */

View File

@ -0,0 +1,83 @@
/*
* Copyright (C) 2013, 2016 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&, Structure*, 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

728
API/ObjCCallbackFunction.mm Normal file
View File

@ -0,0 +1,728 @@
/*
* Copyright (C) 2013, 2016 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"
#import "JavaScriptCore.h"
#if JSC_OBJC_API_ENABLED
#import "APICallbackFunction.h"
#import "APICast.h"
#import "Error.h"
#import "JSCell.h"
#import "JSCInlines.h"
#import "JSContextInternal.h"
#import "JSWrapperMap.h"
#import "JSValueInternal.h"
#import "ObjCCallbackFunction.h"
#import "ObjcRuntimeExtras.h"
#import "StructureInlines.h"
#import <objc/runtime.h>
#import <wtf/RetainPtr.h>
class CallbackArgument {
WTF_MAKE_FAST_ALLOCATED;
public:
virtual ~CallbackArgument();
virtual void set(NSInvocation *, NSInteger, JSContext *, JSValueRef, JSValueRef*) = 0;
std::unique_ptr<CallbackArgument> m_next;
};
CallbackArgument::~CallbackArgument()
{
}
class CallbackArgumentBoolean : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) override
{
bool value = JSValueToBoolean([context JSGlobalContextRef], argument);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
template<typename T>
class CallbackArgumentInteger : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
T value = (T)JSC::toInt32(JSValueToNumber([context JSGlobalContextRef], argument, exception));
[invocation setArgument:&value atIndex:argumentNumber];
}
};
template<typename T>
class CallbackArgumentDouble : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
T value = (T)JSValueToNumber([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentJSValue : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) override
{
JSValue *value = [JSValue valueWithJSValueRef:argument inContext:context];
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentId : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) override
{
id value = valueToObject(context, argument);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentOfClass : public CallbackArgument {
public:
CallbackArgumentOfClass(Class cls)
: m_class(cls)
{
}
private:
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
id object = tryUnwrapObjcObject(contextRef, argument);
if (object && [object isKindOfClass:m_class.get()]) {
[invocation setArgument:&object atIndex:argumentNumber];
return;
}
if (JSValueIsNull(contextRef, argument) || JSValueIsUndefined(contextRef, argument)) {
object = nil;
[invocation setArgument:&object atIndex:argumentNumber];
return;
}
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("Argument does not match Objective-C Class")));
}
RetainPtr<Class> m_class;
};
class CallbackArgumentNSNumber : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToNumber([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentNSString : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToString([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentNSDate : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToDate([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentNSArray : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToArray([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentNSDictionary : public CallbackArgument {
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef* exception) override
{
id value = valueToDictionary([context JSGlobalContextRef], argument, exception);
[invocation setArgument:&value atIndex:argumentNumber];
}
};
class CallbackArgumentStruct : public CallbackArgument {
public:
CallbackArgumentStruct(NSInvocation *conversionInvocation, const char* encodedType)
: m_conversionInvocation(conversionInvocation)
, m_buffer(encodedType)
{
}
private:
void set(NSInvocation *invocation, NSInteger argumentNumber, JSContext *context, JSValueRef argument, JSValueRef*) override
{
JSValue *value = [JSValue valueWithJSValueRef:argument inContext:context];
[m_conversionInvocation invokeWithTarget:value];
[m_conversionInvocation getReturnValue:m_buffer];
[invocation setArgument:m_buffer atIndex:argumentNumber];
}
RetainPtr<NSInvocation> m_conversionInvocation;
StructBuffer m_buffer;
};
class ArgumentTypeDelegate {
public:
typedef std::unique_ptr<CallbackArgument> ResultType;
template<typename T>
static ResultType typeInteger()
{
return std::make_unique<CallbackArgumentInteger<T>>();
}
template<typename T>
static ResultType typeDouble()
{
return std::make_unique<CallbackArgumentDouble<T>>();
}
static ResultType typeBool()
{
return std::make_unique<CallbackArgumentBoolean>();
}
static ResultType typeVoid()
{
RELEASE_ASSERT_NOT_REACHED();
return nullptr;
}
static ResultType typeId()
{
return std::make_unique<CallbackArgumentId>();
}
static ResultType typeOfClass(const char* begin, const char* end)
{
StringRange copy(begin, end);
Class cls = objc_getClass(copy);
if (!cls)
return nullptr;
if (cls == [JSValue class])
return std::make_unique<CallbackArgumentJSValue>();
if (cls == [NSString class])
return std::make_unique<CallbackArgumentNSString>();
if (cls == [NSNumber class])
return std::make_unique<CallbackArgumentNSNumber>();
if (cls == [NSDate class])
return std::make_unique<CallbackArgumentNSDate>();
if (cls == [NSArray class])
return std::make_unique<CallbackArgumentNSArray>();
if (cls == [NSDictionary class])
return std::make_unique<CallbackArgumentNSDictionary>();
return std::make_unique<CallbackArgumentOfClass>(cls);
}
static ResultType typeBlock(const char*, const char*)
{
return nullptr;
}
static ResultType typeStruct(const char* begin, const char* end)
{
StringRange copy(begin, end);
if (NSInvocation *invocation = valueToTypeInvocationFor(copy))
return std::make_unique<CallbackArgumentStruct>(invocation, copy);
return nullptr;
}
};
class CallbackResult {
WTF_MAKE_FAST_ALLOCATED;
public:
virtual ~CallbackResult()
{
}
virtual JSValueRef get(NSInvocation *, JSContext *, JSValueRef*) = 0;
};
class CallbackResultVoid : public CallbackResult {
JSValueRef get(NSInvocation *, JSContext *context, JSValueRef*) override
{
return JSValueMakeUndefined([context JSGlobalContextRef]);
}
};
class CallbackResultId : public CallbackResult {
JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) override
{
id value;
[invocation getReturnValue:&value];
return objectToValue(context, value);
}
};
template<typename T>
class CallbackResultNumeric : public CallbackResult {
JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) override
{
T value;
[invocation getReturnValue:&value];
return JSValueMakeNumber([context JSGlobalContextRef], value);
}
};
class CallbackResultBoolean : public CallbackResult {
JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) override
{
bool value;
[invocation getReturnValue:&value];
return JSValueMakeBoolean([context JSGlobalContextRef], value);
}
};
class CallbackResultStruct : public CallbackResult {
public:
CallbackResultStruct(NSInvocation *conversionInvocation, const char* encodedType)
: m_conversionInvocation(conversionInvocation)
, m_buffer(encodedType)
{
}
private:
JSValueRef get(NSInvocation *invocation, JSContext *context, JSValueRef*) override
{
[invocation getReturnValue:m_buffer];
[m_conversionInvocation setArgument:m_buffer atIndex:2];
[m_conversionInvocation setArgument:&context atIndex:3];
[m_conversionInvocation invokeWithTarget:[JSValue class]];
JSValue *value;
[m_conversionInvocation getReturnValue:&value];
return valueInternalValue(value);
}
RetainPtr<NSInvocation> m_conversionInvocation;
StructBuffer m_buffer;
};
class ResultTypeDelegate {
public:
typedef std::unique_ptr<CallbackResult> ResultType;
template<typename T>
static ResultType typeInteger()
{
return std::make_unique<CallbackResultNumeric<T>>();
}
template<typename T>
static ResultType typeDouble()
{
return std::make_unique<CallbackResultNumeric<T>>();
}
static ResultType typeBool()
{
return std::make_unique<CallbackResultBoolean>();
}
static ResultType typeVoid()
{
return std::make_unique<CallbackResultVoid>();
}
static ResultType typeId()
{
return std::make_unique<CallbackResultId>();
}
static ResultType typeOfClass(const char*, const char*)
{
return std::make_unique<CallbackResultId>();
}
static ResultType typeBlock(const char*, const char*)
{
return std::make_unique<CallbackResultId>();
}
static ResultType typeStruct(const char* begin, const char* end)
{
StringRange copy(begin, end);
if (NSInvocation *invocation = typeToValueInvocationFor(copy))
return std::make_unique<CallbackResultStruct>(invocation, copy);
return nullptr;
}
};
enum CallbackType {
CallbackInitMethod,
CallbackInstanceMethod,
CallbackClassMethod,
CallbackBlock
};
namespace JSC {
class ObjCCallbackFunctionImpl {
public:
ObjCCallbackFunctionImpl(NSInvocation *invocation, CallbackType type, Class instanceClass, std::unique_ptr<CallbackArgument> arguments, std::unique_ptr<CallbackResult> result)
: m_type(type)
, m_instanceClass(instanceClass)
, m_invocation(invocation)
, m_arguments(WTFMove(arguments))
, m_result(WTFMove(result))
{
ASSERT((type != CallbackInstanceMethod && type != CallbackInitMethod) || instanceClass);
}
void destroy(Heap& heap)
{
// We need to explicitly release the target since we didn't call
// -retainArguments on m_invocation (and we don't want to do so).
if (m_type == CallbackBlock || m_type == CallbackClassMethod)
heap.releaseSoon(adoptNS([m_invocation.get() target]));
m_instanceClass = nil;
}
JSValueRef call(JSContext *context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception);
id wrappedBlock()
{
return m_type == CallbackBlock ? [m_invocation target] : nil;
}
id wrappedConstructor()
{
switch (m_type) {
case CallbackBlock:
return [m_invocation target];
case CallbackInitMethod:
return m_instanceClass.get();
default:
return nil;
}
}
CallbackType type() const { return m_type; }
bool isConstructible()
{
return !!wrappedBlock() || m_type == CallbackInitMethod;
}
String name();
private:
CallbackType m_type;
RetainPtr<Class> m_instanceClass;
RetainPtr<NSInvocation> m_invocation;
std::unique_ptr<CallbackArgument> m_arguments;
std::unique_ptr<CallbackResult> m_result;
};
static JSValueRef objCCallbackFunctionCallAsFunction(JSContextRef callerContext, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
// Retake the API lock - we need this for a few reasons:
// (1) We don't want to support the C-API's confusing drops-locks-once policy - should only drop locks if we can do so recursively.
// (2) We're calling some JSC internals that require us to be on the 'inside' - e.g. createTypeError.
// (3) We need to be locked (per context would be fine) against conflicting usage of the ObjCCallbackFunction's NSInvocation.
JSC::JSLockHolder locker(toJS(callerContext));
ObjCCallbackFunction* callback = static_cast<ObjCCallbackFunction*>(toJS(function));
ObjCCallbackFunctionImpl* impl = callback->impl();
JSContext *context = [JSContext contextWithJSGlobalContextRef:toGlobalRef(callback->globalObject()->globalExec())];
if (impl->type() == CallbackInitMethod) {
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("Cannot call a class constructor without |new|")));
return JSValueMakeUndefined(contextRef);
}
CallbackData callbackData;
JSValueRef result;
@autoreleasepool {
[context beginCallbackWithData:&callbackData calleeValue:function thisValue:thisObject argumentCount:argumentCount arguments:arguments];
result = impl->call(context, thisObject, argumentCount, arguments, exception);
if (context.exception)
*exception = valueInternalValue(context.exception);
[context endCallbackWithData:&callbackData];
}
return result;
}
static JSObjectRef objCCallbackFunctionCallAsConstructor(JSContextRef callerContext, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
JSC::JSLockHolder locker(toJS(callerContext));
ObjCCallbackFunction* callback = static_cast<ObjCCallbackFunction*>(toJS(constructor));
ObjCCallbackFunctionImpl* impl = callback->impl();
JSContext *context = [JSContext contextWithJSGlobalContextRef:toGlobalRef(toJS(callerContext)->lexicalGlobalObject()->globalExec())];
CallbackData callbackData;
JSValueRef result;
@autoreleasepool {
[context beginCallbackWithData:&callbackData calleeValue:constructor thisValue:nullptr argumentCount:argumentCount arguments:arguments];
result = impl->call(context, nullptr, argumentCount, arguments, exception);
if (context.exception)
*exception = valueInternalValue(context.exception);
[context endCallbackWithData:&callbackData];
}
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
if (*exception)
return nullptr;
if (!JSValueIsObject(contextRef, result)) {
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("Objective-C blocks called as constructors must return an object.")));
return nullptr;
}
return (JSObjectRef)result;
}
const JSC::ClassInfo ObjCCallbackFunction::s_info = { "CallbackFunction", &Base::s_info, 0, CREATE_METHOD_TABLE(ObjCCallbackFunction) };
ObjCCallbackFunction::ObjCCallbackFunction(JSC::VM& vm, JSC::Structure* structure, JSObjectCallAsFunctionCallback functionCallback, JSObjectCallAsConstructorCallback constructCallback, std::unique_ptr<ObjCCallbackFunctionImpl> impl)
: Base(vm, structure)
, m_functionCallback(functionCallback)
, m_constructCallback(constructCallback)
, m_impl(WTFMove(impl))
{
}
ObjCCallbackFunction* ObjCCallbackFunction::create(JSC::VM& vm, JSC::JSGlobalObject* globalObject, const String& name, std::unique_ptr<ObjCCallbackFunctionImpl> impl)
{
Structure* structure = globalObject->objcCallbackFunctionStructure();
ObjCCallbackFunction* function = new (NotNull, allocateCell<ObjCCallbackFunction>(vm.heap)) ObjCCallbackFunction(vm, structure, objCCallbackFunctionCallAsFunction, objCCallbackFunctionCallAsConstructor, WTFMove(impl));
function->finishCreation(vm, name);
return function;
}
void ObjCCallbackFunction::destroy(JSCell* cell)
{
ObjCCallbackFunction& function = *jsCast<ObjCCallbackFunction*>(cell);
function.impl()->destroy(*Heap::heap(cell));
function.~ObjCCallbackFunction();
}
CallType ObjCCallbackFunction::getCallData(JSCell*, CallData& callData)
{
callData.native.function = APICallbackFunction::call<ObjCCallbackFunction>;
return CallType::Host;
}
ConstructType ObjCCallbackFunction::getConstructData(JSCell* cell, ConstructData& constructData)
{
ObjCCallbackFunction* callback = jsCast<ObjCCallbackFunction*>(cell);
if (!callback->impl()->isConstructible())
return Base::getConstructData(cell, constructData);
constructData.native.function = APICallbackFunction::construct<ObjCCallbackFunction>;
return ConstructType::Host;
}
String ObjCCallbackFunctionImpl::name()
{
if (m_type == CallbackInitMethod)
return class_getName(m_instanceClass.get());
// FIXME: Maybe we could support having the selector as the name of the non-init
// functions to make it a bit more user-friendly from the JS side?
return "";
}
JSValueRef ObjCCallbackFunctionImpl::call(JSContext *context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
{
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
id target;
size_t firstArgument;
switch (m_type) {
case CallbackInitMethod: {
RELEASE_ASSERT(!thisObject);
target = [m_instanceClass alloc];
if (!target || ![target isKindOfClass:m_instanceClass.get()]) {
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("self type check failed for Objective-C instance method")));
return JSValueMakeUndefined(contextRef);
}
[m_invocation setTarget:target];
firstArgument = 2;
break;
}
case CallbackInstanceMethod: {
target = tryUnwrapObjcObject(contextRef, thisObject);
if (!target || ![target isKindOfClass:m_instanceClass.get()]) {
*exception = toRef(JSC::createTypeError(toJS(contextRef), ASCIILiteral("self type check failed for Objective-C instance method")));
return JSValueMakeUndefined(contextRef);
}
[m_invocation setTarget:target];
firstArgument = 2;
break;
}
case CallbackClassMethod:
firstArgument = 2;
break;
case CallbackBlock:
firstArgument = 1;
}
size_t argumentNumber = 0;
for (CallbackArgument* argument = m_arguments.get(); argument; argument = argument->m_next.get()) {
JSValueRef value = argumentNumber < argumentCount ? arguments[argumentNumber] : JSValueMakeUndefined(contextRef);
argument->set(m_invocation.get(), argumentNumber + firstArgument, context, value, exception);
if (*exception)
return JSValueMakeUndefined(contextRef);
++argumentNumber;
}
[m_invocation invoke];
JSValueRef result = m_result->get(m_invocation.get(), context, exception);
// Balance our call to -alloc with a call to -autorelease. We have to do this after calling -init
// because init family methods are allowed to release the allocated object and return something
// else in its place.
if (m_type == CallbackInitMethod) {
id objcResult = tryUnwrapObjcObject(contextRef, result);
if (objcResult)
[objcResult autorelease];
}
return result;
}
} // namespace JSC
static bool blockSignatureContainsClass()
{
static bool containsClass = ^{
id block = ^(NSString *string){ return string; };
return _Block_has_signature(block) && strstr(_Block_signature(block), "NSString");
}();
return containsClass;
}
static inline bool skipNumber(const char*& position)
{
if (!isASCIIDigit(*position))
return false;
while (isASCIIDigit(*++position)) { }
return true;
}
static JSObjectRef objCCallbackFunctionForInvocation(JSContext *context, NSInvocation *invocation, CallbackType type, Class instanceClass, const char* signatureWithObjcClasses)
{
if (!signatureWithObjcClasses)
return nullptr;
const char* position = signatureWithObjcClasses;
auto result = parseObjCType<ResultTypeDelegate>(position);
if (!result || !skipNumber(position))
return nullptr;
switch (type) {
case CallbackInitMethod:
case CallbackInstanceMethod:
case CallbackClassMethod:
// Methods are passed two implicit arguments - (id)self, and the selector.
if ('@' != *position++ || !skipNumber(position) || ':' != *position++ || !skipNumber(position))
return nullptr;
break;
case CallbackBlock:
// Blocks are passed one implicit argument - the block, of type "@?".
if (('@' != *position++) || ('?' != *position++) || !skipNumber(position))
return nullptr;
// Only allow arguments of type 'id' if the block signature contains the NS type information.
if ((!blockSignatureContainsClass() && strchr(position, '@')))
return nullptr;
break;
}
std::unique_ptr<CallbackArgument> arguments;
auto* nextArgument = &arguments;
unsigned argumentCount = 0;
while (*position) {
auto argument = parseObjCType<ArgumentTypeDelegate>(position);
if (!argument || !skipNumber(position))
return nullptr;
*nextArgument = WTFMove(argument);
nextArgument = &(*nextArgument)->m_next;
++argumentCount;
}
JSC::ExecState* exec = toJS([context JSGlobalContextRef]);
JSC::JSLockHolder locker(exec);
auto impl = std::make_unique<JSC::ObjCCallbackFunctionImpl>(invocation, type, instanceClass, WTFMove(arguments), WTFMove(result));
const String& name = impl->name();
return toRef(JSC::ObjCCallbackFunction::create(exec->vm(), exec->lexicalGlobalObject(), name, WTFMove(impl)));
}
JSObjectRef objCCallbackFunctionForInit(JSContext *context, Class cls, Protocol *protocol, SEL sel, const char* types)
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:types]];
[invocation setSelector:sel];
return objCCallbackFunctionForInvocation(context, invocation, CallbackInitMethod, cls, _protocol_getMethodTypeEncoding(protocol, sel, YES, YES));
}
JSObjectRef objCCallbackFunctionForMethod(JSContext *context, Class cls, Protocol *protocol, BOOL isInstanceMethod, SEL sel, const char* types)
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:types]];
[invocation setSelector:sel];
// We need to retain the target Class because m_invocation doesn't retain it by default (and we don't want it to).
// FIXME: What releases it?
if (!isInstanceMethod)
[invocation setTarget:[cls retain]];
return objCCallbackFunctionForInvocation(context, invocation, isInstanceMethod ? CallbackInstanceMethod : CallbackClassMethod, isInstanceMethod ? cls : nil, _protocol_getMethodTypeEncoding(protocol, sel, YES, isInstanceMethod));
}
JSObjectRef objCCallbackFunctionForBlock(JSContext *context, id target)
{
if (!_Block_has_signature(target))
return nullptr;
const char* signature = _Block_signature(target);
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:signature]];
// We don't want to use -retainArguments because that leaks memory. Arguments
// would be retained indefinitely between invocations of the callback.
// Additionally, we copy the target because we want the block to stick around
// until the ObjCCallbackFunctionImpl is destroyed.
[invocation setTarget:[target copy]];
return objCCallbackFunctionForInvocation(context, invocation, CallbackBlock, nil, signature);
}
id tryUnwrapConstructor(JSObjectRef object)
{
if (!toJS(object)->inherits(JSC::ObjCCallbackFunction::info()))
return nil;
JSC::ObjCCallbackFunctionImpl* impl = static_cast<JSC::ObjCCallbackFunction*>(toJS(object))->impl();
if (!impl->isConstructible())
return nil;
return impl->wrappedConstructor();
}
#endif

242
API/ObjcRuntimeExtras.h Normal file
View File

@ -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 *);
}

109
API/OpaqueJSString.cpp Normal file
View File

@ -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;
}

102
API/OpaqueJSString.h Normal file
View File

@ -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

83
API/WebKitAvailability.h Normal file
View File

@ -0,0 +1,83 @@
/*
* 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__)
#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 __NSi_10_12 // Building from trunk rather than SDK.
#define __NSi_10_12 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 */
#if defined(BUILDING_GTK__)
#undef CF_AVAILABLE
#define CF_AVAILABLE(_mac, _ios)
#undef CF_ENUM_AVAILABLE
#define CF_ENUM_AVAILABLE(_mac, _ios)
#endif
#else
#define CF_AVAILABLE(_mac, _ios)
#define CF_ENUM_AVAILABLE(_mac, _ios)
#endif
#endif /* __WebKitAvailability__ */

View File

@ -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::atomicCompareExchangeWeakRelaxed(wordPtr, oldValue, static_cast<uint8_t>(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");
}

View File

@ -0,0 +1,37 @@
/*
* 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.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/* Regression test for webkit.org/b/142513 */
void testCompareAndSwap();
#ifdef __cplusplus
} /* extern "C" */
#endif

View File

@ -0,0 +1,34 @@
/*
* 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.
*/
#pragma once
#include <JavaScriptCore/JavaScriptCore.h>
#if JSC_OBJC_API_ENABLED
void currentThisInsideBlockGetterTest();
#endif // JSC_OBJC_API_ENABLED

View File

@ -0,0 +1,125 @@
/*
* 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.
*/
#include "CurrentThisInsideBlockGetterTest.h"
#if JSC_OBJC_API_ENABLED
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
static JSObjectRef CallAsConstructor(JSContextRef ctx, JSObjectRef constructor, size_t, const JSValueRef[], JSValueRef*)
{
JSObjectRef newObjectRef = NULL;
NSMutableDictionary *constructorPrivateProperties = (__bridge NSMutableDictionary *)(JSObjectGetPrivate(constructor));
NSDictionary *constructorDescriptor = constructorPrivateProperties[@"constructorDescriptor"];
newObjectRef = JSObjectMake(ctx, NULL, NULL);
NSDictionary *objectProperties = constructorDescriptor[@"objectProperties"];
if (objectProperties) {
JSValue *newObject = [JSValue valueWithJSValueRef:newObjectRef inContext:[JSContext contextWithJSGlobalContextRef:JSContextGetGlobalContext(ctx)]];
for (NSString *objectProperty in objectProperties) {
[newObject defineProperty:objectProperty descriptor:objectProperties[objectProperty]];
}
}
return newObjectRef;
}
static void ConstructorFinalize(JSObjectRef object)
{
NSMutableDictionary *privateProperties = (__bridge NSMutableDictionary *)(JSObjectGetPrivate(object));
CFBridgingRelease((__bridge CFTypeRef)(privateProperties));
JSObjectSetPrivate(object, NULL);
}
static JSClassRef ConstructorClass(void)
{
static JSClassRef constructorClass = NULL;
if (constructorClass == NULL) {
JSClassDefinition classDefinition = kJSClassDefinitionEmpty;
classDefinition.className = "Constructor";
classDefinition.callAsConstructor = CallAsConstructor;
classDefinition.finalize = ConstructorFinalize;
constructorClass = JSClassCreate(&classDefinition);
}
return constructorClass;
}
@interface JSValue (ConstructorCreation)
+ (JSValue *)valueWithConstructorDescriptor:(NSDictionary *)constructorDescriptor inContext:(JSContext *)context;
@end
@implementation JSValue (ConstructorCreation)
+ (JSValue *)valueWithConstructorDescriptor:(id)constructorDescriptor inContext:(JSContext *)context
{
NSMutableDictionary *privateProperties = [@{ @"constructorDescriptor" : constructorDescriptor } mutableCopy];
JSGlobalContextRef ctx = [context JSGlobalContextRef];
JSObjectRef constructorRef = JSObjectMake(ctx, ConstructorClass(), (void *)CFBridgingRetain(privateProperties));
JSValue *constructor = [JSValue valueWithJSValueRef:constructorRef inContext:context];
return constructor;
}
@end
@interface JSContext (ConstructorCreation)
- (JSValue *)valueWithConstructorDescriptor:(NSDictionary *)constructorDescriptor;
@end
@implementation JSContext (ConstructorCreation)
- (JSValue *)valueWithConstructorDescriptor:(id)constructorDescriptor
{
return [JSValue valueWithConstructorDescriptor:constructorDescriptor inContext:self];
}
@end
void currentThisInsideBlockGetterTest()
{
@autoreleasepool {
JSContext *context = [[JSContext alloc] init];
JSValue *myConstructor = [context valueWithConstructorDescriptor:@{
@"objectProperties" : @{
@"currentThis" : @{ JSPropertyDescriptorGetKey : ^{ return JSContext.currentThis; } },
},
}];
JSValue *myObj1 = [myConstructor constructWithArguments:nil];
NSLog(@"myObj1.currentThis: %@", myObj1[@"currentThis"]);
JSValue *myObj2 = [myConstructor constructWithArguments:@[ @"bar" ]];
NSLog(@"myObj2.currentThis: %@", myObj2[@"currentThis"]);
}
}
#endif // JSC_OBJC_API_ENABLED

View File

@ -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);
}

View File

@ -0,0 +1,30 @@
/*
* 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.
*/
#pragma once
void customGlobalObjectClassTest(void);
void globalObjectSetPrototypeTest(void);
void globalObjectPrivatePropertyTest(void);

32
API/tests/DateTests.h Normal file
View File

@ -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

149
API/tests/DateTests.mm Normal file
View File

@ -0,0 +1,149 @@
/*
* 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 "DateTests.h"
#import <Foundation/Foundation.h>
#if JSC_OBJC_API_ENABLED
extern "C" void checkResult(NSString *description, bool passed);
@interface DateTests : NSObject
+ (void) NSDateToJSDateTest;
+ (void) JSDateToNSDateTest;
+ (void) roundTripThroughJSDateTest;
+ (void) roundTripThroughObjCDateTest;
@end
static unsigned unitFlags = NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;
@implementation DateTests
+ (void) NSDateToJSDateTest
{
JSContext *context = [[JSContext alloc] init];
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateComponents *components = [[NSCalendar currentCalendar] components:unitFlags fromDate:now];
JSValue *jsNow = [JSValue valueWithObject:now inContext:context];
int year = [[jsNow invokeMethod:@"getFullYear" withArguments:@[]] toInt32];
// Months are 0-indexed for JavaScript Dates.
int month = [[jsNow invokeMethod:@"getMonth" withArguments:@[]] toInt32] + 1;
int day = [[jsNow invokeMethod:@"getDate" withArguments:@[]] toInt32];
int hour = [[jsNow invokeMethod:@"getHours" withArguments:@[]] toInt32];
int minute = [[jsNow invokeMethod:@"getMinutes" withArguments:@[]] toInt32];
int second = [[jsNow invokeMethod:@"getSeconds" withArguments:@[]] toInt32];
checkResult(@"NSDate to JS Date", year == [components year]
&& month == [components month]
&& day == [components day]
&& hour == [components hour]
&& minute == [components minute]
&& second == [components second]);
}
+ (void) JSDateToNSDateTest
{
JSContext *context = [[JSContext alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM dd',' yyyy hh:mm:ss"];
NSDate *februaryFourth2014 = [formatter dateFromString:@"February 4, 2014 11:40:03"];
NSDateComponents *components = [[NSCalendar currentCalendar] components:unitFlags fromDate:februaryFourth2014];
// Months are 0-indexed for JavaScript Dates.
JSValue *jsDate = [context[@"Date"] constructWithArguments:@[@2014, @1, @4, @11, @40, @3]];
int year = [[jsDate invokeMethod:@"getFullYear" withArguments:@[]] toInt32];
int month = [[jsDate invokeMethod:@"getMonth" withArguments:@[]] toInt32] + 1;
int day = [[jsDate invokeMethod:@"getDate" withArguments:@[]] toInt32];
int hour = [[jsDate invokeMethod:@"getHours" withArguments:@[]] toInt32];
int minute = [[jsDate invokeMethod:@"getMinutes" withArguments:@[]] toInt32];
int second = [[jsDate invokeMethod:@"getSeconds" withArguments:@[]] toInt32];
checkResult(@"JS Date to NSDate", year == [components year]
&& month == [components month]
&& day == [components day]
&& hour == [components hour]
&& minute == [components minute]
&& second == [components second]);
}
+ (void) roundTripThroughJSDateTest
{
JSContext *context = [[JSContext alloc] init];
[context evaluateScript:@"function jsReturnDate(date) { return date; }"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM dd',' yyyy hh:mm:ss"];
NSDate *februaryFourth2014 = [formatter dateFromString:@"February 4, 2014 11:40:03"];
NSDateComponents *components = [[NSCalendar currentCalendar] components:unitFlags fromDate:februaryFourth2014];
JSValue *roundTripThroughJS = [context[@"jsReturnDate"] callWithArguments:@[februaryFourth2014]];
int year = [[roundTripThroughJS invokeMethod:@"getFullYear" withArguments:@[]] toInt32];
// Months are 0-indexed for JavaScript Dates.
int month = [[roundTripThroughJS invokeMethod:@"getMonth" withArguments:@[]] toInt32] + 1;
int day = [[roundTripThroughJS invokeMethod:@"getDate" withArguments:@[]] toInt32];
int hour = [[roundTripThroughJS invokeMethod:@"getHours" withArguments:@[]] toInt32];
int minute = [[roundTripThroughJS invokeMethod:@"getMinutes" withArguments:@[]] toInt32];
int second = [[roundTripThroughJS invokeMethod:@"getSeconds" withArguments:@[]] toInt32];
checkResult(@"JS date round trip", year == [components year]
&& month == [components month]
&& day == [components day]
&& hour == [components hour]
&& minute == [components minute]
&& second == [components second]);
}
+ (void) roundTripThroughObjCDateTest
{
JSContext *context = [[JSContext alloc] init];
context[@"objcReturnDate"] = ^(NSDate *date) {
return date;
};
[context evaluateScript:@"function test() {\
var date = new Date(2014, 1, 4, 11, 40, 3); \
var result = objcReturnDate(date); \
return date.getYear() === result.getYear() \
&& date.getMonth() === result.getMonth() \
&& date.getDate() === result.getDate() \
&& date.getHours() === result.getHours() \
&& date.getMinutes() === result.getMinutes() \
&& date.getSeconds() === result.getSeconds() \
&& date.getMilliseconds() === result.getMilliseconds();\
}"];
checkResult(@"ObjC date round trip", [[context[@"test"] callWithArguments:@[]] toBool]);
}
@end
void runDateTests()
{
@autoreleasepool {
[DateTests NSDateToJSDateTest];
[DateTests JSDateToNSDateTest];
[DateTests roundTripThroughJSDateTest];
[DateTests roundTripThroughObjCDateTest];
}
}
#endif // JSC_OBJC_API_ENABLED

View File

@ -0,0 +1,374 @@
/*
* 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, "--useConcurrentJIT=false --useLLInt=true --useJIT=false" },
{ "Baseline", 0, "--useConcurrentJIT=false --useLLInt=true --useJIT=true --useDFGJIT=false" },
{ "DFG", 0, "--useConcurrentJIT=false --useLLInt=true --useJIT=true --useDFGJIT=true --useFTLJIT=false" },
{ "FTL", 200, "--useConcurrentJIT=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 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 = 300 + tierAdjustmentMillis;
StringBuilder scriptBuilder;
scriptBuilder.appendLiteral("function foo() { var startTime = currentCPUTime(); while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
scriptBuilder.appendLiteral(") break; } } foo();");
JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
exception = nullptr;
shouldTerminateCallbackWasCalled = false;
auto startTime = currentCPUTime();
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 script timeout with tail calls: */
timeLimit = (100 + tierAdjustmentMillis) / 1000.0;
JSContextGroupSetExecutionTimeLimit(contextGroup, timeLimit, shouldTerminateCallback, 0);
{
unsigned timeAfterWatchdogShouldHaveFired = 300 + tierAdjustmentMillis;
StringBuilder scriptBuilder;
scriptBuilder.appendLiteral("var startTime = currentCPUTime();"
"function recurse(i) {"
"'use strict';"
"if (i % 1000 === 0) {"
"if (currentCPUTime() - startTime >");
scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
scriptBuilder.appendLiteral(" ) { return; }");
scriptBuilder.appendLiteral(" }");
scriptBuilder.appendLiteral(" return recurse(i + 1); }");
scriptBuilder.appendLiteral("recurse(0);");
JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
exception = nullptr;
shouldTerminateCallbackWasCalled = false;
auto startTime = currentCPUTime();
JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
auto endTime = currentCPUTime();
if (((endTime - startTime) < milliseconds(timeAfterWatchdogShouldHaveFired)) && shouldTerminateCallbackWasCalled)
printf("PASS: %s script with infinite tail calls timed out as expected .\n", tierOptions.tier);
else {
if ((endTime - startTime) >= milliseconds(timeAfterWatchdogShouldHaveFired))
printf("FAIL: %s script with infinite tail calls did not time out as expected.\n", tierOptions.tier);
if (!shouldTerminateCallbackWasCalled)
printf("FAIL: %s script with infinite tail calls' 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 = 300 + tierAdjustmentMillis;
StringBuilder scriptBuilder;
scriptBuilder.appendLiteral("function foo() { var startTime = currentCPUTime(); try { while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
scriptBuilder.appendLiteral(") break; } } catch(e) { } } foo();");
JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
exception = nullptr;
shouldTerminateCallbackWasCalled = false;
auto startTime = currentCPUTime();
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 = 300 + tierAdjustmentMillis;
StringBuilder scriptBuilder;
scriptBuilder.appendLiteral("function foo() { var startTime = currentCPUTime(); while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
scriptBuilder.appendLiteral(") break; } } foo();");
JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
exception = nullptr;
shouldTerminateCallbackWasCalled = false;
auto startTime = currentCPUTime();
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 = 300 + tierAdjustmentMillis;
StringBuilder scriptBuilder;
scriptBuilder.appendLiteral("function foo() { var startTime = currentCPUTime(); while (true) { for (var i = 0; i < 1000; i++); if (currentCPUTime() - startTime > ");
scriptBuilder.appendNumber(timeAfterWatchdogShouldHaveFired / 1000.0);
scriptBuilder.appendLiteral(") break; } } foo();");
JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
exception = nullptr;
cancelTerminateCallbackWasCalled = false;
auto startTime = currentCPUTime();
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 = 250 + tierAdjustmentMillis;
unsigned timeAfterExtendedDeadline = 600 + tierAdjustmentMillis;
unsigned maxBusyLoopTime = 750 + tierAdjustmentMillis;
StringBuilder scriptBuilder;
scriptBuilder.appendLiteral("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.appendLiteral(") break; } } foo();");
JSStringRef script = JSStringCreateWithUTF8CString(scriptBuilder.toString().utf8().data());
exception = nullptr;
extendTerminateCallbackCalled = 0;
auto startTime = currentCPUTime();
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;
}

View File

@ -0,0 +1,37 @@
/*
* 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.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/* Returns 1 if failures were encountered. Else, returns 0. */
int testExecutionTimeLimit();
#ifdef __cplusplus
} /* extern "C" */
#endif

View File

@ -0,0 +1,91 @@
/*
* Copyright (C) 2016 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 "FunctionOverridesTest.h"
#include "FunctionOverrides.h"
#include "InitializeThreading.h"
#include "JSContextRefPrivate.h"
#include "JavaScriptCore.h"
#include "Options.h"
#include <string>
using JSC::Options;
int testFunctionOverrides()
{
bool failed = false;
JSC::initializeThreading();
Options::initialize(); // Ensure options is initialized first.
const char* oldFunctionOverrides = Options::functionOverrides();
Options::functionOverrides() = "testapi-function-overrides.js";
JSC::FunctionOverrides::reinstallOverrides();
JSGlobalContextRef context = JSGlobalContextCreateInGroup(nullptr, nullptr);
JSObjectRef globalObject = JSContextGetGlobalObject(context);
ASSERT_UNUSED(globalObject, JSValueIsObject(context, globalObject));
const char* scriptString =
"var str = '';" "\n"
"function f1() { /* Original f1 */ }" "\n"
"str += f1 + '\\n';" "\n"
"var f2 = function() {" "\n"
" // Original f2" "\n"
"}" "\n"
"str += f2 + '\\n';" "\n"
"str += (function() { /* Original f3 */ }) + '\\n';" "\n"
"var f4Source = '/* Original f4 */'" "\n"
"var f4 = new Function(f4Source);" "\n"
"str += f4 + '\\n';" "\n"
"\n"
"var expectedStr =" "\n"
"'function f1() { /* Overridden f1 */ }\\n"
"function () { /* Overridden f2 */ }\\n"
"function () { /* Overridden f3 */ }\\n"
"function anonymous() { /* Overridden f4 */ }\\n';"
"var result = (str == expectedStr);" "\n"
"result";
JSStringRef script = JSStringCreateWithUTF8CString(scriptString);
JSValueRef exception = nullptr;
JSValueRef resultRef = JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
if (!JSValueIsBoolean(context, resultRef) || !JSValueToBoolean(context, resultRef))
failed = true;
JSGlobalContextRelease(context);
JSC::Options::functionOverrides() = oldFunctionOverrides;
JSC::FunctionOverrides::reinstallOverrides();
printf("%s: function override tests.\n", failed ? "FAIL" : "PASS");
return failed;
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (C) 2016 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.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/* Returns 1 if failures were encountered. Else, returns 0. */
int testFunctionOverrides();
#ifdef __cplusplus
} /* extern "C" */
#endif

View File

@ -0,0 +1,55 @@
/*
* 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"
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;
}

View File

@ -0,0 +1,39 @@
/*
* 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.
*/
#pragma once
#include "JSContextRefPrivate.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Returns 1 if failures were encountered. Else, returns 0. */
int testGlobalContextWithFinalizer();
#ifdef __cplusplus
} /* extern "C" */
#endif

34
API/tests/JSExportTests.h Normal file
View File

@ -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

137
API/tests/JSExportTests.mm Normal file
View File

@ -0,0 +1,137 @@
/*
* 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 "JSExportTests.h"
#import <objc/runtime.h>
#import <objc/objc.h>
#if JSC_OBJC_API_ENABLED
extern "C" void checkResult(NSString *description, bool passed);
@interface JSExportTests : NSObject
+ (void) exportInstanceMethodWithIdProtocolTest;
+ (void) exportInstanceMethodWithClassProtocolTest;
+ (void) exportDynamicallyGeneratedProtocolTest;
@end
@protocol TruthTeller
- (BOOL) returnTrue;
@end
@interface TruthTeller : NSObject<TruthTeller>
@end
@implementation TruthTeller
- (BOOL) returnTrue
{
return true;
}
@end
@protocol ExportMethodWithIdProtocol <JSExport>
- (void) methodWithIdProtocol:(id<TruthTeller>)object;
@end
@interface ExportMethodWithIdProtocol : NSObject<ExportMethodWithIdProtocol>
@end
@implementation ExportMethodWithIdProtocol
- (void) methodWithIdProtocol:(id<TruthTeller>)object
{
checkResult(@"Exporting a method with id<protocol> in the type signature", [object returnTrue]);
}
@end
@protocol ExportMethodWithClassProtocol <JSExport>
- (void) methodWithClassProtocol:(NSObject<TruthTeller> *)object;
@end
@interface ExportMethodWithClassProtocol : NSObject<ExportMethodWithClassProtocol>
@end
@implementation ExportMethodWithClassProtocol
- (void) methodWithClassProtocol:(NSObject<TruthTeller> *)object
{
checkResult(@"Exporting a method with class<protocol> in the type signature", [object returnTrue]);
}
@end
@implementation JSExportTests
+ (void) exportInstanceMethodWithIdProtocolTest
{
JSContext *context = [[JSContext alloc] init];
context[@"ExportMethodWithIdProtocol"] = [ExportMethodWithIdProtocol class];
context[@"makeTestObject"] = ^{
return [[ExportMethodWithIdProtocol alloc] init];
};
context[@"opaqueObject"] = [[TruthTeller alloc] init];
[context evaluateScript:@"makeTestObject().methodWithIdProtocol(opaqueObject);"];
checkResult(@"Successfully exported instance method", !context.exception);
}
+ (void) exportInstanceMethodWithClassProtocolTest
{
JSContext *context = [[JSContext alloc] init];
context[@"ExportMethodWithClassProtocol"] = [ExportMethodWithClassProtocol class];
context[@"makeTestObject"] = ^{
return [[ExportMethodWithClassProtocol alloc] init];
};
context[@"opaqueObject"] = [[TruthTeller alloc] init];
[context evaluateScript:@"makeTestObject().methodWithClassProtocol(opaqueObject);"];
checkResult(@"Successfully exported instance method", !context.exception);
}
+ (void) exportDynamicallyGeneratedProtocolTest
{
JSContext *context = [[JSContext alloc] init];
Protocol *dynProtocol = objc_allocateProtocol("NSStringJSExport");
Protocol *jsExportProtocol = @protocol(JSExport);
protocol_addProtocol(dynProtocol, jsExportProtocol);
Method method = class_getInstanceMethod([NSString class], @selector(boolValue));
protocol_addMethodDescription(dynProtocol, @selector(boolValue), method_getTypeEncoding(method), YES, YES);
NSLog(@"type encoding = %s", method_getTypeEncoding(method));
protocol_addMethodDescription(dynProtocol, @selector(boolValue), "B@:", YES, YES);
objc_registerProtocol(dynProtocol);
class_addProtocol([NSString class], dynProtocol);
context[@"NSString"] = [NSString class];
context[@"myString"] = @"YES";
JSValue *value = [context evaluateScript:@"myString.boolValue()"];
checkResult(@"Dynamically generated JSExport-ed protocols are ignored", [value isUndefined] && !!context.exception);
}
@end
void runJSExportTests()
{
@autoreleasepool {
[JSExportTests exportInstanceMethodWithIdProtocolTest];
[JSExportTests exportInstanceMethodWithClassProtocolTest];
[JSExportTests exportDynamicallyGeneratedProtocolTest];
}
}
#endif // JSC_OBJC_API_ENABLED

197
API/tests/JSNode.c Normal file
View File

@ -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());
}

34
API/tests/JSNode.h Normal file
View File

@ -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.
*/
#pragma once
#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);

124
API/tests/JSNodeList.c Normal file
View File

@ -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);
}

31
API/tests/JSNodeList.h Normal file
View File

@ -0,0 +1,31 @@
/*
* 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.
*/
#pragma once
#include "JSBase.h"
#include "NodeList.h"
extern JSObjectRef JSNodeList_new(JSContextRef, NodeList*);

View File

@ -0,0 +1,69 @@
/*
* Copyright (C) 2016 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 "JSONParseTest.h"
#include "JSCInlines.h"
#include "JSGlobalObject.h"
#include "JSONObject.h"
#include "VM.h"
#include <wtf/RefPtr.h>
using namespace JSC;
int testJSONParse()
{
bool failed = false;
RefPtr<VM> vm = VM::create();
JSLockHolder locker(vm.get());
JSGlobalObject* globalObject = JSGlobalObject::create(*vm, JSGlobalObject::createStructure(*vm, jsNull()));
ExecState* exec = globalObject->globalExec();
JSValue v0 = JSONParse(exec, "");
JSValue v1 = JSONParse(exec, "#$%^");
JSValue v2 = JSONParse(exec, String());
UChar emptyUCharArray[1] = { '\0' };
JSValue v3 = JSONParse(exec, String(emptyUCharArray, 0));
JSValue v4;
JSValue v5 = JSONParse(exec, "123");
failed = failed || (v0 != v1);
failed = failed || (v1 != v2);
failed = failed || (v2 != v3);
failed = failed || (v3 != v4);
failed = failed || (v4 == v5);
vm = nullptr;
if (failed)
printf("FAIL: JSONParse String test.\n");
else
printf("PASS: JSONParse String test.\n");
return failed;
}

36
API/tests/JSONParseTest.h Normal file
View File

@ -0,0 +1,36 @@
/*
* Copyright (C) 2016 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.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
int testJSONParse();
#ifdef __cplusplus
} /* extern "C" */
#endif

85
API/tests/Node.c Normal file
View File

@ -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);
}

47
API/tests/Node.h Normal file
View File

@ -0,0 +1,47 @@
/*
* 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.
*/
#pragma once
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);

81
API/tests/NodeList.c Normal file
View File

@ -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);
}
}

39
API/tests/NodeList.h Normal file
View File

@ -0,0 +1,39 @@
/*
* 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.
*/
#pragma once
#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*);

View File

@ -0,0 +1,182 @@
/*
* 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 "PingPongStackOverflowTest.h"
#include "InitializeThreading.h"
#include "JSContextRefPrivate.h"
#include "JavaScriptCore.h"
#include "Options.h"
#include <wtf/text/StringBuilder.h>
using JSC::Options;
static JSGlobalContextRef context = nullptr;
static int nativeRecursionCount = 0;
static bool PingPongStackOverflowObject_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;
int countAtEntry = nativeRecursionCount++;
JSValueRef result = 0;
if (nativeRecursionCount < 100) {
JSObjectRef function = JSValueToObject(context, hasInstance, exception);
result = JSObjectCallAsFunction(context, function, constructor, 1, &possibleValue, exception);
} else {
StringBuilder builder;
builder.appendLiteral("dummy.valueOf([0]");
for (int i = 1; i < 35000; i++) {
builder.appendLiteral(", [");
builder.appendNumber(i);
builder.appendLiteral("]");
}
builder.appendLiteral(");");
JSStringRef script = JSStringCreateWithUTF8CString(builder.toString().utf8().data());
result = JSEvaluateScript(context, script, NULL, NULL, 1, exception);
JSStringRelease(script);
}
--nativeRecursionCount;
if (nativeRecursionCount != countAtEntry)
printf(" ERROR: PingPongStackOverflow test saw a recursion count mismatch\n");
return result && JSValueToBoolean(context, result);
}
JSClassDefinition PingPongStackOverflowObject_definition = {
0,
kJSClassAttributeNone,
"PingPongStackOverflowObject",
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
PingPongStackOverflowObject_hasInstance,
NULL,
};
static JSClassRef PingPongStackOverflowObject_class(JSContextRef context)
{
UNUSED_PARAM(context);
static JSClassRef jsClass;
if (!jsClass)
jsClass = JSClassCreate(&PingPongStackOverflowObject_definition);
return jsClass;
}
// This tests tests a stack overflow on VM reentry into a JS function from a native function
// after ping-pong'ing back and forth between JS and native functions multiple times.
// This test should not hang or crash.
int testPingPongStackOverflow()
{
bool failed = false;
JSC::initializeThreading();
Options::initialize(); // Ensure options is initialized first.
auto origSoftReservedZoneSize = Options::softReservedZoneSize();
auto origReservedZoneSize = Options::reservedZoneSize();
auto origUseLLInt = Options::useLLInt();
auto origMaxPerThreadStackUsage = Options::maxPerThreadStackUsage();
Options::softReservedZoneSize() = 128 * KB;
Options::reservedZoneSize() = 64 * KB;
#if ENABLE(JIT)
// Normally, we want to disable the LLINT to force the use of JITted code which is necessary for
// reproducing the regression in https://bugs.webkit.org/show_bug.cgi?id=148749. However, we only
// want to do this if the LLINT isn't the only available execution engine.
Options::useLLInt() = false;
#endif
const char* scriptString =
"var count = 0;" \
"PingPongStackOverflowObject.hasInstance = function f() {" \
" return (undefined instanceof PingPongStackOverflowObject);" \
"};" \
"PingPongStackOverflowObject.__proto__ = undefined;" \
"undefined instanceof PingPongStackOverflowObject;";
JSValueRef scriptResult = nullptr;
JSValueRef exception = nullptr;
JSStringRef script = JSStringCreateWithUTF8CString(scriptString);
nativeRecursionCount = 0;
context = JSGlobalContextCreateInGroup(nullptr, nullptr);
JSObjectRef globalObject = JSContextGetGlobalObject(context);
ASSERT(JSValueIsObject(context, globalObject));
JSObjectRef PingPongStackOverflowObject = JSObjectMake(context, PingPongStackOverflowObject_class(context), NULL);
JSStringRef PingPongStackOverflowObjectString = JSStringCreateWithUTF8CString("PingPongStackOverflowObject");
JSObjectSetProperty(context, globalObject, PingPongStackOverflowObjectString, PingPongStackOverflowObject, kJSPropertyAttributeNone, NULL);
JSStringRelease(PingPongStackOverflowObjectString);
unsigned stackSize = 32 * KB;
Options::maxPerThreadStackUsage() = stackSize + Options::softReservedZoneSize();
exception = nullptr;
scriptResult = JSEvaluateScript(context, script, nullptr, nullptr, 1, &exception);
if (!exception) {
printf("FAIL: PingPongStackOverflowError not thrown in PingPongStackOverflow test\n");
failed = true;
} else if (nativeRecursionCount) {
printf("FAIL: Unbalanced native recursion count: %d in PingPongStackOverflow test\n", nativeRecursionCount);
failed = true;
} else {
printf("PASS: PingPongStackOverflow test.\n");
}
Options::softReservedZoneSize() = origSoftReservedZoneSize;
Options::reservedZoneSize() = origReservedZoneSize;
Options::useLLInt() = origUseLLInt;
Options::maxPerThreadStackUsage() = origMaxPerThreadStackUsage;
return failed;
}

View File

@ -0,0 +1,36 @@
/*
* 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.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
int testPingPongStackOverflow();
#ifdef __cplusplus
} /* extern "C" */
#endif

34
API/tests/Regress141275.h Normal file
View File

@ -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

Some files were not shown because too many files have changed in this diff Show More