diff --git a/src/servo/dom/bindings/codegen/BindingGen.py b/src/servo/dom/bindings/codegen/BindingGen.py new file mode 100644 index 00000000000..aa1337ea2a8 --- /dev/null +++ b/src/servo/dom/bindings/codegen/BindingGen.py @@ -0,0 +1,69 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this file, +# You can obtain one at http://mozilla.org/MPL/2.0/. + +import os +import cPickle +import WebIDL +from Configuration import * +from Codegen import CGBindingRoot, replaceFileIfChanged +# import Codegen in general, so we can set a variable on it +import Codegen + +def generate_binding_header(config, outputprefix, webidlfile): + """ + |config| Is the configuration object. + |outputprefix| is a prefix to use for the header guards and filename. + """ + + filename = outputprefix + ".h" + root = CGBindingRoot(config, outputprefix, webidlfile) + if replaceFileIfChanged(filename, root.declare()): + print "Generating binding header: %s" % (filename) + +def generate_binding_cpp(config, outputprefix, webidlfile): + """ + |config| Is the configuration object. + |outputprefix| is a prefix to use for the header guards and filename. + """ + + filename = outputprefix + ".cpp" + root = CGBindingRoot(config, outputprefix, webidlfile) + if replaceFileIfChanged(filename, root.define()): + print "Generating binding implementation: %s" % (filename) + +def main(): + + # Parse arguments. + from optparse import OptionParser + usagestring = "usage: %prog [header|cpp] configFile outputPrefix webIDLFile" + o = OptionParser(usage=usagestring) + o.add_option("--verbose-errors", action='store_true', default=False, + help="When an error happens, display the Python traceback.") + (options, args) = o.parse_args() + + if len(args) != 4 or (args[0] != "header" and args[0] != "cpp"): + o.error(usagestring) + buildTarget = args[0] + configFile = os.path.normpath(args[1]) + outputPrefix = args[2] + webIDLFile = os.path.normpath(args[3]) + + # Load the parsing results + f = open('ParserResults.pkl', 'rb') + parserData = cPickle.load(f) + f.close() + + # Create the configuration data. + config = Configuration(configFile, parserData) + + # Generate the prototype classes. + if buildTarget == "header": + generate_binding_header(config, outputPrefix, webIDLFile); + elif buildTarget == "cpp": + generate_binding_cpp(config, outputPrefix, webIDLFile); + else: + assert False # not reached + +if __name__ == '__main__': + main() diff --git a/src/servo/dom/bindings/codegen/BindingUtils.cpp b/src/servo/dom/bindings/codegen/BindingUtils.cpp new file mode 100644 index 00000000000..27ac92e3596 --- /dev/null +++ b/src/servo/dom/bindings/codegen/BindingUtils.cpp @@ -0,0 +1,633 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/ +/* vim: set ts=2 sw=2 et tw=79: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "BindingUtils.h" + +#include "WrapperFactory.h" +#include "xpcprivate.h" +#include "XPCQuickStubs.h" + +namespace mozilla { +namespace dom { + +JSErrorFormatString ErrorFormatString[] = { +#define MSG_DEF(_name, _argc, _str) \ + { _str, _argc, JSEXN_TYPEERR }, +#include "mozilla/dom/Errors.msg" +#undef MSG_DEF +}; + +const JSErrorFormatString* +GetErrorMessage(void* aUserRef, const char* aLocale, + const unsigned aErrorNumber) +{ + MOZ_ASSERT(aErrorNumber < ArrayLength(ErrorFormatString)); + return &ErrorFormatString[aErrorNumber]; +} + +bool +ThrowErrorMessage(JSContext* aCx, const ErrNum aErrorNumber, ...) +{ + va_list ap; + va_start(ap, aErrorNumber); + JS_ReportErrorNumberVA(aCx, GetErrorMessage, NULL, + static_cast(aErrorNumber), ap); + va_end(ap); + return false; +} + +bool +DefineConstants(JSContext* cx, JSObject* obj, ConstantSpec* cs) +{ + for (; cs->name; ++cs) { + JSBool ok = + JS_DefineProperty(cx, obj, cs->name, cs->value, NULL, NULL, + JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT); + if (!ok) { + return false; + } + } + return true; +} + +static inline bool +Define(JSContext* cx, JSObject* obj, JSFunctionSpec* spec) { + return JS_DefineFunctions(cx, obj, spec); +} +static inline bool +Define(JSContext* cx, JSObject* obj, JSPropertySpec* spec) { + return JS_DefineProperties(cx, obj, spec); +} +static inline bool +Define(JSContext* cx, JSObject* obj, ConstantSpec* spec) { + return DefineConstants(cx, obj, spec); +} + +template +bool +DefinePrefable(JSContext* cx, JSObject* obj, Prefable* props) +{ + MOZ_ASSERT(props); + MOZ_ASSERT(props->specs); + do { + // Define if enabled + if (props->enabled) { + if (!Define(cx, obj, props->specs)) { + return false; + } + } + } while ((++props)->specs); + return true; +} + +// We should use JSFunction objects for interface objects, but we need a custom +// hasInstance hook because we have new interface objects on prototype chains of +// old (XPConnect-based) bindings. Because Function.prototype.toString throws if +// passed a non-Function object we also need to provide our own toString method +// for interface objects. + +enum { + TOSTRING_CLASS_RESERVED_SLOT = 0, + TOSTRING_NAME_RESERVED_SLOT = 1 +}; + +JSBool +InterfaceObjectToString(JSContext* cx, unsigned argc, JS::Value *vp) +{ + JSObject* callee = JSVAL_TO_OBJECT(JS_CALLEE(cx, vp)); + + JSObject* obj = JS_THIS_OBJECT(cx, vp); + if (!obj) { + JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_CONVERT_TO, + "null", "object"); + return false; + } + + jsval v = js::GetFunctionNativeReserved(callee, TOSTRING_CLASS_RESERVED_SLOT); + JSClass* clasp = static_cast(JSVAL_TO_PRIVATE(v)); + + v = js::GetFunctionNativeReserved(callee, TOSTRING_NAME_RESERVED_SLOT); + JSString* jsname = static_cast(JSVAL_TO_STRING(v)); + size_t length; + const jschar* name = JS_GetInternedStringCharsAndLength(jsname, &length); + + if (js::GetObjectJSClass(obj) != clasp) { + JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_INCOMPATIBLE_PROTO, + NS_ConvertUTF16toUTF8(name).get(), "toString", + "object"); + return false; + } + + nsString str; + str.AppendLiteral("function "); + str.Append(name, length); + str.AppendLiteral("() {"); + str.Append('\n'); + str.AppendLiteral(" [native code]"); + str.Append('\n'); + str.AppendLiteral("}"); + + return xpc::NonVoidStringToJsval(cx, str, vp); +} + +static JSObject* +CreateInterfaceObject(JSContext* cx, JSObject* global, JSObject* receiver, + JSClass* constructorClass, JSNative constructorNative, + unsigned ctorNargs, JSObject* proto, + Prefable* staticMethods, + Prefable* constants, + const char* name) +{ + JSObject* constructor; + if (constructorClass) { + JSObject* functionProto = JS_GetFunctionPrototype(cx, global); + if (!functionProto) { + return NULL; + } + constructor = JS_NewObject(cx, constructorClass, functionProto, global); + } else { + MOZ_ASSERT(constructorNative); + JSFunction* fun = JS_NewFunction(cx, constructorNative, ctorNargs, + JSFUN_CONSTRUCTOR, global, name); + if (!fun) { + return NULL; + } + constructor = JS_GetFunctionObject(fun); + } + if (!constructor) { + return NULL; + } + + if (staticMethods && !DefinePrefable(cx, constructor, staticMethods)) { + return NULL; + } + + if (constructorClass) { + JSFunction* toString = js::DefineFunctionWithReserved(cx, constructor, + "toString", + InterfaceObjectToString, + 0, 0); + if (!toString) { + return NULL; + } + + JSObject* toStringObj = JS_GetFunctionObject(toString); + js::SetFunctionNativeReserved(toStringObj, TOSTRING_CLASS_RESERVED_SLOT, + PRIVATE_TO_JSVAL(constructorClass)); + + JSString *str = ::JS_InternString(cx, name); + if (!str) { + return NULL; + } + js::SetFunctionNativeReserved(toStringObj, TOSTRING_NAME_RESERVED_SLOT, + STRING_TO_JSVAL(str)); + } + + if (constants && !DefinePrefable(cx, constructor, constants)) { + return NULL; + } + + if (proto && !JS_LinkConstructorAndPrototype(cx, constructor, proto)) { + return NULL; + } + + JSBool alreadyDefined; + if (!JS_AlreadyHasOwnProperty(cx, receiver, name, &alreadyDefined)) { + return NULL; + } + + // This is Enumerable: False per spec. + if (!alreadyDefined && + !JS_DefineProperty(cx, receiver, name, OBJECT_TO_JSVAL(constructor), NULL, + NULL, 0)) { + return NULL; + } + + return constructor; +} + +static JSObject* +CreateInterfacePrototypeObject(JSContext* cx, JSObject* global, + JSObject* parentProto, JSClass* protoClass, + Prefable* methods, + Prefable* properties, + Prefable* constants) +{ + JSObject* ourProto = JS_NewObjectWithUniqueType(cx, protoClass, parentProto, + global); + if (!ourProto) { + return NULL; + } + + if (methods && !DefinePrefable(cx, ourProto, methods)) { + return NULL; + } + + if (properties && !DefinePrefable(cx, ourProto, properties)) { + return NULL; + } + + if (constants && !DefinePrefable(cx, ourProto, constants)) { + return NULL; + } + + return ourProto; +} + +JSObject* +CreateInterfaceObjects(JSContext* cx, JSObject* global, JSObject *receiver, + JSObject* protoProto, JSClass* protoClass, + JSClass* constructorClass, JSNative constructor, + unsigned ctorNargs, const DOMClass* domClass, + Prefable* methods, + Prefable* properties, + Prefable* constants, + Prefable* staticMethods, const char* name) +{ + MOZ_ASSERT(protoClass || constructorClass || constructor, + "Need at least one class or a constructor!"); + MOZ_ASSERT(!(methods || properties) || protoClass, + "Methods or properties but no protoClass!"); + MOZ_ASSERT(!staticMethods || constructorClass || constructor, + "Static methods but no constructorClass or constructor!"); + MOZ_ASSERT(bool(name) == bool(constructorClass || constructor), + "Must have name precisely when we have an interface object"); + MOZ_ASSERT(!constructorClass || !constructor); + + JSObject* proto; + if (protoClass) { + proto = CreateInterfacePrototypeObject(cx, global, protoProto, protoClass, + methods, properties, constants); + if (!proto) { + return NULL; + } + + js::SetReservedSlot(proto, DOM_PROTO_INSTANCE_CLASS_SLOT, + JS::PrivateValue(const_cast(domClass))); + } + else { + proto = NULL; + } + + JSObject* interface; + if (constructorClass || constructor) { + interface = CreateInterfaceObject(cx, global, receiver, constructorClass, + constructor, ctorNargs, proto, + staticMethods, constants, name); + if (!interface) { + return NULL; + } + } + + return protoClass ? proto : interface; +} + +static bool +NativeInterface2JSObjectAndThrowIfFailed(XPCLazyCallContext& aLccx, + JSContext* aCx, + JS::Value* aRetval, + xpcObjectHelper& aHelper, + const nsIID* aIID, + bool aAllowNativeWrapper) +{ + nsresult rv; + if (!XPCConvert::NativeInterface2JSObject(aLccx, aRetval, NULL, aHelper, aIID, + NULL, aAllowNativeWrapper, &rv)) { + // I can't tell if NativeInterface2JSObject throws JS exceptions + // or not. This is a sloppy stab at the right semantics; the + // method really ought to be fixed to behave consistently. + if (!JS_IsExceptionPending(aCx)) { + Throw(aCx, NS_FAILED(rv) ? rv : NS_ERROR_UNEXPECTED); + } + return false; + } + return true; +} + +bool +DoHandleNewBindingWrappingFailure(JSContext* cx, JSObject* scope, + nsISupports* value, JS::Value* vp) +{ + if (JS_IsExceptionPending(cx)) { + return false; + } + + XPCLazyCallContext lccx(JS_CALLER, cx, scope); + + if (value) { + xpcObjectHelper helper(value); + return NativeInterface2JSObjectAndThrowIfFailed(lccx, cx, vp, helper, NULL, + true); + } + + return Throw(cx, NS_ERROR_XPC_BAD_CONVERT_JS); +} + +// Can only be called with the immediate prototype of the instance object. Can +// only be called on the prototype of an object known to be a DOM instance. +JSBool +InstanceClassHasProtoAtDepth(JSHandleObject protoObject, uint32_t protoID, + uint32_t depth) +{ + const DOMClass* domClass = static_cast( + js::GetReservedSlot(protoObject, DOM_PROTO_INSTANCE_CLASS_SLOT).toPrivate()); + return (uint32_t)domClass->mInterfaceChain[depth] == protoID; +} + +// Only set allowNativeWrapper to false if you really know you need it, if in +// doubt use true. Setting it to false disables security wrappers. +bool +XPCOMObjectToJsval(JSContext* cx, JSObject* scope, xpcObjectHelper &helper, + const nsIID* iid, bool allowNativeWrapper, JS::Value* rval) +{ + XPCLazyCallContext lccx(JS_CALLER, cx, scope); + + if (!NativeInterface2JSObjectAndThrowIfFailed(lccx, cx, rval, helper, iid, + allowNativeWrapper)) { + return false; + } + +#ifdef DEBUG + JSObject* jsobj = JSVAL_TO_OBJECT(*rval); + if (jsobj && !js::GetObjectParent(jsobj)) + NS_ASSERTION(js::GetObjectClass(jsobj)->flags & JSCLASS_IS_GLOBAL, + "Why did we recreate this wrapper?"); +#endif + + return true; +} + +JSBool +QueryInterface(JSContext* cx, unsigned argc, JS::Value* vp) +{ + JS::Value thisv = JS_THIS(cx, vp); + if (thisv == JSVAL_NULL) + return false; + + // Get the object. It might be a security wrapper, in which case we do a checked + // unwrap. + JSObject* origObj = JSVAL_TO_OBJECT(thisv); + JSObject* obj = js::UnwrapObjectChecked(cx, origObj); + if (!obj) + return false; + + nsISupports* native; + if (!UnwrapDOMObjectToISupports(obj, native)) { + return Throw(cx, NS_ERROR_FAILURE); + } + + if (argc < 1) { + return Throw(cx, NS_ERROR_XPC_NOT_ENOUGH_ARGS); + } + + JS::Value* argv = JS_ARGV(cx, vp); + if (!argv[0].isObject()) { + return Throw(cx, NS_ERROR_XPC_BAD_CONVERT_JS); + } + + nsIJSIID* iid; + xpc_qsSelfRef iidRef; + if (NS_FAILED(xpc_qsUnwrapArg(cx, argv[0], &iid, &iidRef.ptr, + &argv[0]))) { + return Throw(cx, NS_ERROR_XPC_BAD_CONVERT_JS); + } + MOZ_ASSERT(iid); + + if (iid->GetID()->Equals(NS_GET_IID(nsIClassInfo))) { + nsresult rv; + nsCOMPtr ci = do_QueryInterface(native, &rv); + if (NS_FAILED(rv)) { + return Throw(cx, rv); + } + + return WrapObject(cx, origObj, ci, &NS_GET_IID(nsIClassInfo), vp); + } + + // Lie, otherwise we need to check classinfo or QI + *vp = thisv; + return true; +} + +JSBool +ThrowingConstructor(JSContext* cx, unsigned argc, JS::Value* vp) +{ + return ThrowErrorMessage(cx, MSG_ILLEGAL_CONSTRUCTOR); +} + +bool +XrayResolveProperty(JSContext* cx, JSObject* wrapper, jsid id, + JSPropertyDescriptor* desc, + // And the things we need to determine the descriptor + Prefable* methods, + jsid* methodIds, + JSFunctionSpec* methodSpecs, + size_t methodCount, + Prefable* attributes, + jsid* attributeIds, + JSPropertySpec* attributeSpecs, + size_t attributeCount, + Prefable* constants, + jsid* constantIds, + ConstantSpec* constantSpecs, + size_t constantCount) +{ + for (size_t prefIdx = 0; prefIdx < methodCount; ++prefIdx) { + MOZ_ASSERT(methods[prefIdx].specs); + if (methods[prefIdx].enabled) { + // Set i to be the index into our full list of ids/specs that we're + // looking at now. + size_t i = methods[prefIdx].specs - methodSpecs; + for ( ; methodIds[i] != JSID_VOID; ++i) { + if (id == methodIds[i]) { + JSFunction *fun = JS_NewFunctionById(cx, methodSpecs[i].call.op, + methodSpecs[i].nargs, 0, + wrapper, id); + if (!fun) { + return false; + } + SET_JITINFO(fun, methodSpecs[i].call.info); + JSObject *funobj = JS_GetFunctionObject(fun); + desc->value.setObject(*funobj); + desc->attrs = methodSpecs[i].flags; + desc->obj = wrapper; + desc->setter = nullptr; + desc->getter = nullptr; + return true; + } + } + } + } + + for (size_t prefIdx = 0; prefIdx < attributeCount; ++prefIdx) { + MOZ_ASSERT(attributes[prefIdx].specs); + if (attributes[prefIdx].enabled) { + // Set i to be the index into our full list of ids/specs that we're + // looking at now. + size_t i = attributes[prefIdx].specs - attributeSpecs; + for ( ; attributeIds[i] != JSID_VOID; ++i) { + if (id == attributeIds[i]) { + // Because of centralization, we need to make sure we fault in the + // JitInfos as well. At present, until the JSAPI changes, the easiest + // way to do this is wrap them up as functions ourselves. + desc->attrs = attributeSpecs[i].flags & ~JSPROP_NATIVE_ACCESSORS; + // They all have getters, so we can just make it. + JSObject *global = JS_GetGlobalForObject(cx, wrapper); + JSFunction *fun = JS_NewFunction(cx, (JSNative)attributeSpecs[i].getter.op, + 0, 0, global, NULL); + if (!fun) + return false; + SET_JITINFO(fun, attributeSpecs[i].getter.info); + JSObject *funobj = JS_GetFunctionObject(fun); + desc->getter = js::CastAsJSPropertyOp(funobj); + desc->attrs |= JSPROP_GETTER; + if (attributeSpecs[i].setter.op) { + // We have a setter! Make it. + fun = JS_NewFunction(cx, (JSNative)attributeSpecs[i].setter.op, + 1, 0, global, NULL); + if (!fun) + return false; + SET_JITINFO(fun, attributeSpecs[i].setter.info); + funobj = JS_GetFunctionObject(fun); + desc->setter = js::CastAsJSStrictPropertyOp(funobj); + desc->attrs |= JSPROP_SETTER; + } else { + desc->setter = NULL; + } + desc->obj = wrapper; + return true; + } + } + } + } + + for (size_t prefIdx = 0; prefIdx < constantCount; ++prefIdx) { + MOZ_ASSERT(constants[prefIdx].specs); + if (constants[prefIdx].enabled) { + // Set i to be the index into our full list of ids/specs that we're + // looking at now. + size_t i = constants[prefIdx].specs - constantSpecs; + for ( ; constantIds[i] != JSID_VOID; ++i) { + if (id == constantIds[i]) { + desc->attrs = JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT; + desc->obj = wrapper; + desc->value = constantSpecs[i].value; + return true; + } + } + } + } + + return true; +} + +bool +XrayEnumerateProperties(JS::AutoIdVector& props, + Prefable* methods, + jsid* methodIds, + JSFunctionSpec* methodSpecs, + size_t methodCount, + Prefable* attributes, + jsid* attributeIds, + JSPropertySpec* attributeSpecs, + size_t attributeCount, + Prefable* constants, + jsid* constantIds, + ConstantSpec* constantSpecs, + size_t constantCount) +{ + for (size_t prefIdx = 0; prefIdx < methodCount; ++prefIdx) { + MOZ_ASSERT(methods[prefIdx].specs); + if (methods[prefIdx].enabled) { + // Set i to be the index into our full list of ids/specs that we're + // looking at now. + size_t i = methods[prefIdx].specs - methodSpecs; + for ( ; methodIds[i] != JSID_VOID; ++i) { + if ((methodSpecs[i].flags & JSPROP_ENUMERATE) && + !props.append(methodIds[i])) { + return false; + } + } + } + } + + for (size_t prefIdx = 0; prefIdx < attributeCount; ++prefIdx) { + MOZ_ASSERT(attributes[prefIdx].specs); + if (attributes[prefIdx].enabled) { + // Set i to be the index into our full list of ids/specs that we're + // looking at now. + size_t i = attributes[prefIdx].specs - attributeSpecs; + for ( ; attributeIds[i] != JSID_VOID; ++i) { + if ((attributeSpecs[i].flags & JSPROP_ENUMERATE) && + !props.append(attributeIds[i])) { + return false; + } + } + } + } + + for (size_t prefIdx = 0; prefIdx < constantCount; ++prefIdx) { + MOZ_ASSERT(constants[prefIdx].specs); + if (constants[prefIdx].enabled) { + // Set i to be the index into our full list of ids/specs that we're + // looking at now. + size_t i = constants[prefIdx].specs - constantSpecs; + for ( ; constantIds[i] != JSID_VOID; ++i) { + if (!props.append(constantIds[i])) { + return false; + } + } + } + } + + return true; +} + +bool +GetPropertyOnPrototype(JSContext* cx, JSObject* proxy, jsid id, bool* found, + JS::Value* vp) +{ + JSObject* proto; + if (!js::GetObjectProto(cx, proxy, &proto)) { + return false; + } + if (!proto) { + *found = false; + return true; + } + + JSBool hasProp; + if (!JS_HasPropertyById(cx, proto, id, &hasProp)) { + return false; + } + + *found = hasProp; + if (!hasProp || !vp) { + return true; + } + + return JS_ForwardGetPropertyTo(cx, proto, id, proxy, vp); +} + +bool +HasPropertyOnPrototype(JSContext* cx, JSObject* proxy, DOMProxyHandler* handler, + jsid id) +{ + Maybe ac; + if (xpc::WrapperFactory::IsXrayWrapper(proxy)) { + proxy = js::UnwrapObject(proxy); + ac.construct(cx, proxy); + } + MOZ_ASSERT(js::IsProxy(proxy) && js::GetProxyHandler(proxy) == handler); + + bool found; + // We ignore an error from GetPropertyOnPrototype. + return !GetPropertyOnPrototype(cx, proxy, id, &found, NULL) || found; +} + +} // namespace dom +} // namespace mozilla diff --git a/src/servo/dom/bindings/codegen/BindingUtils.h b/src/servo/dom/bindings/codegen/BindingUtils.h new file mode 100644 index 00000000000..ee9d6c3691c --- /dev/null +++ b/src/servo/dom/bindings/codegen/BindingUtils.h @@ -0,0 +1,1151 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/ +/* vim: set ts=2 sw=2 et tw=79: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef mozilla_dom_BindingUtils_h__ +#define mozilla_dom_BindingUtils_h__ + +#include "mozilla/dom/DOMJSClass.h" +#include "mozilla/dom/DOMJSProxyHandler.h" +#include "mozilla/dom/workers/Workers.h" +#include "mozilla/ErrorResult.h" + +#include "jsapi.h" +#include "jsfriendapi.h" +#include "jswrapper.h" + +#include "nsIXPConnect.h" +#include "qsObjectHelper.h" +#include "xpcpublic.h" +#include "nsTraceRefcnt.h" +#include "nsWrapperCacheInlines.h" +#include "mozilla/Likely.h" + +// nsGlobalWindow implements nsWrapperCache, but doesn't always use it. Don't +// try to use it without fixing that first. +class nsGlobalWindow; + +namespace mozilla { +namespace dom { + +enum ErrNum { +#define MSG_DEF(_name, _argc, _str) \ + _name, +#include "mozilla/dom/Errors.msg" +#undef MSG_DEF + Err_Limit +}; + +bool +ThrowErrorMessage(JSContext* aCx, const ErrNum aErrorNumber, ...); + +template +inline bool +Throw(JSContext* cx, nsresult rv) +{ + using mozilla::dom::workers::exceptions::ThrowDOMExceptionForNSResult; + + // XXX Introduce exception machinery. + if (mainThread) { + xpc::Throw(cx, rv); + } else { + if (!JS_IsExceptionPending(cx)) { + ThrowDOMExceptionForNSResult(cx, rv); + } + } + return false; +} + +template +inline bool +ThrowMethodFailedWithDetails(JSContext* cx, const ErrorResult& rv, + const char* /* ifaceName */, + const char* /* memberName */) +{ + return Throw(cx, rv.ErrorCode()); +} + +inline bool +IsDOMClass(const JSClass* clasp) +{ + return clasp->flags & JSCLASS_IS_DOMJSCLASS; +} + +inline bool +IsDOMClass(const js::Class* clasp) +{ + return IsDOMClass(Jsvalify(clasp)); +} + +// It's ok for eRegularDOMObject and eProxyDOMObject to be the same, but +// eNonDOMObject should always be different from the other two. This enum +// shouldn't be used to differentiate between non-proxy and proxy bindings. +enum DOMObjectSlot { + eNonDOMObject = -1, + eRegularDOMObject = DOM_OBJECT_SLOT, + eProxyDOMObject = DOM_PROXY_OBJECT_SLOT +}; + +template +inline T* +UnwrapDOMObject(JSObject* obj, DOMObjectSlot slot) +{ + MOZ_ASSERT(slot != eNonDOMObject, + "Don't pass non-DOM objects to this function"); + +#ifdef DEBUG + if (IsDOMClass(js::GetObjectClass(obj))) { + MOZ_ASSERT(slot == eRegularDOMObject); + } else { + MOZ_ASSERT(js::IsObjectProxyClass(js::GetObjectClass(obj)) || + js::IsFunctionProxyClass(js::GetObjectClass(obj))); + MOZ_ASSERT(js::GetProxyHandler(obj)->family() == ProxyFamily()); + MOZ_ASSERT(IsNewProxyBinding(js::GetProxyHandler(obj))); + MOZ_ASSERT(slot == eProxyDOMObject); + } +#endif + + JS::Value val = js::GetReservedSlot(obj, slot); + // XXXbz/khuey worker code tries to unwrap interface objects (which have + // nothing here). That needs to stop. + // XXX We don't null-check UnwrapObject's result; aren't we going to crash + // anyway? + if (val.isUndefined()) { + return NULL; + } + + return static_cast(val.toPrivate()); +} + +// Only use this with a new DOM binding object (either proxy or regular). +inline const DOMClass* +GetDOMClass(JSObject* obj) +{ + js::Class* clasp = js::GetObjectClass(obj); + if (IsDOMClass(clasp)) { + return &DOMJSClass::FromJSClass(clasp)->mClass; + } + + js::BaseProxyHandler* handler = js::GetProxyHandler(obj); + MOZ_ASSERT(handler->family() == ProxyFamily()); + MOZ_ASSERT(IsNewProxyBinding(handler)); + return &static_cast(handler)->mClass; +} + +inline DOMObjectSlot +GetDOMClass(JSObject* obj, const DOMClass*& result) +{ + js::Class* clasp = js::GetObjectClass(obj); + if (IsDOMClass(clasp)) { + result = &DOMJSClass::FromJSClass(clasp)->mClass; + return eRegularDOMObject; + } + + if (js::IsObjectProxyClass(clasp) || js::IsFunctionProxyClass(clasp)) { + js::BaseProxyHandler* handler = js::GetProxyHandler(obj); + if (handler->family() == ProxyFamily() && IsNewProxyBinding(handler)) { + result = &static_cast(handler)->mClass; + return eProxyDOMObject; + } + } + + return eNonDOMObject; +} + +inline bool +UnwrapDOMObjectToISupports(JSObject* obj, nsISupports*& result) +{ + const DOMClass* clasp; + DOMObjectSlot slot = GetDOMClass(obj, clasp); + if (slot == eNonDOMObject || !clasp->mDOMObjectIsISupports) { + return false; + } + + result = UnwrapDOMObject(obj, slot); + return true; +} + +inline bool +IsDOMObject(JSObject* obj) +{ + js::Class* clasp = js::GetObjectClass(obj); + return IsDOMClass(clasp) || + ((js::IsObjectProxyClass(clasp) || js::IsFunctionProxyClass(clasp)) && + (js::GetProxyHandler(obj)->family() == ProxyFamily() && + IsNewProxyBinding(js::GetProxyHandler(obj)))); +} + +// Some callers don't want to set an exception when unwrapping fails +// (for example, overload resolution uses unwrapping to tell what sort +// of thing it's looking at). +// U must be something that a T* can be assigned to (e.g. T* or an nsRefPtr). +template +inline nsresult +UnwrapObject(JSContext* cx, JSObject* obj, U& value) +{ + /* First check to see whether we have a DOM object */ + const DOMClass* domClass; + DOMObjectSlot slot = GetDOMClass(obj, domClass); + if (slot == eNonDOMObject) { + /* Maybe we have a security wrapper or outer window? */ + if (!js::IsWrapper(obj)) { + /* Not a DOM object, not a wrapper, just bail */ + return NS_ERROR_XPC_BAD_CONVERT_JS; + } + + obj = xpc::Unwrap(cx, obj, false); + if (!obj) { + return NS_ERROR_XPC_SECURITY_MANAGER_VETO; + } + MOZ_ASSERT(!js::IsWrapper(obj)); + slot = GetDOMClass(obj, domClass); + if (slot == eNonDOMObject) { + /* We don't have a DOM object */ + return NS_ERROR_XPC_BAD_CONVERT_JS; + } + } + + /* This object is a DOM object. Double-check that it is safely + castable to T by checking whether it claims to inherit from the + class identified by protoID. */ + if (domClass->mInterfaceChain[PrototypeTraits::Depth] == + PrototypeID) { + value = UnwrapDOMObject(obj, slot); + return NS_OK; + } + + /* It's the wrong sort of DOM object */ + return NS_ERROR_XPC_BAD_CONVERT_JS; +} + +inline bool +IsArrayLike(JSContext* cx, JSObject* obj) +{ + MOZ_ASSERT(obj); + // For simplicity, check for security wrappers up front. In case we + // have a security wrapper, don't forget to enter the compartment of + // the underlying object after unwrapping. + Maybe ac; + if (js::IsWrapper(obj)) { + obj = xpc::Unwrap(cx, obj, false); + if (!obj) { + // Let's say it's not + return false; + } + + ac.construct(cx, obj); + } + + // XXXbz need to detect platform objects (including listbinding + // ones) with indexGetters here! + return JS_IsArrayObject(cx, obj) || JS_IsTypedArrayObject(obj, cx); +} + +inline bool +IsPlatformObject(JSContext* cx, JSObject* obj) +{ + // XXXbz Should be treating list-binding objects as platform objects + // too? The one consumer so far wants non-array-like platform + // objects, so listbindings that have an indexGetter should test + // false from here. Maybe this function should have a different + // name? + MOZ_ASSERT(obj); + // Fast-path the common case + JSClass* clasp = js::GetObjectJSClass(obj); + if (IsDOMClass(clasp)) { + return true; + } + // Now for simplicity check for security wrappers before anything else + if (js::IsWrapper(obj)) { + obj = xpc::Unwrap(cx, obj, false); + if (!obj) { + // Let's say it's not + return false; + } + clasp = js::GetObjectJSClass(obj); + } + return IS_WRAPPER_CLASS(js::Valueify(clasp)) || IsDOMClass(clasp) || + JS_IsArrayBufferObject(obj, cx); +} + +// U must be something that a T* can be assigned to (e.g. T* or an nsRefPtr). +template +inline nsresult +UnwrapObject(JSContext* cx, JSObject* obj, U& value) +{ + return UnwrapObject( + PrototypeIDMap::PrototypeID), T>(cx, obj, value); +} + +const size_t kProtoOrIfaceCacheCount = + prototypes::id::_ID_Count + constructors::id::_ID_Count; + +inline void +AllocateProtoOrIfaceCache(JSObject* obj) +{ + MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL); + MOZ_ASSERT(js::GetReservedSlot(obj, DOM_PROTOTYPE_SLOT).isUndefined()); + + // Important: The () at the end ensure zero-initialization + JSObject** protoOrIfaceArray = new JSObject*[kProtoOrIfaceCacheCount](); + + js::SetReservedSlot(obj, DOM_PROTOTYPE_SLOT, + JS::PrivateValue(protoOrIfaceArray)); +} + +inline void +TraceProtoOrIfaceCache(JSTracer* trc, JSObject* obj) +{ + MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL); + + if (!HasProtoOrIfaceArray(obj)) + return; + JSObject** protoOrIfaceArray = GetProtoOrIfaceArray(obj); + for (size_t i = 0; i < kProtoOrIfaceCacheCount; ++i) { + JSObject* proto = protoOrIfaceArray[i]; + if (proto) { + JS_CALL_OBJECT_TRACER(trc, proto, "protoOrIfaceArray[i]"); + } + } +} + +inline void +DestroyProtoOrIfaceCache(JSObject* obj) +{ + MOZ_ASSERT(js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL); + + JSObject** protoOrIfaceArray = GetProtoOrIfaceArray(obj); + + delete [] protoOrIfaceArray; +} + +struct ConstantSpec +{ + const char* name; + JS::Value value; +}; + +/** + * Add constants to an object. + */ +bool +DefineConstants(JSContext* cx, JSObject* obj, ConstantSpec* cs); + +template +struct Prefable { + // A boolean indicating whether this set of specs is enabled + bool enabled; + // Array of specs, terminated in whatever way is customary for T. + // Null to indicate a end-of-array for Prefable, when such an + // indicator is needed. + T* specs; +}; + +/* + * Create a DOM interface object (if constructorClass is non-null) and/or a + * DOM interface prototype object (if protoClass is non-null). + * + * global is used as the parent of the interface object and the interface + * prototype object + * receiver is the object on which we need to define the interface object as a + * property + * protoProto is the prototype to use for the interface prototype object. + * protoClass is the JSClass to use for the interface prototype object. + * This is null if we should not create an interface prototype + * object. + * constructorClass is the JSClass to use for the interface object. + * This is null if we should not create an interface object or + * if it should be a function object. + * constructor is the JSNative to use as a constructor. If this is non-null, it + * should be used as a JSNative to back the interface object, which + * should be a Function. If this is null, then we should create an + * object of constructorClass, unless that's also null, in which + * case we should not create an interface object at all. + * ctorNargs is the length of the constructor function; 0 if no constructor + * instanceClass is the JSClass of instance objects for this class. This can + * be null if this is not a concrete proto. + * methods and properties are to be defined on the interface prototype object; + * these arguments are allowed to be null if there are no + * methods or properties respectively. + * constants are to be defined on the interface object and on the interface + * prototype object; allowed to be null if there are no constants. + * staticMethods are to be defined on the interface object; allowed to be null + * if there are no static methods. + * + * At least one of protoClass and constructorClass should be non-null. + * If constructorClass is non-null, the resulting interface object will be + * defined on the given global with property name |name|, which must also be + * non-null. + * + * returns the interface prototype object if protoClass is non-null, else it + * returns the interface object. + */ +JSObject* +CreateInterfaceObjects(JSContext* cx, JSObject* global, JSObject* receiver, + JSObject* protoProto, JSClass* protoClass, + JSClass* constructorClass, JSNative constructor, + unsigned ctorNargs, const DOMClass* domClass, + Prefable* methods, + Prefable* properties, + Prefable* constants, + Prefable* staticMethods, const char* name); + +template +inline bool +WrapNewBindingObject(JSContext* cx, JSObject* scope, T* value, JS::Value* vp) +{ + JSObject* obj = value->GetWrapper(); + if (obj && js::GetObjectCompartment(obj) == js::GetObjectCompartment(scope)) { + *vp = JS::ObjectValue(*obj); + return true; + } + + if (!obj) { + bool triedToWrap; + obj = value->WrapObject(cx, scope, &triedToWrap); + if (!obj) { + // At this point, obj is null, so just return false. We could + // try to communicate triedToWrap to the caller, but in practice + // callers seem to be testing JS_IsExceptionPending(cx) to + // figure out whether WrapObject() threw instead. + return false; + } + } + + // When called via XrayWrapper, we end up here while running in the + // chrome compartment. But the obj we have would be created in + // whatever the content compartment is. So at this point we need to + // make sure it's correctly wrapped for the compartment of |scope|. + // cx should already be in the compartment of |scope| here. + MOZ_ASSERT(js::IsObjectInContextCompartment(scope, cx)); + *vp = JS::ObjectValue(*obj); + return JS_WrapValue(cx, vp); +} + +// Helper for smart pointers (nsAutoPtr/nsRefPtr/nsCOMPtr). +template