michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- michael@0: * vim: set ts=8 sts=4 et sw=4 tw=99: michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* michael@0: * JavaScript API. michael@0: */ michael@0: michael@0: #include "jsapi.h" michael@0: michael@0: #include "mozilla/FloatingPoint.h" michael@0: #include "mozilla/PodOperations.h" michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include "jsarray.h" michael@0: #include "jsatom.h" michael@0: #include "jsbool.h" michael@0: #include "jscntxt.h" michael@0: #include "jsdate.h" michael@0: #include "jsexn.h" michael@0: #include "jsfun.h" michael@0: #include "jsgc.h" michael@0: #include "jsiter.h" michael@0: #include "jslock.h" michael@0: #include "jsmath.h" michael@0: #include "jsnum.h" michael@0: #include "jsobj.h" michael@0: #include "json.h" michael@0: #include "jsprf.h" michael@0: #include "jsproxy.h" michael@0: #include "jsscript.h" michael@0: #include "jsstr.h" michael@0: #include "jstypes.h" michael@0: #include "jsutil.h" michael@0: #include "jswatchpoint.h" michael@0: #include "jsweakmap.h" michael@0: #ifdef JS_THREADSAFE michael@0: #include "jsworkers.h" michael@0: #endif michael@0: #include "jswrapper.h" michael@0: #include "prmjtime.h" michael@0: michael@0: #if ENABLE_YARR_JIT michael@0: #include "assembler/jit/ExecutableAllocator.h" michael@0: #endif michael@0: #include "builtin/Eval.h" michael@0: #include "builtin/Intl.h" michael@0: #include "builtin/MapObject.h" michael@0: #include "builtin/RegExp.h" michael@0: #ifdef ENABLE_BINARYDATA michael@0: #include "builtin/SIMD.h" michael@0: #include "builtin/TypedObject.h" michael@0: #endif michael@0: #include "frontend/BytecodeCompiler.h" michael@0: #include "frontend/FullParseHandler.h" // for JS_BufferIsCompileableUnit michael@0: #include "frontend/Parser.h" // for JS_BufferIsCompileableUnit michael@0: #include "gc/Marking.h" michael@0: #include "jit/AsmJSLink.h" michael@0: #include "jit/JitCommon.h" michael@0: #include "js/CharacterEncoding.h" michael@0: #include "js/SliceBudget.h" michael@0: #include "js/StructuredClone.h" michael@0: #if ENABLE_INTL_API michael@0: #include "unicode/uclean.h" michael@0: #include "unicode/utypes.h" michael@0: #endif // ENABLE_INTL_API michael@0: #include "vm/DateObject.h" michael@0: #include "vm/Debugger.h" michael@0: #include "vm/ErrorObject.h" michael@0: #include "vm/Interpreter.h" michael@0: #include "vm/NumericConversions.h" michael@0: #include "vm/RegExpStatics.h" michael@0: #include "vm/Runtime.h" michael@0: #include "vm/Shape.h" michael@0: #include "vm/SharedArrayObject.h" michael@0: #include "vm/StopIterationObject.h" michael@0: #include "vm/StringBuffer.h" michael@0: #include "vm/TypedArrayObject.h" michael@0: #include "vm/WeakMapObject.h" michael@0: #include "vm/WrapperObject.h" michael@0: #include "vm/Xdr.h" michael@0: #include "yarr/BumpPointerAllocator.h" michael@0: michael@0: #include "jsatominlines.h" michael@0: #include "jsfuninlines.h" michael@0: #include "jsinferinlines.h" michael@0: #include "jsscriptinlines.h" michael@0: michael@0: #include "vm/Interpreter-inl.h" michael@0: #include "vm/ObjectImpl-inl.h" michael@0: #include "vm/String-inl.h" michael@0: michael@0: using namespace js; michael@0: using namespace js::gc; michael@0: using namespace js::types; michael@0: michael@0: using mozilla::Maybe; michael@0: using mozilla::PodCopy; michael@0: using mozilla::PodZero; michael@0: michael@0: using js::frontend::Parser; michael@0: michael@0: #ifdef HAVE_VA_LIST_AS_ARRAY michael@0: #define JS_ADDRESSOF_VA_LIST(ap) ((va_list *)(ap)) michael@0: #else michael@0: #define JS_ADDRESSOF_VA_LIST(ap) (&(ap)) michael@0: #endif michael@0: michael@0: /* Make sure that jschar is two bytes unsigned integer */ michael@0: JS_STATIC_ASSERT((jschar)-1 > 0); michael@0: JS_STATIC_ASSERT(sizeof(jschar) == 2); michael@0: michael@0: JS_PUBLIC_API(int64_t) michael@0: JS_Now() michael@0: { michael@0: return PRMJ_Now(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(jsval) michael@0: JS_GetNaNValue(JSContext *cx) michael@0: { michael@0: return cx->runtime()->NaNValue; michael@0: } michael@0: michael@0: JS_PUBLIC_API(jsval) michael@0: JS_GetNegativeInfinityValue(JSContext *cx) michael@0: { michael@0: return cx->runtime()->negativeInfinityValue; michael@0: } michael@0: michael@0: JS_PUBLIC_API(jsval) michael@0: JS_GetPositiveInfinityValue(JSContext *cx) michael@0: { michael@0: return cx->runtime()->positiveInfinityValue; michael@0: } michael@0: michael@0: JS_PUBLIC_API(jsval) michael@0: JS_GetEmptyStringValue(JSContext *cx) michael@0: { michael@0: return STRING_TO_JSVAL(cx->runtime()->emptyString); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_GetEmptyString(JSRuntime *rt) michael@0: { michael@0: JS_ASSERT(rt->hasContexts()); michael@0: return rt->emptyString; michael@0: } michael@0: michael@0: namespace js { michael@0: michael@0: void michael@0: AssertHeapIsIdle(JSRuntime *rt) michael@0: { michael@0: JS_ASSERT(rt->heapState == js::Idle); michael@0: } michael@0: michael@0: void michael@0: AssertHeapIsIdle(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdle(cx->runtime()); michael@0: } michael@0: michael@0: } michael@0: michael@0: static void michael@0: AssertHeapIsIdleOrIterating(JSRuntime *rt) michael@0: { michael@0: JS_ASSERT(!rt->isHeapCollecting()); michael@0: } michael@0: michael@0: static void michael@0: AssertHeapIsIdleOrIterating(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdleOrIterating(cx->runtime()); michael@0: } michael@0: michael@0: static void michael@0: AssertHeapIsIdleOrStringIsFlat(JSContext *cx, JSString *str) michael@0: { michael@0: /* michael@0: * We allow some functions to be called during a GC as long as the argument michael@0: * is a flat string, since that will not cause allocation. michael@0: */ michael@0: JS_ASSERT_IF(cx->runtime()->isHeapBusy(), str->isFlat()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ConvertArguments(JSContext *cx, const CallArgs &args, const char *format, ...) michael@0: { michael@0: va_list ap; michael@0: bool ok; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: michael@0: va_start(ap, format); michael@0: ok = JS_ConvertArgumentsVA(cx, args, format, ap); michael@0: va_end(ap); michael@0: return ok; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ConvertArgumentsVA(JSContext *cx, const CallArgs &args, const char *format, va_list ap) michael@0: { michael@0: unsigned index = 0; michael@0: bool required; michael@0: char c; michael@0: double d; michael@0: JSString *str; michael@0: RootedObject obj(cx); michael@0: RootedValue val(cx); michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, args); michael@0: required = true; michael@0: while ((c = *format++) != '\0') { michael@0: if (isspace(c)) michael@0: continue; michael@0: if (c == '/') { michael@0: required = false; michael@0: continue; michael@0: } michael@0: if (index == args.length()) { michael@0: if (required) { michael@0: if (JSFunction *fun = ReportIfNotFunction(cx, args.calleev())) { michael@0: char numBuf[12]; michael@0: JS_snprintf(numBuf, sizeof numBuf, "%u", args.length()); michael@0: JSAutoByteString funNameBytes; michael@0: if (const char *name = GetFunctionNameBytes(cx, fun, &funNameBytes)) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, michael@0: JSMSG_MORE_ARGS_NEEDED, michael@0: name, numBuf, (args.length() == 1) ? "" : "s"); michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: break; michael@0: } michael@0: MutableHandleValue arg = args[index++]; michael@0: switch (c) { michael@0: case 'b': michael@0: *va_arg(ap, bool *) = ToBoolean(arg); michael@0: break; michael@0: case 'c': michael@0: if (!ToUint16(cx, arg, va_arg(ap, uint16_t *))) michael@0: return false; michael@0: break; michael@0: case 'i': michael@0: case 'j': // "j" was broken, you should not use it. michael@0: if (!ToInt32(cx, arg, va_arg(ap, int32_t *))) michael@0: return false; michael@0: break; michael@0: case 'u': michael@0: if (!ToUint32(cx, arg, va_arg(ap, uint32_t *))) michael@0: return false; michael@0: break; michael@0: case 'd': michael@0: if (!ToNumber(cx, arg, va_arg(ap, double *))) michael@0: return false; michael@0: break; michael@0: case 'I': michael@0: if (!ToNumber(cx, arg, &d)) michael@0: return false; michael@0: *va_arg(ap, double *) = ToInteger(d); michael@0: break; michael@0: case 'S': michael@0: case 'W': michael@0: str = ToString(cx, arg); michael@0: if (!str) michael@0: return false; michael@0: arg.setString(str); michael@0: if (c == 'W') { michael@0: JSFlatString *flat = str->ensureFlat(cx); michael@0: if (!flat) michael@0: return false; michael@0: *va_arg(ap, const jschar **) = flat->chars(); michael@0: } else { michael@0: *va_arg(ap, JSString **) = str; michael@0: } michael@0: break; michael@0: case 'o': michael@0: if (arg.isNullOrUndefined()) { michael@0: obj = nullptr; michael@0: } else { michael@0: obj = ToObject(cx, arg); michael@0: if (!obj) michael@0: return false; michael@0: } michael@0: arg.setObjectOrNull(obj); michael@0: *va_arg(ap, JSObject **) = obj; michael@0: break; michael@0: case 'f': michael@0: obj = ReportIfNotFunction(cx, arg); michael@0: if (!obj) michael@0: return false; michael@0: arg.setObject(*obj); michael@0: *va_arg(ap, JSFunction **) = &obj->as(); michael@0: break; michael@0: case 'v': michael@0: *va_arg(ap, jsval *) = arg; michael@0: break; michael@0: case '*': michael@0: break; michael@0: default: michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_CHAR, format); michael@0: return false; michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ConvertValue(JSContext *cx, HandleValue value, JSType type, MutableHandleValue vp) michael@0: { michael@0: bool ok; michael@0: RootedObject obj(cx); michael@0: JSString *str; michael@0: double d; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: switch (type) { michael@0: case JSTYPE_VOID: michael@0: vp.setUndefined(); michael@0: ok = true; michael@0: break; michael@0: case JSTYPE_OBJECT: michael@0: if (value.isNullOrUndefined()) { michael@0: obj.set(nullptr); michael@0: } else { michael@0: obj = ToObject(cx, value); michael@0: if (!obj) michael@0: return false; michael@0: } michael@0: ok = true; michael@0: break; michael@0: case JSTYPE_FUNCTION: michael@0: vp.set(value); michael@0: obj = ReportIfNotFunction(cx, vp); michael@0: ok = (obj != nullptr); michael@0: break; michael@0: case JSTYPE_STRING: michael@0: str = ToString(cx, value); michael@0: ok = (str != nullptr); michael@0: if (ok) michael@0: vp.setString(str); michael@0: break; michael@0: case JSTYPE_NUMBER: michael@0: ok = ToNumber(cx, value, &d); michael@0: if (ok) michael@0: vp.setDouble(d); michael@0: break; michael@0: case JSTYPE_BOOLEAN: michael@0: vp.setBoolean(ToBoolean(value)); michael@0: return true; michael@0: default: { michael@0: char numBuf[12]; michael@0: JS_snprintf(numBuf, sizeof numBuf, "%d", (int)type); michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_TYPE, numBuf); michael@0: ok = false; michael@0: break; michael@0: } michael@0: } michael@0: return ok; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ValueToObject(JSContext *cx, HandleValue value, MutableHandleObject objp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: if (value.isNullOrUndefined()) { michael@0: objp.set(nullptr); michael@0: return true; michael@0: } michael@0: JSObject *obj = ToObject(cx, value); michael@0: if (!obj) michael@0: return false; michael@0: objp.set(obj); michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS_ValueToFunction(JSContext *cx, HandleValue value) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: return ReportIfNotFunction(cx, value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS_ValueToConstructor(JSContext *cx, HandleValue value) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: return ReportIfNotFunction(cx, value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_ValueToSource(JSContext *cx, HandleValue value) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: return ValueToSource(cx, value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DoubleIsInt32(double d, int32_t *ip) michael@0: { michael@0: return mozilla::NumberIsInt32(d, ip); michael@0: } michael@0: michael@0: JS_PUBLIC_API(int32_t) michael@0: JS_DoubleToInt32(double d) michael@0: { michael@0: return ToInt32(d); michael@0: } michael@0: michael@0: JS_PUBLIC_API(uint32_t) michael@0: JS_DoubleToUint32(double d) michael@0: { michael@0: return ToUint32(d); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSType) michael@0: JS_TypeOfValue(JSContext *cx, HandleValue value) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: return TypeOfValue(value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const char *) michael@0: JS_GetTypeName(JSContext *cx, JSType type) michael@0: { michael@0: if ((unsigned)type >= (unsigned)JSTYPE_LIMIT) michael@0: return nullptr; michael@0: return TypeStrings[type]; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_StrictlyEqual(JSContext *cx, jsval value1, jsval value2, bool *equal) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value1, value2); michael@0: bool eq; michael@0: if (!StrictlyEqual(cx, value1, value2, &eq)) michael@0: return false; michael@0: *equal = eq; michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_LooselyEqual(JSContext *cx, HandleValue value1, HandleValue value2, bool *equal) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value1, value2); michael@0: JS_ASSERT(equal); michael@0: return LooselyEqual(cx, value1, value2, equal); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SameValue(JSContext *cx, jsval value1, jsval value2, bool *same) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value1, value2); michael@0: bool s; michael@0: if (!SameValue(cx, value1, value2, &s)) michael@0: return false; michael@0: *same = s; michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsBuiltinEvalFunction(JSFunction *fun) michael@0: { michael@0: return IsAnyBuiltinEval(fun); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsBuiltinFunctionConstructor(JSFunction *fun) michael@0: { michael@0: return fun->isBuiltinFunctionConstructor(); michael@0: } michael@0: michael@0: /************************************************************************/ michael@0: michael@0: /* michael@0: * SpiderMonkey's initialization status is tracked here, and it controls things michael@0: * that should happen only once across all runtimes. It's an API requirement michael@0: * that JS_Init (and JS_ShutDown, if called) be called in a thread-aware michael@0: * manner, so this variable doesn't need to be atomic. michael@0: * michael@0: * The only reason at present for the restriction that you can't call michael@0: * JS_Init/stuff/JS_ShutDown multiple times is the Windows PRMJ NowInit michael@0: * initialization code, which uses PR_CallOnce to initialize the PRMJ_Now michael@0: * subsystem. (For reinitialization to be permitted, we'd need to "reset" the michael@0: * called-once status -- doable, but more trouble than it's worth now.) michael@0: * Initializing that subsystem from JS_Init eliminates the problem, but michael@0: * initialization can take a comparatively long time (15ms or so), so we michael@0: * really don't want to do it in JS_Init, and we really do want to do it only michael@0: * when PRMJ_Now is eventually called. michael@0: */ michael@0: enum InitState { Uninitialized, Running, ShutDown }; michael@0: static InitState jsInitState = Uninitialized; michael@0: michael@0: #ifdef DEBUG michael@0: static void michael@0: CheckMessageNumbering() michael@0: { michael@0: // Assert that the numbers associated with the error names in js.msg are michael@0: // monotonically increasing. It's not a compile-time check, but it's michael@0: // better than nothing. michael@0: int errorNumber = 0; michael@0: # define MSG_DEF(name, number, count, exception, format) \ michael@0: JS_ASSERT(name == errorNumber++); michael@0: # include "js.msg" michael@0: # undef MSG_DEF michael@0: } michael@0: michael@0: static unsigned michael@0: MessageParameterCount(const char *format) michael@0: { michael@0: unsigned numfmtspecs = 0; michael@0: for (const char *fmt = format; *fmt != '\0'; fmt++) { michael@0: if (*fmt == '{' && isdigit(fmt[1])) michael@0: ++numfmtspecs; michael@0: } michael@0: return numfmtspecs; michael@0: } michael@0: michael@0: static void michael@0: CheckMessageParameterCounts() michael@0: { michael@0: // Assert that each message format has the correct number of braced michael@0: // parameters. michael@0: # define MSG_DEF(name, number, count, exception, format) \ michael@0: JS_BEGIN_MACRO \ michael@0: JS_ASSERT(MessageParameterCount(format) == count); \ michael@0: JS_END_MACRO; michael@0: # include "js.msg" michael@0: # undef MSG_DEF michael@0: } michael@0: #endif /* DEBUG */ michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_Init(void) michael@0: { michael@0: MOZ_ASSERT(jsInitState == Uninitialized, michael@0: "must call JS_Init once before any JSAPI operation except " michael@0: "JS_SetICUMemoryFunctions"); michael@0: MOZ_ASSERT(!JSRuntime::hasLiveRuntimes(), michael@0: "how do we have live runtimes before JS_Init?"); michael@0: michael@0: #ifdef DEBUG michael@0: CheckMessageNumbering(); michael@0: CheckMessageParameterCounts(); michael@0: #endif michael@0: michael@0: using js::TlsPerThreadData; michael@0: if (!TlsPerThreadData.initialized() && !TlsPerThreadData.init()) michael@0: return false; michael@0: michael@0: #if defined(JS_ION) michael@0: if (!jit::InitializeIon()) michael@0: return false; michael@0: #endif michael@0: michael@0: if (!ForkJoinContext::initialize()) michael@0: return false; michael@0: michael@0: #if EXPOSE_INTL_API michael@0: UErrorCode err = U_ZERO_ERROR; michael@0: u_init(&err); michael@0: if (U_FAILURE(err)) michael@0: return false; michael@0: #endif // EXPOSE_INTL_API michael@0: michael@0: jsInitState = Running; michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ShutDown(void) michael@0: { michael@0: MOZ_ASSERT(jsInitState == Running, michael@0: "JS_ShutDown must only be called after JS_Init and can't race with it"); michael@0: #ifdef DEBUG michael@0: if (JSRuntime::hasLiveRuntimes()) { michael@0: // Gecko is too buggy to assert this just yet. michael@0: fprintf(stderr, michael@0: "WARNING: YOU ARE LEAKING THE WORLD (at least one JSRuntime " michael@0: "and everything alive inside it, that is) AT JS_ShutDown " michael@0: "TIME. FIX THIS!\n"); michael@0: } michael@0: #endif michael@0: michael@0: #ifdef JS_THREADSAFE michael@0: WorkerThreadState().finish(); michael@0: #endif michael@0: michael@0: PRMJ_NowShutdown(); michael@0: michael@0: #if EXPOSE_INTL_API michael@0: u_cleanup(); michael@0: #endif // EXPOSE_INTL_API michael@0: michael@0: jsInitState = ShutDown; michael@0: } michael@0: michael@0: #ifdef DEBUG michael@0: JS_FRIEND_API(bool) michael@0: JS::isGCEnabled() michael@0: { michael@0: return !TlsPerThreadData.get()->suppressGC; michael@0: } michael@0: #else michael@0: JS_FRIEND_API(bool) JS::isGCEnabled() { return true; } michael@0: #endif michael@0: michael@0: JS_PUBLIC_API(JSRuntime *) michael@0: JS_NewRuntime(uint32_t maxbytes, JSUseHelperThreads useHelperThreads, JSRuntime *parentRuntime) michael@0: { michael@0: MOZ_ASSERT(jsInitState == Running, michael@0: "must call JS_Init prior to creating any JSRuntimes"); michael@0: michael@0: // Any parent runtime should be the topmost parent. This assert michael@0: // isn't required for correctness, but ensuring that the parent michael@0: // runtime is not destroyed before this one is more easily done michael@0: // for the main runtime in the process. michael@0: JS_ASSERT_IF(parentRuntime, !parentRuntime->parentRuntime); michael@0: michael@0: JSRuntime *rt = js_new(parentRuntime, useHelperThreads); michael@0: if (!rt) michael@0: return nullptr; michael@0: michael@0: if (!rt->init(maxbytes)) { michael@0: JS_DestroyRuntime(rt); michael@0: return nullptr; michael@0: } michael@0: michael@0: return rt; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_DestroyRuntime(JSRuntime *rt) michael@0: { michael@0: js_delete(rt); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetICUMemoryFunctions(JS_ICUAllocFn allocFn, JS_ICUReallocFn reallocFn, JS_ICUFreeFn freeFn) michael@0: { michael@0: MOZ_ASSERT(jsInitState == Uninitialized, michael@0: "must call JS_SetICUMemoryFunctions before any other JSAPI " michael@0: "operation (including JS_Init)"); michael@0: michael@0: #if EXPOSE_INTL_API michael@0: UErrorCode status = U_ZERO_ERROR; michael@0: u_setMemoryFunctions(/* context = */ nullptr, allocFn, reallocFn, freeFn, &status); michael@0: return U_SUCCESS(status); michael@0: #else michael@0: return true; michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_GetRuntimePrivate(JSRuntime *rt) michael@0: { michael@0: return rt->data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetRuntimePrivate(JSRuntime *rt, void *data) michael@0: { michael@0: rt->data = data; michael@0: } michael@0: michael@0: #ifdef JS_THREADSAFE michael@0: static void michael@0: StartRequest(JSContext *cx) michael@0: { michael@0: JSRuntime *rt = cx->runtime(); michael@0: JS_ASSERT(CurrentThreadCanAccessRuntime(rt)); michael@0: michael@0: if (rt->requestDepth) { michael@0: rt->requestDepth++; michael@0: } else { michael@0: /* Indicate that a request is running. */ michael@0: rt->requestDepth = 1; michael@0: rt->triggerActivityCallback(true); michael@0: } michael@0: } michael@0: michael@0: static void michael@0: StopRequest(JSContext *cx) michael@0: { michael@0: JSRuntime *rt = cx->runtime(); michael@0: JS_ASSERT(CurrentThreadCanAccessRuntime(rt)); michael@0: michael@0: JS_ASSERT(rt->requestDepth != 0); michael@0: if (rt->requestDepth != 1) { michael@0: rt->requestDepth--; michael@0: } else { michael@0: rt->conservativeGC.updateForRequestEnd(); michael@0: rt->requestDepth = 0; michael@0: rt->triggerActivityCallback(false); michael@0: } michael@0: } michael@0: #endif /* JS_THREADSAFE */ michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_BeginRequest(JSContext *cx) michael@0: { michael@0: #ifdef JS_THREADSAFE michael@0: cx->outstandingRequests++; michael@0: StartRequest(cx); michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_EndRequest(JSContext *cx) michael@0: { michael@0: #ifdef JS_THREADSAFE michael@0: JS_ASSERT(cx->outstandingRequests != 0); michael@0: cx->outstandingRequests--; michael@0: StopRequest(cx); michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsInRequest(JSRuntime *rt) michael@0: { michael@0: #ifdef JS_THREADSAFE michael@0: JS_ASSERT(CurrentThreadCanAccessRuntime(rt)); michael@0: return rt->requestDepth != 0; michael@0: #else michael@0: return false; michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetContextCallback(JSRuntime *rt, JSContextCallback cxCallback, void *data) michael@0: { michael@0: rt->cxCallback = cxCallback; michael@0: rt->cxCallbackData = data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSContext *) michael@0: JS_NewContext(JSRuntime *rt, size_t stackChunkSize) michael@0: { michael@0: return NewContext(rt, stackChunkSize); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_DestroyContext(JSContext *cx) michael@0: { michael@0: JS_ASSERT(!cx->compartment()); michael@0: DestroyContext(cx, DCM_FORCE_GC); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_DestroyContextNoGC(JSContext *cx) michael@0: { michael@0: JS_ASSERT(!cx->compartment()); michael@0: DestroyContext(cx, DCM_NO_GC); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_GetContextPrivate(JSContext *cx) michael@0: { michael@0: return cx->data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetContextPrivate(JSContext *cx, void *data) michael@0: { michael@0: cx->data = data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_GetSecondContextPrivate(JSContext *cx) michael@0: { michael@0: return cx->data2; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetSecondContextPrivate(JSContext *cx, void *data) michael@0: { michael@0: cx->data2 = data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSRuntime *) michael@0: JS_GetRuntime(JSContext *cx) michael@0: { michael@0: return cx->runtime(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSRuntime *) michael@0: JS_GetParentRuntime(JSContext *cx) michael@0: { michael@0: JSRuntime *rt = cx->runtime(); michael@0: return rt->parentRuntime ? rt->parentRuntime : rt; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSContext *) michael@0: JS_ContextIterator(JSRuntime *rt, JSContext **iterp) michael@0: { michael@0: JSContext *cx = *iterp; michael@0: cx = cx ? cx->getNext() : rt->contextList.getFirst(); michael@0: *iterp = cx; michael@0: return cx; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSVersion) michael@0: JS_GetVersion(JSContext *cx) michael@0: { michael@0: return VersionNumber(cx->findVersion()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetVersionForCompartment(JSCompartment *compartment, JSVersion version) michael@0: { michael@0: compartment->options().setVersion(version); michael@0: } michael@0: michael@0: static const struct v2smap { michael@0: JSVersion version; michael@0: const char *string; michael@0: } v2smap[] = { michael@0: {JSVERSION_ECMA_3, "ECMAv3"}, michael@0: {JSVERSION_1_6, "1.6"}, michael@0: {JSVERSION_1_7, "1.7"}, michael@0: {JSVERSION_1_8, "1.8"}, michael@0: {JSVERSION_ECMA_5, "ECMAv5"}, michael@0: {JSVERSION_DEFAULT, js_default_str}, michael@0: {JSVERSION_DEFAULT, "1.0"}, michael@0: {JSVERSION_DEFAULT, "1.1"}, michael@0: {JSVERSION_DEFAULT, "1.2"}, michael@0: {JSVERSION_DEFAULT, "1.3"}, michael@0: {JSVERSION_DEFAULT, "1.4"}, michael@0: {JSVERSION_DEFAULT, "1.5"}, michael@0: {JSVERSION_UNKNOWN, nullptr}, /* must be last, nullptr is sentinel */ michael@0: }; michael@0: michael@0: JS_PUBLIC_API(const char *) michael@0: JS_VersionToString(JSVersion version) michael@0: { michael@0: int i; michael@0: michael@0: for (i = 0; v2smap[i].string; i++) michael@0: if (v2smap[i].version == version) michael@0: return v2smap[i].string; michael@0: return "unknown"; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSVersion) michael@0: JS_StringToVersion(const char *string) michael@0: { michael@0: int i; michael@0: michael@0: for (i = 0; v2smap[i].string; i++) michael@0: if (strcmp(v2smap[i].string, string) == 0) michael@0: return v2smap[i].version; michael@0: return JSVERSION_UNKNOWN; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JS::RuntimeOptions &) michael@0: JS::RuntimeOptionsRef(JSRuntime *rt) michael@0: { michael@0: return rt->options(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JS::RuntimeOptions &) michael@0: JS::RuntimeOptionsRef(JSContext *cx) michael@0: { michael@0: return cx->runtime()->options(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JS::ContextOptions &) michael@0: JS::ContextOptionsRef(JSContext *cx) michael@0: { michael@0: return cx->options(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const char *) michael@0: JS_GetImplementationVersion(void) michael@0: { michael@0: return "JavaScript-C" MOZILLA_VERSION; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetDestroyCompartmentCallback(JSRuntime *rt, JSDestroyCompartmentCallback callback) michael@0: { michael@0: rt->destroyCompartmentCallback = callback; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetDestroyZoneCallback(JSRuntime *rt, JSZoneCallback callback) michael@0: { michael@0: rt->destroyZoneCallback = callback; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetSweepZoneCallback(JSRuntime *rt, JSZoneCallback callback) michael@0: { michael@0: rt->sweepZoneCallback = callback; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetCompartmentNameCallback(JSRuntime *rt, JSCompartmentNameCallback callback) michael@0: { michael@0: rt->compartmentNameCallback = callback; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetWrapObjectCallbacks(JSRuntime *rt, const JSWrapObjectCallbacks *callbacks) michael@0: { michael@0: rt->wrapObjectCallbacks = callbacks; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSCompartment *) michael@0: JS_EnterCompartment(JSContext *cx, JSObject *target) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: JSCompartment *oldCompartment = cx->compartment(); michael@0: cx->enterCompartment(target->compartment()); michael@0: return oldCompartment; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSCompartment *) michael@0: JS_EnterCompartmentOfScript(JSContext *cx, JSScript *target) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: GlobalObject &global = target->global(); michael@0: return JS_EnterCompartment(cx, &global); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_LeaveCompartment(JSContext *cx, JSCompartment *oldCompartment) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: cx->leaveCompartment(oldCompartment); michael@0: } michael@0: michael@0: JSAutoCompartment::JSAutoCompartment(JSContext *cx, JSObject *target) michael@0: : cx_(cx), michael@0: oldCompartment_(cx->compartment()) michael@0: { michael@0: AssertHeapIsIdleOrIterating(cx_); michael@0: cx_->enterCompartment(target->compartment()); michael@0: } michael@0: michael@0: JSAutoCompartment::JSAutoCompartment(JSContext *cx, JSScript *target) michael@0: : cx_(cx), michael@0: oldCompartment_(cx->compartment()) michael@0: { michael@0: AssertHeapIsIdleOrIterating(cx_); michael@0: cx_->enterCompartment(target->compartment()); michael@0: } michael@0: michael@0: JSAutoCompartment::~JSAutoCompartment() michael@0: { michael@0: cx_->leaveCompartment(oldCompartment_); michael@0: } michael@0: michael@0: JSAutoNullCompartment::JSAutoNullCompartment(JSContext *cx) michael@0: : cx_(cx), michael@0: oldCompartment_(cx->compartment()) michael@0: { michael@0: AssertHeapIsIdleOrIterating(cx_); michael@0: cx_->enterNullCompartment(); michael@0: } michael@0: michael@0: JSAutoNullCompartment::~JSAutoNullCompartment() michael@0: { michael@0: cx_->leaveCompartment(oldCompartment_); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetCompartmentPrivate(JSCompartment *compartment, void *data) michael@0: { michael@0: compartment->data = data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_GetCompartmentPrivate(JSCompartment *compartment) michael@0: { michael@0: return compartment->data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetZoneUserData(JS::Zone *zone, void *data) michael@0: { michael@0: zone->data = data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_GetZoneUserData(JS::Zone *zone) michael@0: { michael@0: return zone->data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_WrapObject(JSContext *cx, MutableHandleObject objp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (objp) michael@0: JS::ExposeGCThingToActiveJS(objp, JSTRACE_OBJECT); michael@0: return cx->compartment()->wrap(cx, objp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_WrapValue(JSContext *cx, MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JS::ExposeValueToActiveJS(vp); michael@0: return cx->compartment()->wrap(cx, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_WrapId(JSContext *cx, JS::MutableHandleId idp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: jsid id = idp.get(); michael@0: if (JSID_IS_STRING(id)) michael@0: JS::ExposeGCThingToActiveJS(JSID_TO_STRING(id), JSTRACE_STRING); michael@0: else if (JSID_IS_OBJECT(id)) michael@0: JS::ExposeGCThingToActiveJS(JSID_TO_OBJECT(id), JSTRACE_OBJECT); michael@0: return cx->compartment()->wrapId(cx, idp.address()); michael@0: } michael@0: michael@0: /* michael@0: * Identity remapping. Not for casual consumers. michael@0: * michael@0: * Normally, an object's contents and its identity are inextricably linked. michael@0: * Identity is determined by the address of the JSObject* in the heap, and michael@0: * the contents are what is located at that address. Transplanting allows these michael@0: * concepts to be separated through a combination of swapping (exchanging the michael@0: * contents of two same-compartment objects) and remapping cross-compartment michael@0: * identities by altering wrappers. michael@0: * michael@0: * The |origobj| argument should be the object whose identity needs to be michael@0: * remapped, usually to another compartment. The contents of |origobj| are michael@0: * destroyed. michael@0: * michael@0: * The |target| argument serves two purposes: michael@0: * michael@0: * First, |target| serves as a hint for the new identity of the object. The new michael@0: * identity object will always be in the same compartment as |target|, but michael@0: * if that compartment already had an object representing |origobj| (either a michael@0: * cross-compartment wrapper for it, or |origobj| itself if the two arguments michael@0: * are same-compartment), the existing object is used. Otherwise, |target| michael@0: * itself is used. To avoid ambiguity, JS_TransplantObject always returns the michael@0: * new identity. michael@0: * michael@0: * Second, the new identity object's contents will be those of |target|. A swap() michael@0: * is used to make this happen if an object other than |target| is used. michael@0: * michael@0: * We don't have a good way to recover from failure in this function, so michael@0: * we intentionally crash instead. michael@0: */ michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_TransplantObject(JSContext *cx, HandleObject origobj, HandleObject target) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: JS_ASSERT(origobj != target); michael@0: JS_ASSERT(!origobj->is()); michael@0: JS_ASSERT(!target->is()); michael@0: michael@0: RootedValue origv(cx, ObjectValue(*origobj)); michael@0: RootedObject newIdentity(cx); michael@0: michael@0: { michael@0: // Scope to make ~AutoMaybeTouchDeadZones do its GC before the return value is on the stack. michael@0: AutoMaybeTouchDeadZones agc(cx); michael@0: AutoDisableProxyCheck adpc(cx->runtime()); michael@0: michael@0: JSCompartment *destination = target->compartment(); michael@0: michael@0: if (origobj->compartment() == destination) { michael@0: // If the original object is in the same compartment as the michael@0: // destination, then we know that we won't find a wrapper in the michael@0: // destination's cross compartment map and that the same michael@0: // object will continue to work. michael@0: if (!JSObject::swap(cx, origobj, target)) michael@0: MOZ_CRASH(); michael@0: newIdentity = origobj; michael@0: } else if (WrapperMap::Ptr p = destination->lookupWrapper(origv)) { michael@0: // There might already be a wrapper for the original object in michael@0: // the new compartment. If there is, we use its identity and swap michael@0: // in the contents of |target|. michael@0: newIdentity = &p->value().toObject(); michael@0: michael@0: // When we remove origv from the wrapper map, its wrapper, newIdentity, michael@0: // must immediately cease to be a cross-compartment wrapper. Neuter it. michael@0: destination->removeWrapper(p); michael@0: NukeCrossCompartmentWrapper(cx, newIdentity); michael@0: michael@0: if (!JSObject::swap(cx, newIdentity, target)) michael@0: MOZ_CRASH(); michael@0: } else { michael@0: // Otherwise, we use |target| for the new identity object. michael@0: newIdentity = target; michael@0: } michael@0: michael@0: // Now, iterate through other scopes looking for references to the michael@0: // old object, and update the relevant cross-compartment wrappers. michael@0: if (!RemapAllWrappersForObject(cx, origobj, newIdentity)) michael@0: MOZ_CRASH(); michael@0: michael@0: // Lastly, update the original object to point to the new one. michael@0: if (origobj->compartment() != destination) { michael@0: RootedObject newIdentityWrapper(cx, newIdentity); michael@0: AutoCompartment ac(cx, origobj); michael@0: if (!JS_WrapObject(cx, &newIdentityWrapper)) michael@0: MOZ_CRASH(); michael@0: JS_ASSERT(Wrapper::wrappedObject(newIdentityWrapper) == newIdentity); michael@0: if (!JSObject::swap(cx, origobj, newIdentityWrapper)) michael@0: MOZ_CRASH(); michael@0: origobj->compartment()->putWrapper(cx, ObjectValue(*newIdentity), origv); michael@0: } michael@0: } michael@0: michael@0: // The new identity object might be one of several things. Return it to avoid michael@0: // ambiguity. michael@0: return newIdentity; michael@0: } michael@0: michael@0: /* michael@0: * Recompute all cross-compartment wrappers for an object, resetting state. michael@0: * Gecko uses this to clear Xray wrappers when doing a navigation that reuses michael@0: * the inner window and global object. michael@0: */ michael@0: JS_PUBLIC_API(bool) michael@0: JS_RefreshCrossCompartmentWrappers(JSContext *cx, HandleObject obj) michael@0: { michael@0: return RemapAllWrappersForObject(cx, obj, obj); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_InitStandardClasses(JSContext *cx, HandleObject obj) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: cx->setDefaultCompartmentObjectIfUnset(obj); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: Rooted global(cx, &obj->global()); michael@0: return GlobalObject::initStandardClasses(cx, global); michael@0: } michael@0: michael@0: #define CLASP(name) (&name##Class) michael@0: #define OCLASP(name) (&name##Object::class_) michael@0: #define TYPED_ARRAY_CLASP(type) (&TypedArrayObject::classes[ScalarTypeDescr::type]) michael@0: #define EAGER_ATOM(name) NAME_OFFSET(name) michael@0: #define EAGER_CLASS_ATOM(name) NAME_OFFSET(name) michael@0: michael@0: static js::Class DummyClass; michael@0: static js::Class SentinelClass; michael@0: michael@0: typedef struct JSStdName { michael@0: size_t atomOffset; /* offset of atom pointer in JSAtomState */ michael@0: const Class *clasp; michael@0: bool isDummy() const { return clasp == &DummyClass; }; michael@0: bool isSentinel() const { return clasp == &SentinelClass; }; michael@0: } JSStdName; michael@0: michael@0: static const JSStdName* michael@0: LookupStdName(JSRuntime *rt, HandleString name, const JSStdName *table) michael@0: { michael@0: MOZ_ASSERT(name->isAtom()); michael@0: for (unsigned i = 0; !table[i].isSentinel(); i++) { michael@0: if (table[i].isDummy()) michael@0: continue; michael@0: JSAtom *atom = AtomStateOffsetToName(*rt->commonNames, table[i].atomOffset); michael@0: MOZ_ASSERT(atom); michael@0: if (name == atom) michael@0: return &table[i]; michael@0: } michael@0: michael@0: return nullptr; michael@0: } michael@0: michael@0: /* michael@0: * Table of standard classes, indexed by JSProtoKey. For entries where the michael@0: * JSProtoKey does not correspond to a class with a meaningful constructor, we michael@0: * insert a null entry into the table. michael@0: */ michael@0: #define STD_NAME_ENTRY(name, code, init, clasp) { EAGER_CLASS_ATOM(name), clasp }, michael@0: #define STD_DUMMY_ENTRY(name, code, init, dummy) { 0, &DummyClass }, michael@0: static const JSStdName standard_class_names[] = { michael@0: JS_FOR_PROTOTYPES(STD_NAME_ENTRY, STD_DUMMY_ENTRY) michael@0: { 0, &SentinelClass } michael@0: }; michael@0: michael@0: /* michael@0: * Table of top-level function and constant names and the init function of the michael@0: * corresponding standard class that sets them up. michael@0: */ michael@0: static const JSStdName builtin_property_names[] = { michael@0: { EAGER_ATOM(eval), &JSObject::class_ }, michael@0: michael@0: /* Global properties and functions defined by the Number class. */ michael@0: { EAGER_ATOM(NaN), OCLASP(Number) }, michael@0: { EAGER_ATOM(Infinity), OCLASP(Number) }, michael@0: { EAGER_ATOM(isNaN), OCLASP(Number) }, michael@0: { EAGER_ATOM(isFinite), OCLASP(Number) }, michael@0: { EAGER_ATOM(parseFloat), OCLASP(Number) }, michael@0: { EAGER_ATOM(parseInt), OCLASP(Number) }, michael@0: michael@0: /* String global functions. */ michael@0: { EAGER_ATOM(escape), OCLASP(String) }, michael@0: { EAGER_ATOM(unescape), OCLASP(String) }, michael@0: { EAGER_ATOM(decodeURI), OCLASP(String) }, michael@0: { EAGER_ATOM(encodeURI), OCLASP(String) }, michael@0: { EAGER_ATOM(decodeURIComponent), OCLASP(String) }, michael@0: { EAGER_ATOM(encodeURIComponent), OCLASP(String) }, michael@0: #if JS_HAS_UNEVAL michael@0: { EAGER_ATOM(uneval), OCLASP(String) }, michael@0: #endif michael@0: #ifdef ENABLE_BINARYDATA michael@0: { EAGER_ATOM(SIMD), OCLASP(SIMD) }, michael@0: { EAGER_ATOM(TypedObject), OCLASP(TypedObjectModule) }, michael@0: #endif michael@0: michael@0: { 0, &SentinelClass } michael@0: }; michael@0: michael@0: #undef CLASP michael@0: #undef TYPED_ARRAY_CLASP michael@0: #undef EAGER_ATOM michael@0: #undef EAGER_CLASS_ATOM michael@0: #undef EAGER_ATOM_CLASP michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ResolveStandardClass(JSContext *cx, HandleObject obj, HandleId id, bool *resolved) michael@0: { michael@0: JSRuntime *rt; michael@0: const JSStdName *stdnm; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, id); michael@0: michael@0: Rooted global(cx, &obj->as()); michael@0: *resolved = false; michael@0: michael@0: rt = cx->runtime(); michael@0: if (!rt->hasContexts() || !JSID_IS_ATOM(id)) michael@0: return true; michael@0: michael@0: RootedString idstr(cx, JSID_TO_STRING(id)); michael@0: michael@0: /* Check whether we're resolving 'undefined', and define it if so. */ michael@0: JSAtom *undefinedAtom = cx->names().undefined; michael@0: if (idstr == undefinedAtom) { michael@0: *resolved = true; michael@0: return JSObject::defineProperty(cx, obj, undefinedAtom->asPropertyName(), michael@0: UndefinedHandleValue, michael@0: JS_PropertyStub, JS_StrictPropertyStub, michael@0: JSPROP_PERMANENT | JSPROP_READONLY); michael@0: } michael@0: michael@0: /* Try for class constructors/prototypes named by well-known atoms. */ michael@0: stdnm = LookupStdName(rt, idstr, standard_class_names); michael@0: michael@0: /* Try less frequently used top-level functions and constants. */ michael@0: if (!stdnm) michael@0: stdnm = LookupStdName(rt, idstr, builtin_property_names); michael@0: michael@0: // If this class is anonymous, then it doesn't exist as a global michael@0: // property, so we won't resolve anything. michael@0: if (stdnm && !(stdnm->clasp->flags & JSCLASS_IS_ANONYMOUS)) { michael@0: JSProtoKey key = JSCLASS_CACHED_PROTO_KEY(stdnm->clasp); michael@0: if (!GlobalObject::ensureConstructor(cx, global, key)) michael@0: return false; michael@0: michael@0: *resolved = true; michael@0: return true; michael@0: } michael@0: michael@0: // There is no such property to resolve. An ordinary resolve hook would michael@0: // just return true at this point. But the global object is special in one michael@0: // more way: its prototype chain is lazily initialized. That is, michael@0: // global->getProto() might be null right now because we haven't created michael@0: // Object.prototype yet. Force it now. michael@0: if (!global->getOrCreateObjectPrototype(cx)) michael@0: return false; michael@0: michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_EnumerateStandardClasses(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: MOZ_ASSERT(obj->is()); michael@0: Rooted global(cx, &obj->as()); michael@0: return GlobalObject::initStandardClasses(cx, global); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetClassObject(JSContext *cx, JSProtoKey key, MutableHandleObject objp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return GetBuiltinConstructor(cx, key, objp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetClassPrototype(JSContext *cx, JSProtoKey key, MutableHandleObject objp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return GetBuiltinPrototype(cx, key, objp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSProtoKey) michael@0: JS_IdToProtoKey(JSContext *cx, HandleId id) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: if (!JSID_IS_ATOM(id)) michael@0: return JSProto_Null; michael@0: RootedString idstr(cx, JSID_TO_STRING(id)); michael@0: const JSStdName *stdnm = LookupStdName(cx->runtime(), idstr, standard_class_names); michael@0: if (!stdnm) michael@0: return JSProto_Null; michael@0: michael@0: MOZ_ASSERT(MOZ_ARRAY_LENGTH(standard_class_names) == JSProto_LIMIT + 1); michael@0: return static_cast(stdnm - standard_class_names); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetObjectPrototype(JSContext *cx, HandleObject forObj) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, forObj); michael@0: return forObj->global().getOrCreateObjectPrototype(cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetFunctionPrototype(JSContext *cx, HandleObject forObj) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, forObj); michael@0: return forObj->global().getOrCreateFunctionPrototype(cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetArrayPrototype(JSContext *cx, HandleObject forObj) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, forObj); michael@0: Rooted global(cx, &forObj->global()); michael@0: return GlobalObject::getOrCreateArrayPrototype(cx, global); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetGlobalForObject(JSContext *cx, JSObject *obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: assertSameCompartment(cx, obj); michael@0: return &obj->global(); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS_IsGlobalObject(JSObject *obj) michael@0: { michael@0: return obj->is(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetGlobalForCompartmentOrNull(JSContext *cx, JSCompartment *c) michael@0: { michael@0: AssertHeapIsIdleOrIterating(cx); michael@0: assertSameCompartment(cx, c); michael@0: return c->maybeGlobal(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS::CurrentGlobalOrNull(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdleOrIterating(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (!cx->compartment()) michael@0: return nullptr; michael@0: return cx->global(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(jsval) michael@0: JS_ComputeThis(JSContext *cx, jsval *vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: assertSameCompartment(cx, JSValueArray(vp, 2)); michael@0: CallReceiver call = CallReceiverFromVp(vp); michael@0: if (!BoxNonStrictThis(cx, call)) michael@0: return JSVAL_NULL; michael@0: return call.thisv(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_malloc(JSContext *cx, size_t nbytes) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return cx->malloc_(nbytes); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_realloc(JSContext *cx, void *p, size_t nbytes) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return cx->realloc_(p, nbytes); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_free(JSContext *cx, void *p) michael@0: { michael@0: return js_free(p); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_freeop(JSFreeOp *fop, void *p) michael@0: { michael@0: return FreeOp::get(fop)->free_(p); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFreeOp *) michael@0: JS_GetDefaultFreeOp(JSRuntime *rt) michael@0: { michael@0: return rt->defaultFreeOp(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_updateMallocCounter(JSContext *cx, size_t nbytes) michael@0: { michael@0: return cx->runtime()->updateMallocCounter(cx->zone(), nbytes); michael@0: } michael@0: michael@0: JS_PUBLIC_API(char *) michael@0: JS_strdup(JSContext *cx, const char *s) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: return js_strdup(cx, s); michael@0: } michael@0: michael@0: JS_PUBLIC_API(char *) michael@0: JS_strdup(JSRuntime *rt, const char *s) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: size_t n = strlen(s) + 1; michael@0: void *p = rt->malloc_(n); michael@0: if (!p) michael@0: return nullptr; michael@0: return static_cast(js_memcpy(p, s, n)); michael@0: } michael@0: michael@0: #undef JS_AddRoot michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::AddValueRoot(JSContext *cx, JS::Heap *vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return AddValueRoot(cx, vp->unsafeGet(), nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::AddStringRoot(JSContext *cx, JS::Heap *rp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return AddStringRoot(cx, rp->unsafeGet(), nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::AddObjectRoot(JSContext *cx, JS::Heap *rp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return AddObjectRoot(cx, rp->unsafeGet(), nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::AddNamedValueRoot(JSContext *cx, JS::Heap *vp, const char *name) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return AddValueRoot(cx, vp->unsafeGet(), name); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::AddNamedValueRootRT(JSRuntime *rt, JS::Heap *vp, const char *name) michael@0: { michael@0: return AddValueRootRT(rt, vp->unsafeGet(), name); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::AddNamedStringRoot(JSContext *cx, JS::Heap *rp, const char *name) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return AddStringRoot(cx, rp->unsafeGet(), name); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::AddNamedObjectRoot(JSContext *cx, JS::Heap *rp, const char *name) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return AddObjectRoot(cx, rp->unsafeGet(), name); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::AddNamedScriptRoot(JSContext *cx, JS::Heap *rp, const char *name) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return AddScriptRoot(cx, rp->unsafeGet(), name); michael@0: } michael@0: michael@0: /* We allow unrooting from finalizers within the GC */ michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::RemoveValueRoot(JSContext *cx, JS::Heap *vp) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: RemoveRoot(cx->runtime(), (void *)vp); michael@0: *vp = UndefinedValue(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::RemoveStringRoot(JSContext *cx, JS::Heap *rp) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: RemoveRoot(cx->runtime(), (void *)rp); michael@0: *rp = nullptr; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::RemoveObjectRoot(JSContext *cx, JS::Heap *rp) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: RemoveRoot(cx->runtime(), (void *)rp); michael@0: *rp = nullptr; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::RemoveScriptRoot(JSContext *cx, JS::Heap *rp) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: RemoveRoot(cx->runtime(), (void *)rp); michael@0: *rp = nullptr; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::RemoveValueRootRT(JSRuntime *rt, JS::Heap *vp) michael@0: { michael@0: RemoveRoot(rt, (void *)vp); michael@0: *vp = UndefinedValue(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::RemoveStringRootRT(JSRuntime *rt, JS::Heap *rp) michael@0: { michael@0: RemoveRoot(rt, (void *)rp); michael@0: *rp = nullptr; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::RemoveObjectRootRT(JSRuntime *rt, JS::Heap *rp) michael@0: { michael@0: RemoveRoot(rt, (void *)rp); michael@0: *rp = nullptr; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::RemoveScriptRootRT(JSRuntime *rt, JS::Heap *rp) michael@0: { michael@0: RemoveRoot(rt, (void *)rp); michael@0: *rp = nullptr; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_AddExtraGCRootsTracer(JSRuntime *rt, JSTraceDataOp traceOp, void *data) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: return !!rt->gcBlackRootTracers.append(JSRuntime::ExtraTracer(traceOp, data)); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_RemoveExtraGCRootsTracer(JSRuntime *rt, JSTraceDataOp traceOp, void *data) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: for (size_t i = 0; i < rt->gcBlackRootTracers.length(); i++) { michael@0: JSRuntime::ExtraTracer *e = &rt->gcBlackRootTracers[i]; michael@0: if (e->op == traceOp && e->data == data) { michael@0: rt->gcBlackRootTracers.erase(e); michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: michael@0: #ifdef DEBUG michael@0: michael@0: typedef struct JSHeapDumpNode JSHeapDumpNode; michael@0: michael@0: struct JSHeapDumpNode { michael@0: void *thing; michael@0: JSGCTraceKind kind; michael@0: JSHeapDumpNode *next; /* next sibling */ michael@0: JSHeapDumpNode *parent; /* node with the thing that refer to thing michael@0: from this node */ michael@0: char edgeName[1]; /* name of the edge from parent->thing michael@0: into thing */ michael@0: }; michael@0: michael@0: typedef HashSet, SystemAllocPolicy> VisitedSet; michael@0: michael@0: class DumpingTracer michael@0: { michael@0: public: michael@0: DumpingTracer(JSRuntime *rt, JSTraceCallback callback) michael@0: : base(rt, callback) michael@0: {} michael@0: michael@0: JSTracer base; michael@0: VisitedSet visited; michael@0: bool ok; michael@0: void *startThing; michael@0: void *thingToFind; michael@0: void *thingToIgnore; michael@0: JSHeapDumpNode *parentNode; michael@0: JSHeapDumpNode **lastNodep; michael@0: char buffer[200]; michael@0: }; michael@0: michael@0: static void michael@0: DumpNotify(JSTracer *trc, void **thingp, JSGCTraceKind kind) michael@0: { michael@0: JS_ASSERT(trc->callback == DumpNotify); michael@0: michael@0: DumpingTracer *dtrc = (DumpingTracer *)trc; michael@0: void *thing = *thingp; michael@0: michael@0: if (!dtrc->ok || thing == dtrc->thingToIgnore) michael@0: return; michael@0: michael@0: /* michael@0: * Check if we have already seen thing unless it is thingToFind to include michael@0: * it to the graph each time we reach it and print all live things that michael@0: * refer to thingToFind. michael@0: * michael@0: * This does not print all possible paths leading to thingToFind since michael@0: * when a thing A refers directly or indirectly to thingToFind and A is michael@0: * present several times in the graph, we will print only the first path michael@0: * leading to A and thingToFind, other ways to reach A will be ignored. michael@0: */ michael@0: if (dtrc->thingToFind != thing) { michael@0: /* michael@0: * The startThing check allows to avoid putting startThing into the michael@0: * hash table before tracing startThing in JS_DumpHeap. michael@0: */ michael@0: if (thing == dtrc->startThing) michael@0: return; michael@0: VisitedSet::AddPtr p = dtrc->visited.lookupForAdd(thing); michael@0: if (p) michael@0: return; michael@0: if (!dtrc->visited.add(p, thing)) { michael@0: dtrc->ok = false; michael@0: return; michael@0: } michael@0: } michael@0: michael@0: const char *edgeName = dtrc->base.getTracingEdgeName(dtrc->buffer, sizeof(dtrc->buffer)); michael@0: size_t edgeNameSize = strlen(edgeName) + 1; michael@0: size_t bytes = offsetof(JSHeapDumpNode, edgeName) + edgeNameSize; michael@0: JSHeapDumpNode *node = (JSHeapDumpNode *) js_malloc(bytes); michael@0: if (!node) { michael@0: dtrc->ok = false; michael@0: return; michael@0: } michael@0: michael@0: node->thing = thing; michael@0: node->kind = kind; michael@0: node->next = nullptr; michael@0: node->parent = dtrc->parentNode; michael@0: js_memcpy(node->edgeName, edgeName, edgeNameSize); michael@0: michael@0: JS_ASSERT(!*dtrc->lastNodep); michael@0: *dtrc->lastNodep = node; michael@0: dtrc->lastNodep = &node->next; michael@0: } michael@0: michael@0: /* Dump node and the chain that leads to thing it contains. */ michael@0: static bool michael@0: DumpNode(DumpingTracer *dtrc, FILE* fp, JSHeapDumpNode *node) michael@0: { michael@0: JSHeapDumpNode *prev, *following; michael@0: size_t chainLimit; michael@0: enum { MAX_PARENTS_TO_PRINT = 10 }; michael@0: michael@0: JS_GetTraceThingInfo(dtrc->buffer, sizeof dtrc->buffer, michael@0: &dtrc->base, node->thing, node->kind, true); michael@0: if (fprintf(fp, "%p %-22s via ", node->thing, dtrc->buffer) < 0) michael@0: return false; michael@0: michael@0: /* michael@0: * We need to print the parent chain in the reverse order. To do it in michael@0: * O(N) time where N is the chain length we first reverse the chain while michael@0: * searching for the top and then print each node while restoring the michael@0: * chain order. michael@0: */ michael@0: chainLimit = MAX_PARENTS_TO_PRINT; michael@0: prev = nullptr; michael@0: for (;;) { michael@0: following = node->parent; michael@0: node->parent = prev; michael@0: prev = node; michael@0: node = following; michael@0: if (!node) michael@0: break; michael@0: if (chainLimit == 0) { michael@0: if (fputs("...", fp) < 0) michael@0: return false; michael@0: break; michael@0: } michael@0: --chainLimit; michael@0: } michael@0: michael@0: node = prev; michael@0: prev = following; michael@0: bool ok = true; michael@0: do { michael@0: /* Loop must continue even when !ok to restore the parent chain. */ michael@0: if (ok) { michael@0: if (!prev) { michael@0: /* Print edge from some runtime root or startThing. */ michael@0: if (fputs(node->edgeName, fp) < 0) michael@0: ok = false; michael@0: } else { michael@0: JS_GetTraceThingInfo(dtrc->buffer, sizeof dtrc->buffer, michael@0: &dtrc->base, prev->thing, prev->kind, michael@0: false); michael@0: if (fprintf(fp, "(%p %s).%s", michael@0: prev->thing, dtrc->buffer, node->edgeName) < 0) { michael@0: ok = false; michael@0: } michael@0: } michael@0: } michael@0: following = node->parent; michael@0: node->parent = prev; michael@0: prev = node; michael@0: node = following; michael@0: } while (node); michael@0: michael@0: return ok && putc('\n', fp) >= 0; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DumpHeap(JSRuntime *rt, FILE *fp, void* startThing, JSGCTraceKind startKind, michael@0: void *thingToFind, size_t maxDepth, void *thingToIgnore) michael@0: { michael@0: if (maxDepth == 0) michael@0: return true; michael@0: michael@0: DumpingTracer dtrc(rt, DumpNotify); michael@0: if (!dtrc.visited.init()) michael@0: return false; michael@0: dtrc.ok = true; michael@0: dtrc.startThing = startThing; michael@0: dtrc.thingToFind = thingToFind; michael@0: dtrc.thingToIgnore = thingToIgnore; michael@0: dtrc.parentNode = nullptr; michael@0: JSHeapDumpNode *node = nullptr; michael@0: dtrc.lastNodep = &node; michael@0: if (!startThing) { michael@0: JS_ASSERT(startKind == JSTRACE_OBJECT); michael@0: TraceRuntime(&dtrc.base); michael@0: } else { michael@0: JS_TraceChildren(&dtrc.base, startThing, startKind); michael@0: } michael@0: michael@0: if (!node) michael@0: return dtrc.ok; michael@0: michael@0: size_t depth = 1; michael@0: JSHeapDumpNode *children, *next, *parent; michael@0: bool thingToFindWasTraced = thingToFind && thingToFind == startThing; michael@0: for (;;) { michael@0: /* michael@0: * Loop must continue even when !dtrc.ok to free all nodes allocated michael@0: * so far. michael@0: */ michael@0: if (dtrc.ok) { michael@0: if (thingToFind == nullptr || thingToFind == node->thing) michael@0: dtrc.ok = DumpNode(&dtrc, fp, node); michael@0: michael@0: /* Descend into children. */ michael@0: if (dtrc.ok && michael@0: depth < maxDepth && michael@0: (thingToFind != node->thing || !thingToFindWasTraced)) { michael@0: dtrc.parentNode = node; michael@0: children = nullptr; michael@0: dtrc.lastNodep = &children; michael@0: JS_TraceChildren(&dtrc.base, node->thing, node->kind); michael@0: if (thingToFind == node->thing) michael@0: thingToFindWasTraced = true; michael@0: if (children != nullptr) { michael@0: ++depth; michael@0: node = children; michael@0: continue; michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* Move to next or parents next and free the node. */ michael@0: for (;;) { michael@0: next = node->next; michael@0: parent = node->parent; michael@0: js_free(node); michael@0: node = next; michael@0: if (node) michael@0: break; michael@0: if (!parent) michael@0: return dtrc.ok; michael@0: JS_ASSERT(depth > 1); michael@0: --depth; michael@0: node = parent; michael@0: } michael@0: } michael@0: michael@0: JS_ASSERT(depth == 1); michael@0: return dtrc.ok; michael@0: } michael@0: michael@0: #endif /* DEBUG */ michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS_IsGCMarkingTracer(JSTracer *trc) michael@0: { michael@0: return IS_GC_MARKING_TRACER(trc); michael@0: } michael@0: michael@0: #ifdef DEBUG michael@0: extern JS_PUBLIC_API(bool) michael@0: JS_IsMarkingGray(JSTracer *trc) michael@0: { michael@0: JS_ASSERT(JS_IsGCMarkingTracer(trc)); michael@0: return trc->callback == GCMarker::GrayCallback; michael@0: } michael@0: #endif michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_GC(JSRuntime *rt) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: JS::PrepareForFullGC(rt); michael@0: GC(rt, GC_NORMAL, JS::gcreason::API); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_MaybeGC(JSContext *cx) michael@0: { michael@0: MaybeGC(cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetGCCallback(JSRuntime *rt, JSGCCallback cb, void *data) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: rt->gcCallback = cb; michael@0: rt->gcCallbackData = data; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetFinalizeCallback(JSRuntime *rt, JSFinalizeCallback cb) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: rt->gcFinalizeCallback = cb; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsAboutToBeFinalized(JS::Heap *objp) michael@0: { michael@0: return IsObjectAboutToBeFinalized(objp->unsafeGet()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsAboutToBeFinalizedUnbarriered(JSObject **objp) michael@0: { michael@0: return IsObjectAboutToBeFinalized(objp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetGCParameter(JSRuntime *rt, JSGCParamKey key, uint32_t value) michael@0: { michael@0: switch (key) { michael@0: case JSGC_MAX_BYTES: { michael@0: JS_ASSERT(value >= rt->gcBytes); michael@0: rt->gcMaxBytes = value; michael@0: break; michael@0: } michael@0: case JSGC_MAX_MALLOC_BYTES: michael@0: rt->setGCMaxMallocBytes(value); michael@0: break; michael@0: case JSGC_SLICE_TIME_BUDGET: michael@0: rt->gcSliceBudget = SliceBudget::TimeBudget(value); michael@0: break; michael@0: case JSGC_MARK_STACK_LIMIT: michael@0: js::SetMarkStackLimit(rt, value); michael@0: break; michael@0: case JSGC_HIGH_FREQUENCY_TIME_LIMIT: michael@0: rt->gcHighFrequencyTimeThreshold = value; michael@0: break; michael@0: case JSGC_HIGH_FREQUENCY_LOW_LIMIT: michael@0: rt->gcHighFrequencyLowLimitBytes = value * 1024 * 1024; michael@0: break; michael@0: case JSGC_HIGH_FREQUENCY_HIGH_LIMIT: michael@0: rt->gcHighFrequencyHighLimitBytes = value * 1024 * 1024; michael@0: break; michael@0: case JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX: michael@0: rt->gcHighFrequencyHeapGrowthMax = value / 100.0; michael@0: MOZ_ASSERT(rt->gcHighFrequencyHeapGrowthMax / 0.85 > 1.0); michael@0: break; michael@0: case JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN: michael@0: rt->gcHighFrequencyHeapGrowthMin = value / 100.0; michael@0: MOZ_ASSERT(rt->gcHighFrequencyHeapGrowthMin / 0.85 > 1.0); michael@0: break; michael@0: case JSGC_LOW_FREQUENCY_HEAP_GROWTH: michael@0: rt->gcLowFrequencyHeapGrowth = value / 100.0; michael@0: MOZ_ASSERT(rt->gcLowFrequencyHeapGrowth / 0.9 > 1.0); michael@0: break; michael@0: case JSGC_DYNAMIC_HEAP_GROWTH: michael@0: rt->gcDynamicHeapGrowth = value; michael@0: break; michael@0: case JSGC_DYNAMIC_MARK_SLICE: michael@0: rt->gcDynamicMarkSlice = value; michael@0: break; michael@0: case JSGC_ALLOCATION_THRESHOLD: michael@0: rt->gcAllocationThreshold = value * 1024 * 1024; michael@0: break; michael@0: case JSGC_DECOMMIT_THRESHOLD: michael@0: rt->gcDecommitThreshold = value * 1024 * 1024; michael@0: break; michael@0: default: michael@0: JS_ASSERT(key == JSGC_MODE); michael@0: rt->setGCMode(JSGCMode(value)); michael@0: JS_ASSERT(rt->gcMode() == JSGC_MODE_GLOBAL || michael@0: rt->gcMode() == JSGC_MODE_COMPARTMENT || michael@0: rt->gcMode() == JSGC_MODE_INCREMENTAL); michael@0: return; michael@0: } michael@0: } michael@0: michael@0: JS_PUBLIC_API(uint32_t) michael@0: JS_GetGCParameter(JSRuntime *rt, JSGCParamKey key) michael@0: { michael@0: switch (key) { michael@0: case JSGC_MAX_BYTES: michael@0: return uint32_t(rt->gcMaxBytes); michael@0: case JSGC_MAX_MALLOC_BYTES: michael@0: return rt->gcMaxMallocBytes; michael@0: case JSGC_BYTES: michael@0: return uint32_t(rt->gcBytes); michael@0: case JSGC_MODE: michael@0: return uint32_t(rt->gcMode()); michael@0: case JSGC_UNUSED_CHUNKS: michael@0: return uint32_t(rt->gcChunkPool.getEmptyCount()); michael@0: case JSGC_TOTAL_CHUNKS: michael@0: return uint32_t(rt->gcChunkSet.count() + rt->gcChunkPool.getEmptyCount()); michael@0: case JSGC_SLICE_TIME_BUDGET: michael@0: return uint32_t(rt->gcSliceBudget > 0 ? rt->gcSliceBudget / PRMJ_USEC_PER_MSEC : 0); michael@0: case JSGC_MARK_STACK_LIMIT: michael@0: return rt->gcMarker.maxCapacity(); michael@0: case JSGC_HIGH_FREQUENCY_TIME_LIMIT: michael@0: return rt->gcHighFrequencyTimeThreshold; michael@0: case JSGC_HIGH_FREQUENCY_LOW_LIMIT: michael@0: return rt->gcHighFrequencyLowLimitBytes / 1024 / 1024; michael@0: case JSGC_HIGH_FREQUENCY_HIGH_LIMIT: michael@0: return rt->gcHighFrequencyHighLimitBytes / 1024 / 1024; michael@0: case JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX: michael@0: return uint32_t(rt->gcHighFrequencyHeapGrowthMax * 100); michael@0: case JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN: michael@0: return uint32_t(rt->gcHighFrequencyHeapGrowthMin * 100); michael@0: case JSGC_LOW_FREQUENCY_HEAP_GROWTH: michael@0: return uint32_t(rt->gcLowFrequencyHeapGrowth * 100); michael@0: case JSGC_DYNAMIC_HEAP_GROWTH: michael@0: return rt->gcDynamicHeapGrowth; michael@0: case JSGC_DYNAMIC_MARK_SLICE: michael@0: return rt->gcDynamicMarkSlice; michael@0: case JSGC_ALLOCATION_THRESHOLD: michael@0: return rt->gcAllocationThreshold / 1024 / 1024; michael@0: default: michael@0: JS_ASSERT(key == JSGC_NUMBER); michael@0: return uint32_t(rt->gcNumber); michael@0: } michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetGCParameterForThread(JSContext *cx, JSGCParamKey key, uint32_t value) michael@0: { michael@0: JS_ASSERT(key == JSGC_MAX_CODE_CACHE_BYTES); michael@0: } michael@0: michael@0: JS_PUBLIC_API(uint32_t) michael@0: JS_GetGCParameterForThread(JSContext *cx, JSGCParamKey key) michael@0: { michael@0: JS_ASSERT(key == JSGC_MAX_CODE_CACHE_BYTES); michael@0: return 0; michael@0: } michael@0: michael@0: static const size_t NumGCConfigs = 14; michael@0: struct JSGCConfig { michael@0: JSGCParamKey key; michael@0: uint32_t value; michael@0: }; michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetGCParametersBasedOnAvailableMemory(JSRuntime *rt, uint32_t availMem) michael@0: { michael@0: static const JSGCConfig minimal[NumGCConfigs] = { michael@0: {JSGC_MAX_MALLOC_BYTES, 6 * 1024 * 1024}, michael@0: {JSGC_SLICE_TIME_BUDGET, 30}, michael@0: {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500}, michael@0: {JSGC_HIGH_FREQUENCY_HIGH_LIMIT, 40}, michael@0: {JSGC_HIGH_FREQUENCY_LOW_LIMIT, 0}, michael@0: {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, 300}, michael@0: {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, 120}, michael@0: {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 120}, michael@0: {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500}, michael@0: {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500}, michael@0: {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500}, michael@0: {JSGC_ALLOCATION_THRESHOLD, 1}, michael@0: {JSGC_DECOMMIT_THRESHOLD, 1}, michael@0: {JSGC_MODE, JSGC_MODE_INCREMENTAL} michael@0: }; michael@0: michael@0: const JSGCConfig *config = minimal; michael@0: if (availMem > 512) { michael@0: static const JSGCConfig nominal[NumGCConfigs] = { michael@0: {JSGC_MAX_MALLOC_BYTES, 6 * 1024 * 1024}, michael@0: {JSGC_SLICE_TIME_BUDGET, 30}, michael@0: {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1000}, michael@0: {JSGC_HIGH_FREQUENCY_HIGH_LIMIT, 500}, michael@0: {JSGC_HIGH_FREQUENCY_LOW_LIMIT, 100}, michael@0: {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, 300}, michael@0: {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, 150}, michael@0: {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 150}, michael@0: {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500}, michael@0: {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500}, michael@0: {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500}, michael@0: {JSGC_ALLOCATION_THRESHOLD, 30}, michael@0: {JSGC_DECOMMIT_THRESHOLD, 32}, michael@0: {JSGC_MODE, JSGC_MODE_COMPARTMENT} michael@0: }; michael@0: michael@0: config = nominal; michael@0: } michael@0: michael@0: for (size_t i = 0; i < NumGCConfigs; i++) michael@0: JS_SetGCParameter(rt, config[i].key, config[i].value); michael@0: } michael@0: michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_NewExternalString(JSContext *cx, const jschar *chars, size_t length, michael@0: const JSStringFinalizer *fin) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JSString *s = JSExternalString::new_(cx, chars, length, fin); michael@0: return s; michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS_IsExternalString(JSString *str) michael@0: { michael@0: return str->isExternal(); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(const JSStringFinalizer *) michael@0: JS_GetExternalStringFinalizer(JSString *str) michael@0: { michael@0: return str->asExternal().externalFinalizer(); michael@0: } michael@0: michael@0: static void michael@0: SetNativeStackQuota(JSRuntime *rt, StackKind kind, size_t stackSize) michael@0: { michael@0: rt->nativeStackQuota[kind] = stackSize; michael@0: if (rt->nativeStackBase) michael@0: RecomputeStackLimit(rt, kind); michael@0: } michael@0: michael@0: void michael@0: js::RecomputeStackLimit(JSRuntime *rt, StackKind kind) michael@0: { michael@0: size_t stackSize = rt->nativeStackQuota[kind]; michael@0: #if JS_STACK_GROWTH_DIRECTION > 0 michael@0: if (stackSize == 0) { michael@0: rt->mainThread.nativeStackLimit[kind] = UINTPTR_MAX; michael@0: } else { michael@0: JS_ASSERT(rt->nativeStackBase <= size_t(-1) - stackSize); michael@0: rt->mainThread.nativeStackLimit[kind] = michael@0: rt->nativeStackBase + stackSize - 1; michael@0: } michael@0: #else michael@0: if (stackSize == 0) { michael@0: rt->mainThread.nativeStackLimit[kind] = 0; michael@0: } else { michael@0: JS_ASSERT(rt->nativeStackBase >= stackSize); michael@0: rt->mainThread.nativeStackLimit[kind] = michael@0: rt->nativeStackBase - (stackSize - 1); michael@0: } michael@0: #endif michael@0: michael@0: // If there's no pending interrupt request set on the runtime's main thread's michael@0: // jitStackLimit, then update it so that it reflects the new nativeStacklimit. michael@0: // michael@0: // Note that, for now, we use the untrusted limit for ion. This is fine, michael@0: // because it's the most conservative limit, and if we hit it, we'll bail michael@0: // out of ion into the interpeter, which will do a proper recursion check. michael@0: #ifdef JS_ION michael@0: if (kind == StackForUntrustedScript) { michael@0: JSRuntime::AutoLockForInterrupt lock(rt); michael@0: if (rt->mainThread.jitStackLimit != uintptr_t(-1)) { michael@0: rt->mainThread.jitStackLimit = rt->mainThread.nativeStackLimit[kind]; michael@0: #ifdef JS_ARM_SIMULATOR michael@0: rt->mainThread.jitStackLimit = jit::Simulator::StackLimit(); michael@0: #endif michael@0: } michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetNativeStackQuota(JSRuntime *rt, size_t systemCodeStackSize, michael@0: size_t trustedScriptStackSize, michael@0: size_t untrustedScriptStackSize) michael@0: { michael@0: JS_ASSERT_IF(trustedScriptStackSize, michael@0: trustedScriptStackSize < systemCodeStackSize); michael@0: if (!trustedScriptStackSize) michael@0: trustedScriptStackSize = systemCodeStackSize; michael@0: JS_ASSERT_IF(untrustedScriptStackSize, michael@0: untrustedScriptStackSize < trustedScriptStackSize); michael@0: if (!untrustedScriptStackSize) michael@0: untrustedScriptStackSize = trustedScriptStackSize; michael@0: SetNativeStackQuota(rt, StackForSystemCode, systemCodeStackSize); michael@0: SetNativeStackQuota(rt, StackForTrustedScript, trustedScriptStackSize); michael@0: SetNativeStackQuota(rt, StackForUntrustedScript, untrustedScriptStackSize); michael@0: } michael@0: michael@0: /************************************************************************/ michael@0: michael@0: JS_PUBLIC_API(int) michael@0: JS_IdArrayLength(JSContext *cx, JSIdArray *ida) michael@0: { michael@0: return ida->length; michael@0: } michael@0: michael@0: JS_PUBLIC_API(jsid) michael@0: JS_IdArrayGet(JSContext *cx, JSIdArray *ida, int index) michael@0: { michael@0: JS_ASSERT(index >= 0 && index < ida->length); michael@0: return ida->vector[index]; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_DestroyIdArray(JSContext *cx, JSIdArray *ida) michael@0: { michael@0: cx->runtime()->defaultFreeOp()->free_(ida); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ValueToId(JSContext *cx, HandleValue value, MutableHandleId idp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: return ValueToId(cx, value, idp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_StringToId(JSContext *cx, HandleString string, MutableHandleId idp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, string); michael@0: RootedValue value(cx, StringValue(string)); michael@0: return ValueToId(cx, value, idp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IdToValue(JSContext *cx, jsid id, MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: vp.set(IdToValue(id)); michael@0: assertSameCompartment(cx, vp); michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefaultValue(JSContext *cx, HandleObject obj, JSType hint, MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JS_ASSERT(obj != nullptr); michael@0: JS_ASSERT(hint == JSTYPE_VOID || hint == JSTYPE_STRING || hint == JSTYPE_NUMBER); michael@0: return JSObject::defaultValue(cx, obj, hint, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_PropertyStub(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp) michael@0: { michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_StrictPropertyStub(JSContext *cx, HandleObject obj, HandleId id, bool strict, MutableHandleValue vp) michael@0: { michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeletePropertyStub(JSContext *cx, HandleObject obj, HandleId id, bool *succeeded) michael@0: { michael@0: *succeeded = true; michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_EnumerateStub(JSContext *cx, HandleObject obj) michael@0: { michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ResolveStub(JSContext *cx, HandleObject obj, HandleId id) michael@0: { michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ConvertStub(JSContext *cx, HandleObject obj, JSType type, MutableHandleValue vp) michael@0: { michael@0: JS_ASSERT(type != JSTYPE_OBJECT && type != JSTYPE_FUNCTION); michael@0: JS_ASSERT(obj); michael@0: return DefaultValue(cx, obj, type, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_InitClass(JSContext *cx, HandleObject obj, HandleObject parent_proto, michael@0: const JSClass *clasp, JSNative constructor, unsigned nargs, michael@0: const JSPropertySpec *ps, const JSFunctionSpec *fs, michael@0: const JSPropertySpec *static_ps, const JSFunctionSpec *static_fs) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, parent_proto); michael@0: return js_InitClass(cx, obj, parent_proto, Valueify(clasp), constructor, michael@0: nargs, ps, fs, static_ps, static_fs); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_LinkConstructorAndPrototype(JSContext *cx, HandleObject ctor, HandleObject proto) michael@0: { michael@0: return LinkConstructorAndPrototype(cx, ctor, proto); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const JSClass *) michael@0: JS_GetClass(JSObject *obj) michael@0: { michael@0: return obj->getJSClass(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_InstanceOf(JSContext *cx, HandleObject obj, const JSClass *clasp, CallArgs *args) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: #ifdef DEBUG michael@0: if (args) { michael@0: assertSameCompartment(cx, obj); michael@0: assertSameCompartment(cx, args->thisv(), args->calleev()); michael@0: } michael@0: #endif michael@0: if (!obj || obj->getJSClass() != clasp) { michael@0: if (args) michael@0: ReportIncompatibleMethod(cx, *args, Valueify(clasp)); michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_HasInstance(JSContext *cx, HandleObject obj, HandleValue value, bool *bp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: assertSameCompartment(cx, obj, value); michael@0: return HasInstance(cx, obj, value, bp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_GetPrivate(JSObject *obj) michael@0: { michael@0: /* This function can be called by a finalizer. */ michael@0: return obj->getPrivate(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetPrivate(JSObject *obj, void *data) michael@0: { michael@0: /* This function can be called by a finalizer. */ michael@0: obj->setPrivate(data); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_GetInstancePrivate(JSContext *cx, HandleObject obj, const JSClass *clasp, CallArgs *args) michael@0: { michael@0: if (!JS_InstanceOf(cx, obj, clasp, args)) michael@0: return nullptr; michael@0: return obj->getPrivate(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetPrototype(JSContext *cx, JS::Handle obj, JS::MutableHandle protop) michael@0: { michael@0: return JSObject::getProto(cx, obj, protop); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetPrototype(JSContext *cx, JS::Handle obj, JS::Handle proto) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, proto); michael@0: michael@0: bool succeeded; michael@0: if (!JSObject::setProto(cx, obj, proto, &succeeded)) michael@0: return false; michael@0: michael@0: if (!succeeded) { michael@0: RootedValue val(cx, ObjectValue(*obj)); michael@0: js_ReportValueError(cx, JSMSG_SETPROTOTYPEOF_FAIL, JSDVG_IGNORE_STACK, val, js::NullPtr()); michael@0: return false; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetParent(JSObject *obj) michael@0: { michael@0: JS_ASSERT(!obj->is()); michael@0: return obj->getParent(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetParent(JSContext *cx, HandleObject obj, HandleObject parent) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JS_ASSERT(!obj->is()); michael@0: JS_ASSERT(parent || !obj->getParent()); michael@0: assertSameCompartment(cx, obj, parent); michael@0: michael@0: return JSObject::setParent(cx, obj, parent); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetConstructor(JSContext *cx, HandleObject proto) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, proto); michael@0: michael@0: RootedValue cval(cx); michael@0: if (!JSObject::getProperty(cx, proto, proto, cx->names().constructor, &cval)) michael@0: return nullptr; michael@0: if (!IsFunctionObject(cval)) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR, michael@0: proto->getClass()->name); michael@0: return nullptr; michael@0: } michael@0: return &cval.toObject(); michael@0: } michael@0: michael@0: namespace { michael@0: michael@0: class AutoCompartmentRooter : private JS::CustomAutoRooter michael@0: { michael@0: public: michael@0: explicit AutoCompartmentRooter(JSContext *cx, JSCompartment *comp michael@0: MOZ_GUARD_OBJECT_NOTIFIER_PARAM) michael@0: : CustomAutoRooter(cx), compartment(comp) michael@0: { michael@0: MOZ_GUARD_OBJECT_NOTIFIER_INIT; michael@0: } michael@0: michael@0: operator JSCompartment *() { michael@0: return compartment; michael@0: } michael@0: michael@0: JSCompartment *operator->() { michael@0: return compartment; michael@0: } michael@0: michael@0: protected: michael@0: virtual void trace(JSTracer *trc) michael@0: { michael@0: compartment->mark(); michael@0: } michael@0: michael@0: private: michael@0: JSCompartment *compartment; michael@0: MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER michael@0: }; michael@0: michael@0: } /* anonymous namespace */ michael@0: michael@0: bool michael@0: JS::CompartmentOptions::cloneSingletons(JSContext *cx) const michael@0: { michael@0: return cloneSingletonsOverride_.get(cx->options().cloneSingletons()); michael@0: } michael@0: michael@0: JS::CompartmentOptions & michael@0: JS::CompartmentOptions::setZone(ZoneSpecifier spec) michael@0: { michael@0: zone_.spec = spec; michael@0: return *this; michael@0: } michael@0: michael@0: JS::CompartmentOptions & michael@0: JS::CompartmentOptions::setSameZoneAs(JSObject *obj) michael@0: { michael@0: zone_.pointer = static_cast(obj->zone()); michael@0: return *this; michael@0: } michael@0: michael@0: JS::CompartmentOptions & michael@0: JS::CompartmentOptionsRef(JSCompartment *compartment) michael@0: { michael@0: return compartment->options(); michael@0: } michael@0: michael@0: JS::CompartmentOptions & michael@0: JS::CompartmentOptionsRef(JSObject *obj) michael@0: { michael@0: return obj->compartment()->options(); michael@0: } michael@0: michael@0: JS::CompartmentOptions & michael@0: JS::CompartmentOptionsRef(JSContext *cx) michael@0: { michael@0: return cx->compartment()->options(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewGlobalObject(JSContext *cx, const JSClass *clasp, JSPrincipals *principals, michael@0: JS::OnNewGlobalHookOption hookOption, michael@0: const JS::CompartmentOptions &options /* = JS::CompartmentOptions() */) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: JS_ASSERT(!cx->isExceptionPending()); michael@0: michael@0: JSRuntime *rt = cx->runtime(); michael@0: michael@0: Zone *zone; michael@0: if (options.zoneSpecifier() == JS::SystemZone) michael@0: zone = rt->systemZone; michael@0: else if (options.zoneSpecifier() == JS::FreshZone) michael@0: zone = nullptr; michael@0: else michael@0: zone = static_cast(options.zonePointer()); michael@0: michael@0: AutoCompartmentRooter compartment(cx, NewCompartment(cx, zone, principals, options)); michael@0: if (!compartment) michael@0: return nullptr; michael@0: michael@0: // Lazily create the system zone. michael@0: if (!rt->systemZone && options.zoneSpecifier() == JS::SystemZone) { michael@0: rt->systemZone = compartment->zone(); michael@0: rt->systemZone->isSystem = true; michael@0: } michael@0: michael@0: Rooted global(cx); michael@0: { michael@0: AutoCompartment ac(cx, compartment); michael@0: global = GlobalObject::create(cx, Valueify(clasp)); michael@0: } michael@0: michael@0: if (!global) michael@0: return nullptr; michael@0: michael@0: if (hookOption == JS::FireOnNewGlobalHook) michael@0: JS_FireOnNewGlobalObject(cx, global); michael@0: michael@0: return global; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_GlobalObjectTraceHook(JSTracer *trc, JSObject *global) michael@0: { michael@0: JS_ASSERT(global->is()); michael@0: michael@0: // Off thread parsing and compilation tasks create a dummy global which is then michael@0: // merged back into the host compartment. Since it used to be a global, it will still michael@0: // have this trace hook, but it does not have a meaning relative to its new compartment. michael@0: // We can safely skip it. michael@0: if (!global->isOwnGlobal()) michael@0: return; michael@0: michael@0: // Trace the compartment for any GC things that should only stick around if we know the michael@0: // compartment is live. michael@0: global->compartment()->trace(trc); michael@0: michael@0: JSTraceOp trace = global->compartment()->options().getTrace(); michael@0: if (trace) michael@0: trace(trc, global); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_FireOnNewGlobalObject(JSContext *cx, JS::HandleObject global) michael@0: { michael@0: // This hook is infallible, because we don't really want arbitrary script michael@0: // to be able to throw errors during delicate global creation routines. michael@0: // This infallibility will eat OOM and slow script, but if that happens michael@0: // we'll likely run up into them again soon in a fallible context. michael@0: Rooted globalObject(cx, &global->as()); michael@0: Debugger::onNewGlobalObject(cx, globalObject); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewObject(JSContext *cx, const JSClass *jsclasp, HandleObject proto, HandleObject parent) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, proto, parent); michael@0: michael@0: const Class *clasp = Valueify(jsclasp); michael@0: if (!clasp) michael@0: clasp = &JSObject::class_; /* default class is Object */ michael@0: michael@0: JS_ASSERT(clasp != &JSFunction::class_); michael@0: JS_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL)); michael@0: michael@0: JSObject *obj = NewObjectWithClassProto(cx, clasp, proto, parent); michael@0: JS_ASSERT_IF(obj, obj->getParent()); michael@0: return obj; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewObjectWithGivenProto(JSContext *cx, const JSClass *jsclasp, HandleObject proto, HandleObject parent) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, proto, parent); michael@0: michael@0: const Class *clasp = Valueify(jsclasp); michael@0: if (!clasp) michael@0: clasp = &JSObject::class_; /* default class is Object */ michael@0: michael@0: JS_ASSERT(clasp != &JSFunction::class_); michael@0: JS_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL)); michael@0: michael@0: JSObject *obj = NewObjectWithGivenProto(cx, clasp, proto, parent); michael@0: if (obj) michael@0: MarkTypeObjectUnknownProperties(cx, obj->type()); michael@0: return obj; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewObjectForConstructor(JSContext *cx, const JSClass *clasp, const CallArgs& args) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: Value callee = args.calleev(); michael@0: assertSameCompartment(cx, callee); michael@0: RootedObject obj(cx, &callee.toObject()); michael@0: return CreateThis(cx, Valueify(clasp), obj); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsExtensible(JSContext *cx, HandleObject obj, bool *extensible) michael@0: { michael@0: return JSObject::isExtensible(cx, obj, extensible); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsNative(JSObject *obj) michael@0: { michael@0: return obj->isNative(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSRuntime *) michael@0: JS_GetObjectRuntime(JSObject *obj) michael@0: { michael@0: return obj->compartment()->runtimeFromMainThread(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_FreezeObject(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: return JSObject::freeze(cx, obj); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeepFreezeObject(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: /* Assume that non-extensible objects are already deep-frozen, to avoid divergence. */ michael@0: bool extensible; michael@0: if (!JSObject::isExtensible(cx, obj, &extensible)) michael@0: return false; michael@0: if (!extensible) michael@0: return true; michael@0: michael@0: if (!JSObject::freeze(cx, obj)) michael@0: return false; michael@0: michael@0: /* Walk slots in obj and if any value is a non-null object, seal it. */ michael@0: for (uint32_t i = 0, n = obj->slotSpan(); i < n; ++i) { michael@0: const Value &v = obj->getSlot(i); michael@0: if (v.isPrimitive()) michael@0: continue; michael@0: RootedObject obj(cx, &v.toObject()); michael@0: if (!JS_DeepFreezeObject(cx, obj)) michael@0: return false; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: static bool michael@0: LookupPropertyById(JSContext *cx, HandleObject obj, HandleId id, michael@0: MutableHandleObject objp, MutableHandleShape propp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, id); michael@0: michael@0: return JSObject::lookupGeneric(cx, obj, id, objp, propp); michael@0: } michael@0: michael@0: #define AUTO_NAMELEN(s,n) (((n) == (size_t)-1) ? js_strlen(s) : (n)) michael@0: michael@0: static bool michael@0: LookupResult(JSContext *cx, HandleObject obj, HandleObject obj2, HandleId id, michael@0: HandleShape shape, MutableHandleValue vp) michael@0: { michael@0: if (!shape) { michael@0: /* XXX bad API: no way to tell "not defined" from "void value" */ michael@0: vp.setUndefined(); michael@0: return true; michael@0: } michael@0: michael@0: if (!obj2->isNative()) { michael@0: if (obj2->is()) { michael@0: Rooted desc(cx); michael@0: if (!Proxy::getPropertyDescriptor(cx, obj2, id, &desc)) michael@0: return false; michael@0: if (!desc.isShared()) { michael@0: vp.set(desc.value()); michael@0: return true; michael@0: } michael@0: } michael@0: } else if (IsImplicitDenseOrTypedArrayElement(shape)) { michael@0: vp.set(obj2->getDenseOrTypedArrayElement(JSID_TO_INT(id))); michael@0: return true; michael@0: } else { michael@0: /* Peek at the native property's slot value, without doing a Get. */ michael@0: if (shape->hasSlot()) { michael@0: vp.set(obj2->nativeGetSlot(shape->slot())); michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: /* XXX bad API: no way to return "defined but value unknown" */ michael@0: vp.setBoolean(true); michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_LookupPropertyById(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp) michael@0: { michael@0: RootedObject obj2(cx); michael@0: RootedShape prop(cx); michael@0: michael@0: return LookupPropertyById(cx, obj, id, &obj2, &prop) && michael@0: LookupResult(cx, obj, obj2, id, prop, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_LookupElement(JSContext *cx, HandleObject obj, uint32_t index, MutableHandleValue vp) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: RootedId id(cx); michael@0: if (!IndexToId(cx, index, &id)) michael@0: return false; michael@0: return JS_LookupPropertyById(cx, obj, id, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_LookupProperty(JSContext *cx, HandleObject objArg, const char *name, MutableHandleValue vp) michael@0: { michael@0: RootedObject obj(cx, objArg); michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_LookupPropertyById(cx, obj, id, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_LookupUCProperty(JSContext *cx, HandleObject objArg, const jschar *name, size_t namelen, michael@0: MutableHandleValue vp) michael@0: { michael@0: RootedObject obj(cx, objArg); michael@0: JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); michael@0: if (!atom) michael@0: return false; michael@0: michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_LookupPropertyById(cx, obj, id, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_HasPropertyById(JSContext *cx, HandleObject obj, HandleId id, bool *foundp) michael@0: { michael@0: RootedObject obj2(cx); michael@0: RootedShape prop(cx); michael@0: bool ok = LookupPropertyById(cx, obj, id, &obj2, &prop); michael@0: *foundp = (prop != nullptr); michael@0: return ok; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_HasElement(JSContext *cx, HandleObject obj, uint32_t index, bool *foundp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: RootedId id(cx); michael@0: if (!IndexToId(cx, index, &id)) michael@0: return false; michael@0: return JS_HasPropertyById(cx, obj, id, foundp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_HasProperty(JSContext *cx, HandleObject obj, const char *name, bool *foundp) michael@0: { michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_HasPropertyById(cx, obj, id, foundp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_HasUCProperty(JSContext *cx, HandleObject obj, const jschar *name, size_t namelen, bool *foundp) michael@0: { michael@0: JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_HasPropertyById(cx, obj, id, foundp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_AlreadyHasOwnPropertyById(JSContext *cx, HandleObject obj, HandleId id, bool *foundp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, id); michael@0: michael@0: if (!obj->isNative()) { michael@0: RootedObject obj2(cx); michael@0: RootedShape prop(cx); michael@0: michael@0: if (!LookupPropertyById(cx, obj, id, &obj2, &prop)) michael@0: return false; michael@0: *foundp = (obj == obj2); michael@0: return true; michael@0: } michael@0: michael@0: // Check for an existing native property on the objct. Be careful not to michael@0: // call any lookup or resolve hooks. michael@0: michael@0: if (JSID_IS_INT(id)) { michael@0: uint32_t index = JSID_TO_INT(id); michael@0: michael@0: if (obj->containsDenseElement(index)) { michael@0: *foundp = true; michael@0: return true; michael@0: } michael@0: michael@0: if (obj->is() && index < obj->as().length()) { michael@0: *foundp = true; michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: *foundp = obj->nativeContains(cx, id); michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_AlreadyHasOwnElement(JSContext *cx, HandleObject obj, uint32_t index, bool *foundp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: RootedId id(cx); michael@0: if (!IndexToId(cx, index, &id)) michael@0: return false; michael@0: return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_AlreadyHasOwnProperty(JSContext *cx, HandleObject obj, const char *name, bool *foundp) michael@0: { michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_AlreadyHasOwnUCProperty(JSContext *cx, HandleObject obj, const jschar *name, size_t namelen, michael@0: bool *foundp) michael@0: { michael@0: JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp); michael@0: } michael@0: michael@0: /* Wrapper functions to create wrappers with no corresponding JSJitInfo from API michael@0: * function arguments. michael@0: */ michael@0: static JSPropertyOpWrapper michael@0: GetterWrapper(JSPropertyOp getter) michael@0: { michael@0: JSPropertyOpWrapper ret; michael@0: ret.op = getter; michael@0: ret.info = nullptr; michael@0: return ret; michael@0: } michael@0: michael@0: static JSStrictPropertyOpWrapper michael@0: SetterWrapper(JSStrictPropertyOp setter) michael@0: { michael@0: JSStrictPropertyOpWrapper ret; michael@0: ret.op = setter; michael@0: ret.info = nullptr; michael@0: return ret; michael@0: } michael@0: michael@0: static bool michael@0: DefinePropertyById(JSContext *cx, HandleObject obj, HandleId id, HandleValue value, michael@0: const JSPropertyOpWrapper &get, const JSStrictPropertyOpWrapper &set, michael@0: unsigned attrs, unsigned flags) michael@0: { michael@0: PropertyOp getter = get.op; michael@0: StrictPropertyOp setter = set.op; michael@0: /* michael@0: * JSPROP_READONLY has no meaning when accessors are involved. Ideally we'd michael@0: * throw if this happens, but we've accepted it for long enough that it's michael@0: * not worth trying to make callers change their ways. Just flip it off on michael@0: * its way through the API layer so that we can enforce this internally. michael@0: */ michael@0: if (attrs & (JSPROP_GETTER | JSPROP_SETTER)) michael@0: attrs &= ~JSPROP_READONLY; michael@0: michael@0: /* michael@0: * When we use DefineProperty, we need full scriptable Function objects rather michael@0: * than JSNatives. However, we might be pulling this property descriptor off michael@0: * of something with JSNative property descriptors. If we are, wrap them in michael@0: * JS Function objects. michael@0: */ michael@0: if (attrs & JSPROP_NATIVE_ACCESSORS) { michael@0: JS_ASSERT(!(attrs & (JSPROP_GETTER | JSPROP_SETTER))); michael@0: JSFunction::Flags zeroFlags = JSAPIToJSFunctionFlags(0); michael@0: // We can't just use JS_NewFunctionById here because it michael@0: // assumes a string id. michael@0: RootedAtom atom(cx, JSID_IS_ATOM(id) ? JSID_TO_ATOM(id) : nullptr); michael@0: attrs &= ~JSPROP_NATIVE_ACCESSORS; michael@0: if (getter) { michael@0: RootedObject global(cx, (JSObject*) &obj->global()); michael@0: JSFunction *getobj = NewFunction(cx, NullPtr(), (Native) getter, 0, michael@0: zeroFlags, global, atom); michael@0: if (!getobj) michael@0: return false; michael@0: michael@0: if (get.info) michael@0: getobj->setJitInfo(get.info); michael@0: michael@0: getter = JS_DATA_TO_FUNC_PTR(PropertyOp, getobj); michael@0: attrs |= JSPROP_GETTER; michael@0: } michael@0: if (setter) { michael@0: // Root just the getter, since the setter is not yet a JSObject. michael@0: AutoRooterGetterSetter getRoot(cx, JSPROP_GETTER, &getter, nullptr); michael@0: RootedObject global(cx, (JSObject*) &obj->global()); michael@0: JSFunction *setobj = NewFunction(cx, NullPtr(), (Native) setter, 1, michael@0: zeroFlags, global, atom); michael@0: if (!setobj) michael@0: return false; michael@0: michael@0: if (set.info) michael@0: setobj->setJitInfo(set.info); michael@0: michael@0: setter = JS_DATA_TO_FUNC_PTR(StrictPropertyOp, setobj); michael@0: attrs |= JSPROP_SETTER; michael@0: } michael@0: } michael@0: michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, id, value, michael@0: (attrs & JSPROP_GETTER) michael@0: ? JS_FUNC_TO_DATA_PTR(JSObject *, getter) michael@0: : nullptr, michael@0: (attrs & JSPROP_SETTER) michael@0: ? JS_FUNC_TO_DATA_PTR(JSObject *, setter) michael@0: : nullptr); michael@0: michael@0: return JSObject::defineGeneric(cx, obj, id, value, getter, setter, attrs); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefinePropertyById(JSContext *cx, JSObject *objArg, jsid idArg, jsval valueArg, michael@0: JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) michael@0: { michael@0: RootedObject obj(cx, objArg); michael@0: RootedId id(cx, idArg); michael@0: RootedValue value(cx, valueArg); michael@0: return DefinePropertyById(cx, obj, id, value, GetterWrapper(getter), SetterWrapper(setter), michael@0: attrs, 0); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineElement(JSContext *cx, JSObject *objArg, uint32_t index, jsval valueArg, michael@0: JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) michael@0: { michael@0: RootedObject obj(cx, objArg); michael@0: RootedValue value(cx, valueArg); michael@0: AutoRooterGetterSetter gsRoot(cx, attrs, &getter, &setter); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: RootedId id(cx); michael@0: if (!IndexToId(cx, index, &id)) michael@0: return false; michael@0: return DefinePropertyById(cx, obj, id, value, GetterWrapper(getter), SetterWrapper(setter), michael@0: attrs, 0); michael@0: } michael@0: michael@0: static bool michael@0: DefineProperty(JSContext *cx, HandleObject obj, const char *name, HandleValue value, michael@0: const JSPropertyOpWrapper &getter, const JSStrictPropertyOpWrapper &setter, michael@0: unsigned attrs, unsigned flags) michael@0: { michael@0: AutoRooterGetterSetter gsRoot(cx, attrs, const_cast(&getter.op), michael@0: const_cast(&setter.op)); michael@0: michael@0: RootedId id(cx); michael@0: if (attrs & JSPROP_INDEX) { michael@0: id.set(INT_TO_JSID(intptr_t(name))); michael@0: attrs &= ~JSPROP_INDEX; michael@0: } else { michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: id = AtomToId(atom); michael@0: } michael@0: michael@0: return DefinePropertyById(cx, obj, id, value, getter, setter, attrs, flags); michael@0: } michael@0: michael@0: michael@0: static bool michael@0: DefineSelfHostedProperty(JSContext *cx, michael@0: HandleObject obj, michael@0: const char *name, michael@0: const char *getterName, michael@0: const char *setterName, michael@0: unsigned attrs, michael@0: unsigned flags) michael@0: { michael@0: RootedAtom nameAtom(cx, Atomize(cx, name, strlen(name))); michael@0: if (!nameAtom) michael@0: return false; michael@0: michael@0: RootedAtom getterNameAtom(cx, Atomize(cx, getterName, strlen(getterName))); michael@0: if (!getterNameAtom) michael@0: return false; michael@0: michael@0: RootedValue getterValue(cx); michael@0: if (!cx->global()->getSelfHostedFunction(cx, getterNameAtom, nameAtom, michael@0: 0, &getterValue)) michael@0: { michael@0: return false; michael@0: } michael@0: JS_ASSERT(getterValue.isObject() && getterValue.toObject().is()); michael@0: RootedFunction getterFunc(cx, &getterValue.toObject().as()); michael@0: JSPropertyOp getterOp = JS_DATA_TO_FUNC_PTR(PropertyOp, getterFunc.get()); michael@0: michael@0: RootedFunction setterFunc(cx); michael@0: if (setterName) { michael@0: RootedAtom setterNameAtom(cx, Atomize(cx, setterName, strlen(setterName))); michael@0: if (!setterNameAtom) michael@0: return false; michael@0: michael@0: RootedValue setterValue(cx); michael@0: if (!cx->global()->getSelfHostedFunction(cx, setterNameAtom, nameAtom, michael@0: 0, &setterValue)) michael@0: { michael@0: return false; michael@0: } michael@0: JS_ASSERT(setterValue.isObject() && setterValue.toObject().is()); michael@0: setterFunc = &getterValue.toObject().as(); michael@0: } michael@0: JSStrictPropertyOp setterOp = JS_DATA_TO_FUNC_PTR(StrictPropertyOp, setterFunc.get()); michael@0: michael@0: return DefineProperty(cx, obj, name, JS::UndefinedHandleValue, michael@0: GetterWrapper(getterOp), SetterWrapper(setterOp), michael@0: attrs, flags); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineProperty(JSContext *cx, HandleObject obj, const char *name, HandleValue value, michael@0: unsigned attrs, michael@0: PropertyOp getter /* = nullptr */, JSStrictPropertyOp setter /* = nullptr */) michael@0: { michael@0: return DefineProperty(cx, obj, name, value, GetterWrapper(getter), SetterWrapper(setter), michael@0: attrs, 0); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineProperty(JSContext *cx, HandleObject obj, const char *name, HandleObject valueArg, michael@0: unsigned attrs, michael@0: PropertyOp getter /* = nullptr */, JSStrictPropertyOp setter /* = nullptr */) michael@0: { michael@0: RootedValue value(cx, ObjectValue(*valueArg)); michael@0: return DefineProperty(cx, obj, name, value, GetterWrapper(getter), SetterWrapper(setter), michael@0: attrs, 0); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineProperty(JSContext *cx, HandleObject obj, const char *name, HandleString valueArg, michael@0: unsigned attrs, michael@0: PropertyOp getter /* = nullptr */, JSStrictPropertyOp setter /* = nullptr */) michael@0: { michael@0: RootedValue value(cx, StringValue(valueArg)); michael@0: return DefineProperty(cx, obj, name, value, GetterWrapper(getter), SetterWrapper(setter), michael@0: attrs, 0); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineProperty(JSContext *cx, HandleObject obj, const char *name, int32_t valueArg, michael@0: unsigned attrs, michael@0: PropertyOp getter /* = nullptr */, JSStrictPropertyOp setter /* = nullptr */) michael@0: { michael@0: Value value = Int32Value(valueArg); michael@0: return DefineProperty(cx, obj, name, HandleValue::fromMarkedLocation(&value), michael@0: GetterWrapper(getter), SetterWrapper(setter), attrs, 0); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineProperty(JSContext *cx, HandleObject obj, const char *name, uint32_t valueArg, michael@0: unsigned attrs, michael@0: PropertyOp getter /* = nullptr */, JSStrictPropertyOp setter /* = nullptr */) michael@0: { michael@0: Value value = UINT_TO_JSVAL(valueArg); michael@0: return DefineProperty(cx, obj, name, HandleValue::fromMarkedLocation(&value), michael@0: GetterWrapper(getter), SetterWrapper(setter), attrs, 0); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineProperty(JSContext *cx, HandleObject obj, const char *name, double valueArg, michael@0: unsigned attrs, michael@0: PropertyOp getter /* = nullptr */, JSStrictPropertyOp setter /* = nullptr */) michael@0: { michael@0: Value value = NumberValue(valueArg); michael@0: return DefineProperty(cx, obj, name, HandleValue::fromMarkedLocation(&value), michael@0: GetterWrapper(getter), SetterWrapper(setter), attrs, 0); michael@0: } michael@0: michael@0: static bool michael@0: DefineUCProperty(JSContext *cx, HandleObject obj, const jschar *name, size_t namelen, michael@0: const Value &value_, PropertyOp getter, StrictPropertyOp setter, unsigned attrs, michael@0: unsigned flags) michael@0: { michael@0: RootedValue value(cx, value_); michael@0: AutoRooterGetterSetter gsRoot(cx, attrs, &getter, &setter); michael@0: JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return DefinePropertyById(cx, obj, id, value, GetterWrapper(getter), SetterWrapper(setter), michael@0: attrs, flags); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineUCProperty(JSContext *cx, JSObject *objArg, const jschar *name, size_t namelen, michael@0: jsval valueArg, JSPropertyOp getter, JSStrictPropertyOp setter, unsigned attrs) michael@0: { michael@0: RootedObject obj(cx, objArg); michael@0: RootedValue value(cx, valueArg); michael@0: return DefineUCProperty(cx, obj, name, namelen, value, getter, setter, attrs, 0); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineOwnProperty(JSContext *cx, HandleObject obj, HandleId id, HandleValue descriptor, bool *bp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, id, descriptor); michael@0: michael@0: return DefineOwnProperty(cx, obj, id, descriptor, bp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_DefineObject(JSContext *cx, JSObject *objArg, const char *name, const JSClass *jsclasp, michael@0: JSObject *protoArg, unsigned attrs) michael@0: { michael@0: RootedObject obj(cx, objArg); michael@0: RootedObject proto(cx, protoArg); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, proto); michael@0: michael@0: const Class *clasp = Valueify(jsclasp); michael@0: if (!clasp) michael@0: clasp = &JSObject::class_; /* default class is Object */ michael@0: michael@0: RootedObject nobj(cx, NewObjectWithClassProto(cx, clasp, proto, obj)); michael@0: if (!nobj) michael@0: return nullptr; michael@0: michael@0: RootedValue nobjValue(cx, ObjectValue(*nobj)); michael@0: if (!DefineProperty(cx, obj, name, nobjValue, GetterWrapper(nullptr), SetterWrapper(nullptr), michael@0: attrs, 0)) { michael@0: return nullptr; michael@0: } michael@0: michael@0: return nobj; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineConstDoubles(JSContext *cx, HandleObject obj, const JSConstDoubleSpec *cds) michael@0: { michael@0: bool ok; michael@0: unsigned attrs; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JSPropertyOpWrapper noget = GetterWrapper(nullptr); michael@0: JSStrictPropertyOpWrapper noset = SetterWrapper(nullptr); michael@0: for (ok = true; cds->name; cds++) { michael@0: RootedValue value(cx, DoubleValue(cds->dval)); michael@0: attrs = cds->flags; michael@0: if (!attrs) michael@0: attrs = JSPROP_READONLY | JSPROP_PERMANENT; michael@0: ok = DefineProperty(cx, obj, cds->name, value, noget, noset, attrs, 0); michael@0: if (!ok) michael@0: break; michael@0: } michael@0: return ok; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineProperties(JSContext *cx, HandleObject obj, const JSPropertySpec *ps) michael@0: { michael@0: bool ok; michael@0: for (ok = true; ps->name; ps++) { michael@0: if (ps->flags & JSPROP_NATIVE_ACCESSORS) { michael@0: // If you declare native accessors, then you should have a native michael@0: // getter. michael@0: JS_ASSERT(ps->getter.propertyOp.op); michael@0: // If you do not have a self-hosted getter, you should not have a michael@0: // self-hosted setter. This is the closest approximation to that michael@0: // assertion we can have with our setup. michael@0: JS_ASSERT_IF(ps->setter.propertyOp.info, ps->setter.propertyOp.op); michael@0: michael@0: ok = DefineProperty(cx, obj, ps->name, JS::UndefinedHandleValue, michael@0: ps->getter.propertyOp, ps->setter.propertyOp, ps->flags, 0); michael@0: } else { michael@0: // If you have self-hosted getter/setter, you can't have a michael@0: // native one. michael@0: JS_ASSERT(!ps->getter.propertyOp.op && !ps->setter.propertyOp.op); michael@0: JS_ASSERT(ps->flags & JSPROP_GETTER); michael@0: /* michael@0: * During creation of the self-hosting global, we ignore all michael@0: * self-hosted properties, as that means we're currently setting up michael@0: * the global object that the self-hosted code is then compiled michael@0: * in. That means that Self-hosted properties can't be used in the michael@0: * self-hosting global itself, right now. michael@0: */ michael@0: if (cx->runtime()->isSelfHostingGlobal(cx->global())) michael@0: continue; michael@0: michael@0: ok = DefineSelfHostedProperty(cx, obj, ps->name, michael@0: ps->getter.selfHosted.funname, michael@0: ps->setter.selfHosted.funname, michael@0: ps->flags, 0); michael@0: } michael@0: if (!ok) michael@0: break; michael@0: } michael@0: return ok; michael@0: } michael@0: michael@0: static bool michael@0: GetPropertyDescriptorById(JSContext *cx, HandleObject obj, HandleId id, michael@0: MutableHandle desc) michael@0: { michael@0: RootedObject obj2(cx); michael@0: RootedShape shape(cx); michael@0: michael@0: if (!LookupPropertyById(cx, obj, id, &obj2, &shape)) michael@0: return false; michael@0: michael@0: desc.clear(); michael@0: if (!shape) michael@0: return true; michael@0: michael@0: desc.object().set(obj2); michael@0: if (obj2->isNative()) { michael@0: if (IsImplicitDenseOrTypedArrayElement(shape)) { michael@0: desc.setEnumerable(); michael@0: desc.value().set(obj2->getDenseOrTypedArrayElement(JSID_TO_INT(id))); michael@0: } else { michael@0: desc.setAttributes(shape->attributes()); michael@0: desc.setGetter(shape->getter()); michael@0: desc.setSetter(shape->setter()); michael@0: JS_ASSERT(desc.value().isUndefined()); michael@0: if (shape->hasSlot()) michael@0: desc.value().set(obj2->nativeGetSlot(shape->slot())); michael@0: } michael@0: } else { michael@0: if (obj2->is()) michael@0: return Proxy::getPropertyDescriptor(cx, obj2, id, desc); michael@0: if (!JSObject::getGenericAttributes(cx, obj2, id, &desc.attributesRef())) michael@0: return false; michael@0: JS_ASSERT(desc.getter() == nullptr); michael@0: JS_ASSERT(desc.setter() == nullptr); michael@0: JS_ASSERT(desc.value().isUndefined()); michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetOwnPropertyDescriptorById(JSContext *cx, HandleObject obj, HandleId id, michael@0: MutableHandle desc) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: return GetOwnPropertyDescriptor(cx, obj, id, desc); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetOwnPropertyDescriptor(JSContext *cx, HandleObject obj, const char *name, michael@0: MutableHandle desc) michael@0: { michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_GetOwnPropertyDescriptorById(cx, obj, id, desc); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetPropertyDescriptorById(JSContext *cx, HandleObject obj, HandleId id, michael@0: MutableHandle desc) michael@0: { michael@0: return GetPropertyDescriptorById(cx, obj, id, desc); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetPropertyDescriptor(JSContext *cx, HandleObject obj, const char *name, michael@0: MutableHandle desc) michael@0: { michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return atom && JS_GetPropertyDescriptorById(cx, obj, id, desc); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetPropertyById(JSContext *cx, HandleObject obj, HandleId id, MutableHandleValue vp) michael@0: { michael@0: return JS_ForwardGetPropertyTo(cx, obj, id, obj, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ForwardGetPropertyTo(JSContext *cx, JS::HandleObject obj, JS::HandleId id, JS::HandleObject onBehalfOf, michael@0: JS::MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, id); michael@0: assertSameCompartment(cx, onBehalfOf); michael@0: michael@0: return JSObject::getGeneric(cx, obj, onBehalfOf, id, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetElement(JSContext *cx, HandleObject objArg, uint32_t index, MutableHandleValue vp) michael@0: { michael@0: return JS_ForwardGetElementTo(cx, objArg, index, objArg, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ForwardGetElementTo(JSContext *cx, HandleObject obj, uint32_t index, HandleObject onBehalfOf, michael@0: MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: return JSObject::getElement(cx, obj, onBehalfOf, index, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetProperty(JSContext *cx, HandleObject obj, const char *name, MutableHandleValue vp) michael@0: { michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_GetPropertyById(cx, obj, id, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetUCProperty(JSContext *cx, HandleObject obj, const jschar *name, size_t namelen, michael@0: MutableHandleValue vp) michael@0: { michael@0: JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_GetPropertyById(cx, obj, id, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetPropertyById(JSContext *cx, HandleObject obj, HandleId id, HandleValue v) michael@0: { michael@0: RootedValue value(cx, v); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, id); michael@0: michael@0: return JSObject::setGeneric(cx, obj, obj, id, &value, false); michael@0: } michael@0: michael@0: static bool michael@0: SetElement(JSContext *cx, HandleObject obj, uint32_t index, MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, vp); michael@0: michael@0: return JSObject::setElement(cx, obj, obj, index, vp, false); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetElement(JSContext *cx, HandleObject obj, uint32_t index, HandleValue v) michael@0: { michael@0: RootedValue value(cx, v); michael@0: return SetElement(cx, obj, index, &value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetElement(JSContext *cx, HandleObject obj, uint32_t index, HandleObject v) michael@0: { michael@0: RootedValue value(cx, ObjectOrNullValue(v)); michael@0: return SetElement(cx, obj, index, &value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetElement(JSContext *cx, HandleObject obj, uint32_t index, HandleString v) michael@0: { michael@0: RootedValue value(cx, StringValue(v)); michael@0: return SetElement(cx, obj, index, &value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetElement(JSContext *cx, HandleObject obj, uint32_t index, int32_t v) michael@0: { michael@0: RootedValue value(cx, NumberValue(v)); michael@0: return SetElement(cx, obj, index, &value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetElement(JSContext *cx, HandleObject obj, uint32_t index, uint32_t v) michael@0: { michael@0: RootedValue value(cx, NumberValue(v)); michael@0: return SetElement(cx, obj, index, &value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetElement(JSContext *cx, HandleObject obj, uint32_t index, double v) michael@0: { michael@0: RootedValue value(cx, NumberValue(v)); michael@0: return SetElement(cx, obj, index, &value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetProperty(JSContext *cx, HandleObject obj, const char *name, HandleValue v) michael@0: { michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_SetPropertyById(cx, obj, id, v); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetUCProperty(JSContext *cx, HandleObject obj, const jschar *name, size_t namelen, michael@0: HandleValue v) michael@0: { michael@0: JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); michael@0: if (!atom) michael@0: return false; michael@0: RootedId id(cx, AtomToId(atom)); michael@0: return JS_SetPropertyById(cx, obj, id, v); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeletePropertyById2(JSContext *cx, HandleObject obj, HandleId id, bool *result) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, id); michael@0: michael@0: return JSObject::deleteByValue(cx, obj, IdToValue(id), result); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeleteElement2(JSContext *cx, HandleObject obj, uint32_t index, bool *result) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: return JSObject::deleteElement(cx, obj, index, result); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeleteProperty2(JSContext *cx, HandleObject obj, const char *name, bool *result) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: return JSObject::deleteByValue(cx, obj, StringValue(atom), result); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeleteUCProperty2(JSContext *cx, HandleObject obj, const jschar *name, size_t namelen, michael@0: bool *result) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); michael@0: if (!atom) michael@0: return false; michael@0: return JSObject::deleteByValue(cx, obj, StringValue(atom), result); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeletePropertyById(JSContext *cx, HandleObject obj, HandleId id) michael@0: { michael@0: bool junk; michael@0: return JS_DeletePropertyById2(cx, obj, id, &junk); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeleteElement(JSContext *cx, HandleObject obj, uint32_t index) michael@0: { michael@0: bool junk; michael@0: return JS_DeleteElement2(cx, obj, index, &junk); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DeleteProperty(JSContext *cx, HandleObject obj, const char *name) michael@0: { michael@0: bool junk; michael@0: return JS_DeleteProperty2(cx, obj, name, &junk); michael@0: } michael@0: michael@0: static Shape * michael@0: LastConfigurableShape(JSObject *obj) michael@0: { michael@0: for (Shape::Range r(obj->lastProperty()); !r.empty(); r.popFront()) { michael@0: Shape *shape = &r.front(); michael@0: if (shape->configurable()) michael@0: return shape; michael@0: } michael@0: return nullptr; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ClearNonGlobalObject(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: JS_ASSERT(!obj->is()); michael@0: michael@0: if (!obj->isNative()) michael@0: return; michael@0: michael@0: /* Remove all configurable properties from obj. */ michael@0: RootedShape shape(cx); michael@0: while ((shape = LastConfigurableShape(obj))) { michael@0: if (!obj->removeProperty(cx, shape->propid())) michael@0: return; michael@0: } michael@0: michael@0: /* Set all remaining writable plain data properties to undefined. */ michael@0: for (Shape::Range r(obj->lastProperty()); !r.empty(); r.popFront()) { michael@0: Shape *shape = &r.front(); michael@0: if (shape->isDataDescriptor() && michael@0: shape->writable() && michael@0: shape->hasDefaultSetter() && michael@0: shape->hasSlot()) michael@0: { michael@0: obj->nativeSetSlot(shape->slot(), UndefinedValue()); michael@0: } michael@0: } michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetAllNonReservedSlotsToUndefined(JSContext *cx, JSObject *objArg) michael@0: { michael@0: RootedObject obj(cx, objArg); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: if (!obj->isNative()) michael@0: return; michael@0: michael@0: const Class *clasp = obj->getClass(); michael@0: unsigned numReserved = JSCLASS_RESERVED_SLOTS(clasp); michael@0: unsigned numSlots = obj->slotSpan(); michael@0: for (unsigned i = numReserved; i < numSlots; i++) michael@0: obj->setSlot(i, UndefinedValue()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSIdArray *) michael@0: JS_Enumerate(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: AutoIdVector props(cx); michael@0: JSIdArray *ida; michael@0: if (!GetPropertyNames(cx, obj, JSITER_OWNONLY, &props) || !VectorToIdArray(cx, props, &ida)) michael@0: return nullptr; michael@0: return ida; michael@0: } michael@0: michael@0: /* michael@0: * XXX reverse iterator for properties, unreverse and meld with jsinterp.c's michael@0: * prop_iterator_class somehow... michael@0: * + preserve the obj->enumerate API while optimizing the native object case michael@0: * + native case here uses a JSShape *, but that iterates in reverse! michael@0: * + so we make non-native match, by reverse-iterating after JS_Enumerating michael@0: */ michael@0: static const uint32_t JSSLOT_ITER_INDEX = 0; michael@0: michael@0: static void michael@0: prop_iter_finalize(FreeOp *fop, JSObject *obj) michael@0: { michael@0: void *pdata = obj->getPrivate(); michael@0: if (!pdata) michael@0: return; michael@0: michael@0: if (obj->getSlot(JSSLOT_ITER_INDEX).toInt32() >= 0) { michael@0: /* Non-native case: destroy the ida enumerated when obj was created. */ michael@0: JSIdArray *ida = (JSIdArray *) pdata; michael@0: fop->free_(ida); michael@0: } michael@0: } michael@0: michael@0: static void michael@0: prop_iter_trace(JSTracer *trc, JSObject *obj) michael@0: { michael@0: void *pdata = obj->getPrivate(); michael@0: if (!pdata) michael@0: return; michael@0: michael@0: if (obj->getSlot(JSSLOT_ITER_INDEX).toInt32() < 0) { michael@0: /* michael@0: * Native case: just mark the next property to visit. We don't need a michael@0: * barrier here because the pointer is updated via setPrivate, which michael@0: * always takes a barrier. michael@0: */ michael@0: Shape *tmp = static_cast(pdata); michael@0: MarkShapeUnbarriered(trc, &tmp, "prop iter shape"); michael@0: obj->setPrivateUnbarriered(tmp); michael@0: } else { michael@0: /* Non-native case: mark each id in the JSIdArray private. */ michael@0: JSIdArray *ida = (JSIdArray *) pdata; michael@0: MarkIdRange(trc, ida->length, ida->vector, "prop iter"); michael@0: } michael@0: } michael@0: michael@0: static const Class prop_iter_class = { michael@0: "PropertyIterator", michael@0: JSCLASS_HAS_PRIVATE | JSCLASS_IMPLEMENTS_BARRIERS | JSCLASS_HAS_RESERVED_SLOTS(1), michael@0: JS_PropertyStub, /* addProperty */ michael@0: JS_DeletePropertyStub, /* delProperty */ michael@0: JS_PropertyStub, /* getProperty */ michael@0: JS_StrictPropertyStub, /* setProperty */ michael@0: JS_EnumerateStub, michael@0: JS_ResolveStub, michael@0: JS_ConvertStub, michael@0: prop_iter_finalize, michael@0: nullptr, /* call */ michael@0: nullptr, /* hasInstance */ michael@0: nullptr, /* construct */ michael@0: prop_iter_trace michael@0: }; michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewPropertyIterator(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: RootedObject iterobj(cx, NewObjectWithClassProto(cx, &prop_iter_class, nullptr, obj)); michael@0: if (!iterobj) michael@0: return nullptr; michael@0: michael@0: int index; michael@0: if (obj->isNative()) { michael@0: /* Native case: start with the last property in obj. */ michael@0: iterobj->setPrivateGCThing(obj->lastProperty()); michael@0: index = -1; michael@0: } else { michael@0: /* Non-native case: enumerate a JSIdArray and keep it via private. */ michael@0: JSIdArray *ida = JS_Enumerate(cx, obj); michael@0: if (!ida) michael@0: return nullptr; michael@0: iterobj->setPrivate((void *)ida); michael@0: index = ida->length; michael@0: } michael@0: michael@0: /* iterobj cannot escape to other threads here. */ michael@0: iterobj->setSlot(JSSLOT_ITER_INDEX, Int32Value(index)); michael@0: return iterobj; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_NextProperty(JSContext *cx, HandleObject iterobj, jsid *idp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, iterobj); michael@0: int32_t i = iterobj->getSlot(JSSLOT_ITER_INDEX).toInt32(); michael@0: if (i < 0) { michael@0: /* Native case: private data is a property tree node pointer. */ michael@0: JS_ASSERT(iterobj->getParent()->isNative()); michael@0: Shape *shape = static_cast(iterobj->getPrivate()); michael@0: michael@0: while (shape->previous() && !shape->enumerable()) michael@0: shape = shape->previous(); michael@0: michael@0: if (!shape->previous()) { michael@0: JS_ASSERT(shape->isEmptyShape()); michael@0: *idp = JSID_VOID; michael@0: } else { michael@0: iterobj->setPrivateGCThing(const_cast(shape->previous().get())); michael@0: *idp = shape->propid(); michael@0: } michael@0: } else { michael@0: /* Non-native case: use the ida enumerated when iterobj was created. */ michael@0: JSIdArray *ida = (JSIdArray *) iterobj->getPrivate(); michael@0: JS_ASSERT(i <= ida->length); michael@0: STATIC_ASSUME(i <= ida->length); michael@0: if (i == 0) { michael@0: *idp = JSID_VOID; michael@0: } else { michael@0: *idp = ida->vector[--i]; michael@0: iterobj->setSlot(JSSLOT_ITER_INDEX, Int32Value(i)); michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(jsval) michael@0: JS_GetReservedSlot(JSObject *obj, uint32_t index) michael@0: { michael@0: return obj->getReservedSlot(index); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetReservedSlot(JSObject *obj, uint32_t index, Value value) michael@0: { michael@0: obj->setReservedSlot(index, value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewArrayObject(JSContext *cx, const JS::HandleValueArray& contents) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: assertSameCompartment(cx, contents); michael@0: return NewDenseCopiedArray(cx, contents.length(), contents.begin()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewArrayObject(JSContext *cx, size_t length) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: return NewDenseAllocatedArray(cx, length); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsArrayObject(JSContext *cx, JS::HandleObject obj) michael@0: { michael@0: assertSameCompartment(cx, obj); michael@0: return ObjectClassIs(obj, ESClass_Array, cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsArrayObject(JSContext *cx, JS::HandleValue value) michael@0: { michael@0: if (!value.isObject()) michael@0: return false; michael@0: RootedObject obj(cx, &value.toObject()); michael@0: return JS_IsArrayObject(cx, obj); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetArrayLength(JSContext *cx, HandleObject obj, uint32_t *lengthp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: return GetLengthProperty(cx, obj, lengthp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetArrayLength(JSContext *cx, HandleObject obj, uint32_t length) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: return SetLengthProperty(cx, obj, length); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_HoldPrincipals(JSPrincipals *principals) michael@0: { michael@0: ++principals->refcount; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_DropPrincipals(JSRuntime *rt, JSPrincipals *principals) michael@0: { michael@0: int rc = --principals->refcount; michael@0: if (rc == 0) michael@0: rt->destroyPrincipals(principals); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetSecurityCallbacks(JSRuntime *rt, const JSSecurityCallbacks *scb) michael@0: { michael@0: JS_ASSERT(scb != &NullSecurityCallbacks); michael@0: rt->securityCallbacks = scb ? scb : &NullSecurityCallbacks; michael@0: } michael@0: michael@0: JS_PUBLIC_API(const JSSecurityCallbacks *) michael@0: JS_GetSecurityCallbacks(JSRuntime *rt) michael@0: { michael@0: return (rt->securityCallbacks != &NullSecurityCallbacks) ? rt->securityCallbacks : nullptr; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetTrustedPrincipals(JSRuntime *rt, const JSPrincipals *prin) michael@0: { michael@0: rt->setTrustedPrincipals(prin); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(void) michael@0: JS_InitDestroyPrincipalsCallback(JSRuntime *rt, JSDestroyPrincipalsOp destroyPrincipals) michael@0: { michael@0: JS_ASSERT(destroyPrincipals); michael@0: JS_ASSERT(!rt->destroyPrincipals); michael@0: rt->destroyPrincipals = destroyPrincipals; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS_NewFunction(JSContext *cx, JSNative native, unsigned nargs, unsigned flags, michael@0: HandleObject parent, const char *name) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, parent); michael@0: michael@0: RootedAtom atom(cx); michael@0: if (name) { michael@0: atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return nullptr; michael@0: } michael@0: michael@0: JSFunction::Flags funFlags = JSAPIToJSFunctionFlags(flags); michael@0: return NewFunction(cx, NullPtr(), native, nargs, funFlags, parent, atom); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS_NewFunctionById(JSContext *cx, JSNative native, unsigned nargs, unsigned flags, michael@0: HandleObject parent, HandleId id) michael@0: { michael@0: JS_ASSERT(JSID_IS_STRING(id)); michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: JS_ASSERT(native); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, parent); michael@0: michael@0: RootedAtom name(cx, JSID_TO_ATOM(id)); michael@0: JSFunction::Flags funFlags = JSAPIToJSFunctionFlags(flags); michael@0: return NewFunction(cx, NullPtr(), native, nargs, funFlags, parent, name); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS::GetSelfHostedFunction(JSContext *cx, const char *selfHostedName, HandleId id, unsigned nargs) michael@0: { michael@0: JS_ASSERT(JSID_IS_STRING(id)); michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: RootedAtom name(cx, JSID_TO_ATOM(id)); michael@0: RootedAtom shName(cx, Atomize(cx, selfHostedName, strlen(selfHostedName))); michael@0: if (!shName) michael@0: return nullptr; michael@0: RootedValue funVal(cx); michael@0: if (!cx->global()->getSelfHostedFunction(cx, shName, name, nargs, &funVal)) michael@0: return nullptr; michael@0: return &funVal.toObject().as(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_CloneFunctionObject(JSContext *cx, HandleObject funobj, HandleObject parentArg) michael@0: { michael@0: RootedObject parent(cx, parentArg); michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, parent); michael@0: // Note that funobj can be in a different compartment. michael@0: michael@0: if (!parent) michael@0: parent = cx->global(); michael@0: michael@0: if (!funobj->is()) { michael@0: AutoCompartment ac(cx, funobj); michael@0: RootedValue v(cx, ObjectValue(*funobj)); michael@0: ReportIsNotFunction(cx, v); michael@0: return nullptr; michael@0: } michael@0: michael@0: RootedFunction fun(cx, &funobj->as()); michael@0: if (fun->isInterpretedLazy()) { michael@0: AutoCompartment ac(cx, funobj); michael@0: if (!fun->getOrCreateScript(cx)) michael@0: return nullptr; michael@0: } michael@0: /* michael@0: * If a function was compiled to be lexically nested inside some other michael@0: * script, we cannot clone it without breaking the compiler's assumptions. michael@0: */ michael@0: if (fun->isInterpreted() && (fun->nonLazyScript()->enclosingStaticScope() || michael@0: (fun->nonLazyScript()->compileAndGo() && !parent->is()))) michael@0: { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_CLONE_FUNOBJ_SCOPE); michael@0: return nullptr; michael@0: } michael@0: michael@0: if (fun->isBoundFunction()) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); michael@0: return nullptr; michael@0: } michael@0: michael@0: if (fun->isNative() && IsAsmJSModuleNative(fun->native())) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT); michael@0: return nullptr; michael@0: } michael@0: michael@0: return CloneFunctionObject(cx, fun, parent, fun->getAllocKind()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetFunctionObject(JSFunction *fun) michael@0: { michael@0: return fun; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_GetFunctionId(JSFunction *fun) michael@0: { michael@0: return fun->atom(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_GetFunctionDisplayId(JSFunction *fun) michael@0: { michael@0: return fun->displayAtom(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(uint16_t) michael@0: JS_GetFunctionArity(JSFunction *fun) michael@0: { michael@0: return fun->nargs(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ObjectIsFunction(JSContext *cx, JSObject *obj) michael@0: { michael@0: return obj->is(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ObjectIsCallable(JSContext *cx, JSObject *obj) michael@0: { michael@0: return obj->isCallable(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsNativeFunction(JSObject *funobj, JSNative call) michael@0: { michael@0: if (!funobj->is()) michael@0: return false; michael@0: JSFunction *fun = &funobj->as(); michael@0: return fun->isNative() && fun->native() == call; michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS_IsConstructor(JSFunction *fun) michael@0: { michael@0: return fun->isNativeConstructor() || fun->isInterpretedConstructor(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject*) michael@0: JS_BindCallable(JSContext *cx, HandleObject target, HandleObject newThis) michael@0: { michael@0: RootedValue thisArg(cx, ObjectValue(*newThis)); michael@0: return js_fun_bind(cx, target, thisArg, nullptr, 0); michael@0: } michael@0: michael@0: static bool michael@0: js_generic_native_method_dispatcher(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: michael@0: const JSFunctionSpec *fs = (JSFunctionSpec *) michael@0: args.callee().as().getExtendedSlot(0).toPrivate(); michael@0: JS_ASSERT((fs->flags & JSFUN_GENERIC_NATIVE) != 0); michael@0: michael@0: if (argc < 1) { michael@0: js_ReportMissingArg(cx, args.calleev(), 0); michael@0: return false; michael@0: } michael@0: michael@0: /* michael@0: * Copy all actual (argc) arguments down over our |this| parameter, vp[1], michael@0: * which is almost always the class constructor object, e.g. Array. Then michael@0: * call the corresponding prototype native method with our first argument michael@0: * passed as |this|. michael@0: */ michael@0: memmove(vp + 1, vp + 2, argc * sizeof(jsval)); michael@0: michael@0: /* Clear the last parameter in case too few arguments were passed. */ michael@0: vp[2 + --argc].setUndefined(); michael@0: michael@0: return fs->call.op(cx, argc, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DefineFunctions(JSContext *cx, HandleObject obj, const JSFunctionSpec *fs) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: RootedObject ctor(cx); michael@0: michael@0: for (; fs->name; fs++) { michael@0: RootedAtom atom(cx); michael@0: // If the name starts with "@@", it must be a well-known symbol. michael@0: if (fs->name[0] != '@' || fs->name[1] != '@') michael@0: atom = Atomize(cx, fs->name, strlen(fs->name)); michael@0: else if (strcmp(fs->name, "@@iterator") == 0) michael@0: // FIXME: This atom should be a symbol: bug 918828. michael@0: atom = cx->names().std_iterator; michael@0: else michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_SYMBOL, fs->name); michael@0: if (!atom) michael@0: return false; michael@0: michael@0: Rooted id(cx, AtomToId(atom)); michael@0: michael@0: /* michael@0: * Define a generic arity N+1 static method for the arity N prototype michael@0: * method if flags contains JSFUN_GENERIC_NATIVE. michael@0: */ michael@0: unsigned flags = fs->flags; michael@0: if (flags & JSFUN_GENERIC_NATIVE) { michael@0: if (!ctor) { michael@0: ctor = JS_GetConstructor(cx, obj); michael@0: if (!ctor) michael@0: return false; michael@0: } michael@0: michael@0: flags &= ~JSFUN_GENERIC_NATIVE; michael@0: JSFunction *fun = DefineFunction(cx, ctor, id, michael@0: js_generic_native_method_dispatcher, michael@0: fs->nargs + 1, flags, michael@0: JSFunction::ExtendedFinalizeKind); michael@0: if (!fun) michael@0: return false; michael@0: michael@0: /* michael@0: * As jsapi.h notes, fs must point to storage that lives as long michael@0: * as fun->object lives. michael@0: */ michael@0: fun->setExtendedSlot(0, PrivateValue(const_cast(fs))); michael@0: } michael@0: michael@0: /* michael@0: * Delay cloning self-hosted functions until they are called. This is michael@0: * achieved by passing DefineFunction a nullptr JSNative which michael@0: * produces an interpreted JSFunction where !hasScript. Interpreted michael@0: * call paths then call InitializeLazyFunctionScript if !hasScript. michael@0: */ michael@0: if (fs->selfHostedName) { michael@0: JS_ASSERT(!fs->call.op); michael@0: JS_ASSERT(!fs->call.info); michael@0: /* michael@0: * During creation of the self-hosting global, we ignore all michael@0: * self-hosted functions, as that means we're currently setting up michael@0: * the global object that the self-hosted code is then compiled michael@0: * in. Self-hosted functions can access each other via their names, michael@0: * but not via the builtin classes they get installed into. michael@0: */ michael@0: if (cx->runtime()->isSelfHostingGlobal(cx->global())) michael@0: continue; michael@0: michael@0: RootedAtom shName(cx, Atomize(cx, fs->selfHostedName, strlen(fs->selfHostedName))); michael@0: if (!shName) michael@0: return false; michael@0: RootedValue funVal(cx); michael@0: if (!cx->global()->getSelfHostedFunction(cx, shName, atom, fs->nargs, &funVal)) michael@0: return false; michael@0: if (!JSObject::defineGeneric(cx, obj, id, funVal, nullptr, nullptr, flags)) michael@0: return false; michael@0: } else { michael@0: JSFunction *fun = DefineFunction(cx, obj, id, fs->call.op, fs->nargs, flags); michael@0: if (!fun) michael@0: return false; michael@0: if (fs->call.info) michael@0: fun->setJitInfo(fs->call.info); michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS_DefineFunction(JSContext *cx, HandleObject obj, const char *name, JSNative call, michael@0: unsigned nargs, unsigned attrs) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return nullptr; michael@0: Rooted id(cx, AtomToId(atom)); michael@0: return DefineFunction(cx, obj, id, call, nargs, attrs); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS_DefineUCFunction(JSContext *cx, HandleObject obj, michael@0: const jschar *name, size_t namelen, JSNative call, michael@0: unsigned nargs, unsigned attrs) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: JSAtom *atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen)); michael@0: if (!atom) michael@0: return nullptr; michael@0: Rooted id(cx, AtomToId(atom)); michael@0: return DefineFunction(cx, obj, id, call, nargs, attrs); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(JSFunction *) michael@0: JS_DefineFunctionById(JSContext *cx, HandleObject obj, HandleId id, JSNative call, michael@0: unsigned nargs, unsigned attrs) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: return DefineFunction(cx, obj, id, call, nargs, attrs); michael@0: } michael@0: michael@0: struct AutoLastFrameCheck michael@0: { michael@0: AutoLastFrameCheck(JSContext *cx michael@0: MOZ_GUARD_OBJECT_NOTIFIER_PARAM) michael@0: : cx(cx) michael@0: { michael@0: JS_ASSERT(cx); michael@0: MOZ_GUARD_OBJECT_NOTIFIER_INIT; michael@0: } michael@0: michael@0: ~AutoLastFrameCheck() { michael@0: if (cx->isExceptionPending() && michael@0: !JS_IsRunning(cx) && michael@0: !cx->options().dontReportUncaught()) { michael@0: js_ReportUncaughtException(cx); michael@0: } michael@0: } michael@0: michael@0: private: michael@0: JSContext *cx; michael@0: MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER michael@0: }; michael@0: michael@0: /* Use the fastest available getc. */ michael@0: #if defined(HAVE_GETC_UNLOCKED) michael@0: # define fast_getc getc_unlocked michael@0: #elif defined(HAVE__GETC_NOLOCK) michael@0: # define fast_getc _getc_nolock michael@0: #else michael@0: # define fast_getc getc michael@0: #endif michael@0: michael@0: typedef js::Vector FileContents; michael@0: michael@0: static bool michael@0: ReadCompleteFile(JSContext *cx, FILE *fp, FileContents &buffer) michael@0: { michael@0: /* Get the complete length of the file, if possible. */ michael@0: struct stat st; michael@0: int ok = fstat(fileno(fp), &st); michael@0: if (ok != 0) michael@0: return false; michael@0: if (st.st_size > 0) { michael@0: if (!buffer.reserve(st.st_size)) michael@0: return false; michael@0: } michael@0: michael@0: // Read in the whole file. Note that we can't assume the data's length michael@0: // is actually st.st_size, because 1) some files lie about their size michael@0: // (/dev/zero and /dev/random), and 2) reading files in text mode on michael@0: // Windows collapses "\r\n" pairs to single \n characters. michael@0: for (;;) { michael@0: int c = fast_getc(fp); michael@0: if (c == EOF) michael@0: break; michael@0: if (!buffer.append(c)) michael@0: return false; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: namespace { michael@0: michael@0: class AutoFile michael@0: { michael@0: FILE *fp_; michael@0: public: michael@0: AutoFile() michael@0: : fp_(nullptr) michael@0: {} michael@0: ~AutoFile() michael@0: { michael@0: if (fp_ && fp_ != stdin) michael@0: fclose(fp_); michael@0: } michael@0: FILE *fp() const { return fp_; } michael@0: bool open(JSContext *cx, const char *filename); michael@0: bool readAll(JSContext *cx, FileContents &buffer) michael@0: { michael@0: JS_ASSERT(fp_); michael@0: return ReadCompleteFile(cx, fp_, buffer); michael@0: } michael@0: }; michael@0: michael@0: } /* anonymous namespace */ michael@0: michael@0: /* michael@0: * Open a source file for reading. Supports "-" and nullptr to mean stdin. The michael@0: * return value must be fclosed unless it is stdin. michael@0: */ michael@0: bool michael@0: AutoFile::open(JSContext *cx, const char *filename) michael@0: { michael@0: if (!filename || strcmp(filename, "-") == 0) { michael@0: fp_ = stdin; michael@0: } else { michael@0: fp_ = fopen(filename, "r"); michael@0: if (!fp_) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_OPEN, michael@0: filename, "No such file or directory"); michael@0: return false; michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: JSObject * const JS::ReadOnlyCompileOptions::nullObjectPtr = nullptr; michael@0: michael@0: void michael@0: JS::ReadOnlyCompileOptions::copyPODOptions(const ReadOnlyCompileOptions &rhs) michael@0: { michael@0: version = rhs.version; michael@0: versionSet = rhs.versionSet; michael@0: utf8 = rhs.utf8; michael@0: lineno = rhs.lineno; michael@0: column = rhs.column; michael@0: compileAndGo = rhs.compileAndGo; michael@0: forEval = rhs.forEval; michael@0: noScriptRval = rhs.noScriptRval; michael@0: selfHostingMode = rhs.selfHostingMode; michael@0: canLazilyParse = rhs.canLazilyParse; michael@0: strictOption = rhs.strictOption; michael@0: extraWarningsOption = rhs.extraWarningsOption; michael@0: werrorOption = rhs.werrorOption; michael@0: asmJSOption = rhs.asmJSOption; michael@0: forceAsync = rhs.forceAsync; michael@0: installedFile = rhs.installedFile; michael@0: sourceIsLazy = rhs.sourceIsLazy; michael@0: introductionType = rhs.introductionType; michael@0: introductionLineno = rhs.introductionLineno; michael@0: introductionOffset = rhs.introductionOffset; michael@0: hasIntroductionInfo = rhs.hasIntroductionInfo; michael@0: } michael@0: michael@0: JSPrincipals * michael@0: JS::ReadOnlyCompileOptions::originPrincipals(ExclusiveContext *cx) const michael@0: { michael@0: return NormalizeOriginPrincipals(cx->compartment()->principals, originPrincipals_); michael@0: } michael@0: michael@0: JS::OwningCompileOptions::OwningCompileOptions(JSContext *cx) michael@0: : ReadOnlyCompileOptions(), michael@0: runtime(GetRuntime(cx)), michael@0: elementRoot(cx), michael@0: elementAttributeNameRoot(cx), michael@0: introductionScriptRoot(cx) michael@0: { michael@0: } michael@0: michael@0: JS::OwningCompileOptions::~OwningCompileOptions() michael@0: { michael@0: if (originPrincipals_) michael@0: JS_DropPrincipals(runtime, originPrincipals_); michael@0: michael@0: // OwningCompileOptions always owns these, so these casts are okay. michael@0: js_free(const_cast(filename_)); michael@0: js_free(const_cast(sourceMapURL_)); michael@0: js_free(const_cast(introducerFilename_)); michael@0: } michael@0: michael@0: bool michael@0: JS::OwningCompileOptions::copy(JSContext *cx, const ReadOnlyCompileOptions &rhs) michael@0: { michael@0: copyPODOptions(rhs); michael@0: michael@0: setOriginPrincipals(rhs.originPrincipals(cx)); michael@0: setElement(rhs.element()); michael@0: setElementAttributeName(rhs.elementAttributeName()); michael@0: setIntroductionScript(rhs.introductionScript()); michael@0: michael@0: return (setFileAndLine(cx, rhs.filename(), rhs.lineno) && michael@0: setSourceMapURL(cx, rhs.sourceMapURL()) && michael@0: setIntroducerFilename(cx, rhs.introducerFilename())); michael@0: } michael@0: michael@0: bool michael@0: JS::OwningCompileOptions::setFile(JSContext *cx, const char *f) michael@0: { michael@0: char *copy = nullptr; michael@0: if (f) { michael@0: copy = JS_strdup(cx, f); michael@0: if (!copy) michael@0: return false; michael@0: } michael@0: michael@0: // OwningCompileOptions always owns filename_, so this cast is okay. michael@0: js_free(const_cast(filename_)); michael@0: michael@0: filename_ = copy; michael@0: return true; michael@0: } michael@0: michael@0: bool michael@0: JS::OwningCompileOptions::setFileAndLine(JSContext *cx, const char *f, unsigned l) michael@0: { michael@0: if (!setFile(cx, f)) michael@0: return false; michael@0: michael@0: lineno = l; michael@0: return true; michael@0: } michael@0: michael@0: bool michael@0: JS::OwningCompileOptions::setSourceMapURL(JSContext *cx, const jschar *s) michael@0: { michael@0: jschar *copy = nullptr; michael@0: if (s) { michael@0: copy = js_strdup(cx, s); michael@0: if (!copy) michael@0: return false; michael@0: } michael@0: michael@0: // OwningCompileOptions always owns sourceMapURL_, so this cast is okay. michael@0: js_free(const_cast(sourceMapURL_)); michael@0: michael@0: sourceMapURL_ = copy; michael@0: return true; michael@0: } michael@0: michael@0: bool michael@0: JS::OwningCompileOptions::setIntroducerFilename(JSContext *cx, const char *s) michael@0: { michael@0: char *copy = nullptr; michael@0: if (s) { michael@0: copy = JS_strdup(cx, s); michael@0: if (!copy) michael@0: return false; michael@0: } michael@0: michael@0: // OwningCompileOptions always owns introducerFilename_, so this cast is okay. michael@0: js_free(const_cast(introducerFilename_)); michael@0: michael@0: introducerFilename_ = copy; michael@0: return true; michael@0: } michael@0: michael@0: bool michael@0: JS::OwningCompileOptions::wrap(JSContext *cx, JSCompartment *compartment) michael@0: { michael@0: if (!compartment->wrap(cx, &elementRoot)) michael@0: return false; michael@0: if (elementAttributeNameRoot) { michael@0: if (!compartment->wrap(cx, elementAttributeNameRoot.address())) michael@0: return false; michael@0: } michael@0: michael@0: // There is no equivalent of cross-compartment wrappers for scripts. If michael@0: // the introduction script would be in a different compartment from the michael@0: // compiled code, we would be creating a cross-compartment script michael@0: // reference, which would be bogus. In that case, just don't bother to michael@0: // retain the introduction script. michael@0: if (introductionScriptRoot) { michael@0: if (introductionScriptRoot->compartment() != compartment) michael@0: introductionScriptRoot = nullptr; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: JS::CompileOptions::CompileOptions(JSContext *cx, JSVersion version) michael@0: : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx), michael@0: introductionScriptRoot(cx) michael@0: { michael@0: this->version = (version != JSVERSION_UNKNOWN) ? version : cx->findVersion(); michael@0: michael@0: compileAndGo = false; michael@0: noScriptRval = cx->options().noScriptRval(); michael@0: strictOption = cx->options().strictMode(); michael@0: extraWarningsOption = cx->options().extraWarnings(); michael@0: werrorOption = cx->options().werror(); michael@0: asmJSOption = cx->runtime()->options().asmJS(); michael@0: } michael@0: michael@0: bool michael@0: JS::CompileOptions::wrap(JSContext *cx, JSCompartment *compartment) michael@0: { michael@0: if (!compartment->wrap(cx, &elementRoot)) michael@0: return false; michael@0: if (elementAttributeNameRoot) { michael@0: if (!compartment->wrap(cx, elementAttributeNameRoot.address())) michael@0: return false; michael@0: } michael@0: michael@0: // There is no equivalent of cross-compartment wrappers for scripts. If michael@0: // the introduction script would be in a different compartment from the michael@0: // compiled code, we would be creating a cross-compartment script michael@0: // reference, which would be bogus. In that case, just don't bother to michael@0: // retain the introduction script. michael@0: if (introductionScriptRoot) { michael@0: if (introductionScriptRoot->compartment() != compartment) michael@0: introductionScriptRoot = nullptr; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: bool michael@0: JS::Compile(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: SourceBufferHolder &srcBuf, MutableHandleScript script) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: AutoLastFrameCheck lfc(cx); michael@0: michael@0: script.set(frontend::CompileScript(cx, &cx->tempLifoAlloc(), obj, NullPtr(), options, srcBuf)); michael@0: return !!script; michael@0: } michael@0: michael@0: JSScript * michael@0: JS::Compile(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: const jschar *chars, size_t length) michael@0: { michael@0: SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership); michael@0: RootedScript script(cx); michael@0: if (!Compile(cx, obj, options, srcBuf, &script)) michael@0: return nullptr; michael@0: return script; michael@0: } michael@0: michael@0: JSScript * michael@0: JS::Compile(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: const char *bytes, size_t length) michael@0: { michael@0: jschar *chars; michael@0: if (options.utf8) michael@0: chars = UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length), &length).get(); michael@0: else michael@0: chars = InflateString(cx, bytes, &length); michael@0: if (!chars) michael@0: return nullptr; michael@0: michael@0: JSScript *script = Compile(cx, obj, options, chars, length); michael@0: js_free(chars); michael@0: return script; michael@0: } michael@0: michael@0: JSScript * michael@0: JS::Compile(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, FILE *fp) michael@0: { michael@0: FileContents buffer(cx); michael@0: if (!ReadCompleteFile(cx, fp, buffer)) michael@0: return nullptr; michael@0: michael@0: JSScript *script = Compile(cx, obj, options, buffer.begin(), buffer.length()); michael@0: return script; michael@0: } michael@0: michael@0: JSScript * michael@0: JS::Compile(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, const char *filename) michael@0: { michael@0: AutoFile file; michael@0: if (!file.open(cx, filename)) michael@0: return nullptr; michael@0: CompileOptions options(cx, optionsArg); michael@0: options.setFileAndLine(filename, 1); michael@0: return Compile(cx, obj, options, file.fp()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::CanCompileOffThread(JSContext *cx, const ReadOnlyCompileOptions &options, size_t length) michael@0: { michael@0: static const size_t TINY_LENGTH = 1000; michael@0: static const size_t HUGE_LENGTH = 100 * 1000; michael@0: michael@0: // These are heuristics which the caller may choose to ignore (e.g., for michael@0: // testing purposes). michael@0: if (!options.forceAsync) { michael@0: // Compiling off the main thread inolves creating a new Zone and other michael@0: // significant overheads. Don't bother if the script is tiny. michael@0: if (length < TINY_LENGTH) michael@0: return false; michael@0: michael@0: #ifdef JS_THREADSAFE michael@0: // If the parsing task would have to wait for GC to complete, it'll probably michael@0: // be faster to just start it synchronously on the main thread unless the michael@0: // script is huge. michael@0: if (OffThreadParsingMustWaitForGC(cx->runtime()) && length < HUGE_LENGTH) michael@0: return false; michael@0: #endif // JS_THREADSAFE michael@0: } michael@0: michael@0: return cx->runtime()->canUseParallelParsing(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::CompileOffThread(JSContext *cx, const ReadOnlyCompileOptions &options, michael@0: const jschar *chars, size_t length, michael@0: OffThreadCompileCallback callback, void *callbackData) michael@0: { michael@0: JS_ASSERT(CanCompileOffThread(cx, options, length)); michael@0: return StartOffThreadParseScript(cx, options, chars, length, callback, callbackData); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSScript *) michael@0: JS::FinishOffThreadScript(JSContext *maybecx, JSRuntime *rt, void *token) michael@0: { michael@0: #ifdef JS_THREADSAFE michael@0: JS_ASSERT(CurrentThreadCanAccessRuntime(rt)); michael@0: michael@0: if (maybecx) { michael@0: RootedScript script(maybecx); michael@0: { michael@0: AutoLastFrameCheck lfc(maybecx); michael@0: script = WorkerThreadState().finishParseTask(maybecx, rt, token); michael@0: } michael@0: return script; michael@0: } else { michael@0: return WorkerThreadState().finishParseTask(maybecx, rt, token); michael@0: } michael@0: #else michael@0: MOZ_ASSUME_UNREACHABLE("Off thread compilation is not available."); michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSScript *) michael@0: JS_CompileScript(JSContext *cx, JS::HandleObject obj, const char *ascii, michael@0: size_t length, const JS::CompileOptions &options) michael@0: { michael@0: return Compile(cx, obj, options, ascii, length); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSScript *) michael@0: JS_CompileUCScript(JSContext *cx, JS::HandleObject obj, const jschar *chars, michael@0: size_t length, const JS::CompileOptions &options) michael@0: { michael@0: return Compile(cx, obj, options, chars, length); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_BufferIsCompilableUnit(JSContext *cx, HandleObject obj, const char *utf8, size_t length) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: cx->clearPendingException(); michael@0: michael@0: jschar *chars = JS::UTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(utf8, length), &length).get(); michael@0: if (!chars) michael@0: return true; michael@0: michael@0: // Return true on any out-of-memory error or non-EOF-related syntax error, so our michael@0: // caller doesn't try to collect more buffered source. michael@0: bool result = true; michael@0: michael@0: CompileOptions options(cx); michael@0: options.setCompileAndGo(false); michael@0: Parser parser(cx, &cx->tempLifoAlloc(), michael@0: options, chars, length, michael@0: /* foldConstants = */ true, nullptr, nullptr); michael@0: JSErrorReporter older = JS_SetErrorReporter(cx, nullptr); michael@0: if (!parser.parse(obj)) { michael@0: // We ran into an error. If it was because we ran out of source, we michael@0: // return false so our caller knows to try to collect more buffered michael@0: // source. michael@0: if (parser.isUnexpectedEOF()) michael@0: result = false; michael@0: michael@0: cx->clearPendingException(); michael@0: } michael@0: JS_SetErrorReporter(cx, older); michael@0: michael@0: js_free(chars); michael@0: return result; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_GetGlobalFromScript(JSScript *script) michael@0: { michael@0: JS_ASSERT(!script->isCachedEval()); michael@0: return &script->global(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::CompileFunction(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: const char *name, unsigned nargs, const char *const *argnames, michael@0: SourceBufferHolder &srcBuf, MutableHandleFunction fun) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: RootedAtom funAtom(cx); michael@0: AutoLastFrameCheck lfc(cx); michael@0: michael@0: if (name) { michael@0: funAtom = Atomize(cx, name, strlen(name)); michael@0: if (!funAtom) michael@0: return false; michael@0: } michael@0: michael@0: AutoNameVector formals(cx); michael@0: for (unsigned i = 0; i < nargs; i++) { michael@0: RootedAtom argAtom(cx, Atomize(cx, argnames[i], strlen(argnames[i]))); michael@0: if (!argAtom || !formals.append(argAtom->asPropertyName())) michael@0: return false; michael@0: } michael@0: michael@0: fun.set(NewFunction(cx, NullPtr(), nullptr, 0, JSFunction::INTERPRETED, obj, michael@0: funAtom, JSFunction::FinalizeKind, TenuredObject)); michael@0: if (!fun) michael@0: return false; michael@0: michael@0: if (!frontend::CompileFunctionBody(cx, fun, options, formals, srcBuf)) michael@0: return false; michael@0: michael@0: if (obj && funAtom && options.defineOnScope) { michael@0: Rooted id(cx, AtomToId(funAtom)); michael@0: RootedValue value(cx, ObjectValue(*fun)); michael@0: if (!JSObject::defineGeneric(cx, obj, id, value, nullptr, nullptr, JSPROP_ENUMERATE)) michael@0: return false; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS::CompileFunction(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: const char *name, unsigned nargs, const char *const *argnames, michael@0: const jschar *chars, size_t length) michael@0: { michael@0: RootedFunction fun(cx); michael@0: SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership); michael@0: if (!JS::CompileFunction(cx, obj, options, name, nargs, argnames, srcBuf, &fun)) michael@0: return nullptr; michael@0: return fun; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS::CompileFunction(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: const char *name, unsigned nargs, const char *const *argnames, michael@0: const char *bytes, size_t length) michael@0: { michael@0: jschar *chars; michael@0: if (options.utf8) michael@0: chars = UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length), &length).get(); michael@0: else michael@0: chars = InflateString(cx, bytes, &length); michael@0: if (!chars) michael@0: return nullptr; michael@0: michael@0: JSFunction *fun = CompileFunction(cx, obj, options, name, nargs, argnames, chars, length); michael@0: js_free(chars); michael@0: return fun; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS_CompileUCFunction(JSContext *cx, JS::HandleObject obj, const char *name, michael@0: unsigned nargs, const char *const *argnames, michael@0: const jschar *chars, size_t length, michael@0: const CompileOptions &options) michael@0: { michael@0: return CompileFunction(cx, obj, options, name, nargs, argnames, chars, length); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunction *) michael@0: JS_CompileFunction(JSContext *cx, JS::HandleObject obj, const char *name, michael@0: unsigned nargs, const char *const *argnames, michael@0: const char *ascii, size_t length, michael@0: const JS::CompileOptions &options) michael@0: { michael@0: return CompileFunction(cx, obj, options, name, nargs, argnames, ascii, length); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_DecompileScript(JSContext *cx, HandleScript script, const char *name, unsigned indent) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: script->ensureNonLazyCanonicalFunction(cx); michael@0: RootedFunction fun(cx, script->functionNonDelazifying()); michael@0: if (fun) michael@0: return JS_DecompileFunction(cx, fun, indent); michael@0: bool haveSource = script->scriptSource()->hasSourceData(); michael@0: if (!haveSource && !JSScript::loadSource(cx, script->scriptSource(), &haveSource)) michael@0: return nullptr; michael@0: return haveSource ? script->sourceData(cx) : js_NewStringCopyZ(cx, "[no source]"); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_DecompileFunction(JSContext *cx, HandleFunction fun, unsigned indent) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, fun); michael@0: return FunctionToString(cx, fun, false, !(indent & JS_DONT_PRETTY_PRINT)); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_DecompileFunctionBody(JSContext *cx, HandleFunction fun, unsigned indent) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, fun); michael@0: return FunctionToString(cx, fun, true, !(indent & JS_DONT_PRETTY_PRINT)); michael@0: } michael@0: michael@0: MOZ_NEVER_INLINE static bool michael@0: ExecuteScript(JSContext *cx, HandleObject obj, HandleScript scriptArg, jsval *rval) michael@0: { michael@0: RootedScript script(cx, scriptArg); michael@0: michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, scriptArg); michael@0: AutoLastFrameCheck lfc(cx); michael@0: return Execute(cx, script, *obj, rval); michael@0: } michael@0: michael@0: MOZ_NEVER_INLINE JS_PUBLIC_API(bool) michael@0: JS_ExecuteScript(JSContext *cx, HandleObject obj, HandleScript scriptArg, MutableHandleValue rval) michael@0: { michael@0: return ExecuteScript(cx, obj, scriptArg, rval.address()); michael@0: } michael@0: michael@0: MOZ_NEVER_INLINE JS_PUBLIC_API(bool) michael@0: JS_ExecuteScript(JSContext *cx, HandleObject obj, HandleScript scriptArg) michael@0: { michael@0: return ExecuteScript(cx, obj, scriptArg, nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::CloneAndExecuteScript(JSContext *cx, HandleObject obj, HandleScript scriptArg) michael@0: { michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: RootedScript script(cx, scriptArg); michael@0: if (script->compartment() != cx->compartment()) { michael@0: script = CloneScript(cx, NullPtr(), NullPtr(), script); michael@0: if (!script) michael@0: return false; michael@0: } michael@0: return ExecuteScript(cx, obj, script, nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ExecuteScriptVersion(JSContext *cx, HandleObject obj, HandleScript script, michael@0: MutableHandleValue rval, JSVersion version) michael@0: { michael@0: return ExecuteScript(cx, obj, script, rval.address()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ExecuteScriptVersion(JSContext *cx, HandleObject obj, HandleScript script, JSVersion version) michael@0: { michael@0: return ExecuteScript(cx, obj, script, nullptr); michael@0: } michael@0: michael@0: static const unsigned LARGE_SCRIPT_LENGTH = 500*1024; michael@0: michael@0: static bool michael@0: Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: SourceBufferHolder &srcBuf, JS::Value *rval) michael@0: { michael@0: CompileOptions options(cx, optionsArg); michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: michael@0: AutoLastFrameCheck lfc(cx); michael@0: michael@0: options.setCompileAndGo(obj->is()); michael@0: options.setNoScriptRval(!rval); michael@0: SourceCompressionTask sct(cx); michael@0: RootedScript script(cx, frontend::CompileScript(cx, &cx->tempLifoAlloc(), michael@0: obj, NullPtr(), options, michael@0: srcBuf, nullptr, 0, &sct)); michael@0: if (!script) michael@0: return false; michael@0: michael@0: JS_ASSERT(script->getVersion() == options.version); michael@0: michael@0: bool result = Execute(cx, script, *obj, rval); michael@0: if (!sct.complete()) michael@0: result = false; michael@0: michael@0: // After evaluation, the compiled script will not be run again. michael@0: // script->ensureRanAnalysis allocated 1 analyze::Bytecode for every opcode michael@0: // which for large scripts means significant memory. Perform a GC eagerly michael@0: // to clear out this analysis data before anything happens to inhibit the michael@0: // flushing of this memory (such as setting requestAnimationFrame). michael@0: if (script->length() > LARGE_SCRIPT_LENGTH) { michael@0: script = nullptr; michael@0: PrepareZoneForGC(cx->zone()); michael@0: GC(cx->runtime(), GC_NORMAL, JS::gcreason::FINISH_LARGE_EVALUTE); michael@0: } michael@0: michael@0: return result; michael@0: } michael@0: michael@0: static bool michael@0: Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: const jschar *chars, size_t length, JS::Value *rval) michael@0: { michael@0: SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership); michael@0: return ::Evaluate(cx, obj, optionsArg, srcBuf, rval); michael@0: } michael@0: michael@0: static bool michael@0: Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: const char *bytes, size_t length, JS::Value *rval) michael@0: { michael@0: jschar *chars; michael@0: if (options.utf8) michael@0: chars = UTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(bytes, length), &length).get(); michael@0: else michael@0: chars = InflateString(cx, bytes, &length); michael@0: if (!chars) michael@0: return false; michael@0: michael@0: SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::GiveOwnership); michael@0: bool ok = ::Evaluate(cx, obj, options, srcBuf, rval); michael@0: return ok; michael@0: } michael@0: michael@0: static bool michael@0: Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: const char *filename, JS::Value *rval) michael@0: { michael@0: FileContents buffer(cx); michael@0: { michael@0: AutoFile file; michael@0: if (!file.open(cx, filename) || !file.readAll(cx, buffer)) michael@0: return false; michael@0: } michael@0: michael@0: CompileOptions options(cx, optionsArg); michael@0: options.setFileAndLine(filename, 1); michael@0: return Evaluate(cx, obj, options, buffer.begin(), buffer.length(), rval); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS::Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: SourceBufferHolder &srcBuf, MutableHandleValue rval) michael@0: { michael@0: return ::Evaluate(cx, obj, optionsArg, srcBuf, rval.address()); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS::Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: const jschar *chars, size_t length, MutableHandleValue rval) michael@0: { michael@0: return ::Evaluate(cx, obj, optionsArg, chars, length, rval.address()); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS::Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: const char *bytes, size_t length, MutableHandleValue rval) michael@0: { michael@0: return ::Evaluate(cx, obj, options, bytes, length, rval.address()); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS::Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: const char *filename, MutableHandleValue rval) michael@0: { michael@0: return ::Evaluate(cx, obj, optionsArg, filename, rval.address()); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS::Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: SourceBufferHolder &srcBuf) michael@0: { michael@0: return ::Evaluate(cx, obj, optionsArg, srcBuf, nullptr); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS::Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: const jschar *chars, size_t length) michael@0: { michael@0: return ::Evaluate(cx, obj, optionsArg, chars, length, nullptr); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS::Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &options, michael@0: const char *bytes, size_t length) michael@0: { michael@0: return ::Evaluate(cx, obj, options, bytes, length, nullptr); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(bool) michael@0: JS::Evaluate(JSContext *cx, HandleObject obj, const ReadOnlyCompileOptions &optionsArg, michael@0: const char *filename) michael@0: { michael@0: return ::Evaluate(cx, obj, optionsArg, filename, nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_EvaluateUCScript(JSContext *cx, HandleObject obj, const jschar *chars, unsigned length, michael@0: const char *filename, unsigned lineno, MutableHandleValue rval) michael@0: { michael@0: CompileOptions options(cx); michael@0: options.setFileAndLine(filename, lineno); michael@0: michael@0: return ::Evaluate(cx, obj, options, chars, length, rval.address()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_EvaluateUCScript(JSContext *cx, HandleObject obj, SourceBufferHolder &srcBuf, michael@0: const char *filename, unsigned lineno, MutableHandleValue rval) michael@0: { michael@0: CompileOptions options(cx); michael@0: options.setFileAndLine(filename, lineno); michael@0: michael@0: return ::Evaluate(cx, obj, options, srcBuf, rval.address()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_EvaluateScript(JSContext *cx, HandleObject obj, const char *bytes, unsigned nbytes, michael@0: const char *filename, unsigned lineno, MutableHandleValue rval) michael@0: { michael@0: CompileOptions options(cx); michael@0: options.setFileAndLine(filename, lineno); michael@0: michael@0: return ::Evaluate(cx, obj, options, bytes, nbytes, rval.address()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_EvaluateScript(JSContext *cx, HandleObject obj, const char *bytes, unsigned nbytes, michael@0: const char *filename, unsigned lineno) michael@0: { michael@0: CompileOptions options(cx); michael@0: options.setFileAndLine(filename, lineno); michael@0: michael@0: return ::Evaluate(cx, obj, options, bytes, nbytes, nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_CallFunction(JSContext *cx, HandleObject obj, HandleFunction fun, const HandleValueArray& args, michael@0: MutableHandleValue rval) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, fun, args); michael@0: AutoLastFrameCheck lfc(cx); michael@0: michael@0: return Invoke(cx, ObjectOrNullValue(obj), ObjectValue(*fun), args.length(), args.begin(), rval); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_CallFunctionName(JSContext *cx, HandleObject obj, const char *name, const HandleValueArray& args, michael@0: MutableHandleValue rval) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, args); michael@0: AutoLastFrameCheck lfc(cx); michael@0: michael@0: JSAtom *atom = Atomize(cx, name, strlen(name)); michael@0: if (!atom) michael@0: return false; michael@0: michael@0: RootedValue v(cx); michael@0: RootedId id(cx, AtomToId(atom)); michael@0: if (!JSObject::getGeneric(cx, obj, obj, id, &v)) michael@0: return false; michael@0: michael@0: return Invoke(cx, ObjectOrNullValue(obj), v, args.length(), args.begin(), rval); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_CallFunctionValue(JSContext *cx, HandleObject obj, HandleValue fval, const HandleValueArray& args, michael@0: MutableHandleValue rval) michael@0: { michael@0: JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment())); michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj, fval, args); michael@0: AutoLastFrameCheck lfc(cx); michael@0: michael@0: return Invoke(cx, ObjectOrNullValue(obj), fval, args.length(), args.begin(), rval); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS::Call(JSContext *cx, HandleValue thisv, HandleValue fval, const JS::HandleValueArray& args, michael@0: MutableHandleValue rval) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, thisv, fval, args); michael@0: AutoLastFrameCheck lfc(cx); michael@0: michael@0: return Invoke(cx, thisv, fval, args.length(), args.begin(), rval); michael@0: } michael@0: michael@0: static JSObject * michael@0: JS_NewHelper(JSContext *cx, HandleObject ctor, const JS::HandleValueArray& inputArgs) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, ctor, inputArgs); michael@0: michael@0: // This is not a simple variation of JS_CallFunctionValue because JSOP_NEW michael@0: // is not a simple variation of JSOP_CALL. We have to determine what class michael@0: // of object to create, create it, and clamp the return value to an object, michael@0: // among other details. InvokeConstructor does the hard work. michael@0: InvokeArgs args(cx); michael@0: if (!args.init(inputArgs.length())) michael@0: return nullptr; michael@0: michael@0: args.setCallee(ObjectValue(*ctor)); michael@0: args.setThis(NullValue()); michael@0: PodCopy(args.array(), inputArgs.begin(), inputArgs.length()); michael@0: michael@0: if (!InvokeConstructor(cx, args)) michael@0: return nullptr; michael@0: michael@0: if (!args.rval().isObject()) { michael@0: /* michael@0: * Although constructors may return primitives (via proxies), this michael@0: * API is asking for an object, so we report an error. michael@0: */ michael@0: JSAutoByteString bytes; michael@0: if (js_ValueToPrintable(cx, args.rval(), &bytes)) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_NEW_RESULT, michael@0: bytes.ptr()); michael@0: } michael@0: return nullptr; michael@0: } michael@0: michael@0: return &args.rval().toObject(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_New(JSContext *cx, HandleObject ctor, const JS::HandleValueArray& inputArgs) michael@0: { michael@0: RootedObject obj(cx); michael@0: { michael@0: AutoLastFrameCheck lfc(cx); michael@0: obj = JS_NewHelper(cx, ctor, inputArgs); michael@0: } michael@0: return obj; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSInterruptCallback) michael@0: JS_SetInterruptCallback(JSRuntime *rt, JSInterruptCallback callback) michael@0: { michael@0: JSInterruptCallback old = rt->interruptCallback; michael@0: rt->interruptCallback = callback; michael@0: return old; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSInterruptCallback) michael@0: JS_GetInterruptCallback(JSRuntime *rt) michael@0: { michael@0: return rt->interruptCallback; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_RequestInterruptCallback(JSRuntime *rt) michael@0: { michael@0: rt->requestInterrupt(JSRuntime::RequestInterruptAnyThread); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsRunning(JSContext *cx) michael@0: { michael@0: return cx->currentlyRunning(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SaveFrameChain(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdleOrIterating(cx); michael@0: CHECK_REQUEST(cx); michael@0: return cx->saveFrameChain(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_RestoreFrameChain(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdleOrIterating(cx); michael@0: CHECK_REQUEST(cx); michael@0: cx->restoreFrameChain(); michael@0: } michael@0: michael@0: #ifdef MOZ_TRACE_JSCALLS michael@0: JS_PUBLIC_API(void) michael@0: JS_SetFunctionCallback(JSContext *cx, JSFunctionCallback fcb) michael@0: { michael@0: cx->functionCallback = fcb; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSFunctionCallback) michael@0: JS_GetFunctionCallback(JSContext *cx) michael@0: { michael@0: return cx->functionCallback; michael@0: } michael@0: #endif michael@0: michael@0: /************************************************************************/ michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_NewStringCopyN(JSContext *cx, const char *s, size_t n) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (!n) michael@0: return cx->names().empty; michael@0: return js_NewStringCopyN(cx, s, n); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_NewStringCopyZ(JSContext *cx, const char *s) michael@0: { michael@0: size_t n; michael@0: jschar *js; michael@0: JSString *str; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (!s || !*s) michael@0: return cx->runtime()->emptyString; michael@0: n = strlen(s); michael@0: js = InflateString(cx, s, &n); michael@0: if (!js) michael@0: return nullptr; michael@0: str = js_NewString(cx, js, n); michael@0: if (!str) michael@0: js_free(js); michael@0: return str; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_StringHasBeenInterned(JSContext *cx, JSString *str) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: if (!str->isAtom()) michael@0: return false; michael@0: michael@0: return AtomIsInterned(cx, &str->asAtom()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(jsid) michael@0: INTERNED_STRING_TO_JSID(JSContext *cx, JSString *str) michael@0: { michael@0: JS_ASSERT(str); michael@0: JS_ASSERT(((size_t)str & JSID_TYPE_MASK) == 0); michael@0: JS_ASSERT_IF(cx, JS_StringHasBeenInterned(cx, str)); michael@0: return AtomToId(&str->asAtom()); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_InternJSString(JSContext *cx, HandleString str) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JSAtom *atom = AtomizeString(cx, str, InternAtom); michael@0: JS_ASSERT_IF(atom, JS_StringHasBeenInterned(cx, atom)); michael@0: return atom; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_InternString(JSContext *cx, const char *s) michael@0: { michael@0: return JS_InternStringN(cx, s, strlen(s)); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_InternStringN(JSContext *cx, const char *s, size_t length) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JSAtom *atom = Atomize(cx, s, length, InternAtom); michael@0: JS_ASSERT_IF(atom, JS_StringHasBeenInterned(cx, atom)); michael@0: return atom; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_NewUCString(JSContext *cx, jschar *chars, size_t length) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return js_NewString(cx, chars, length); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_NewUCStringCopyN(JSContext *cx, const jschar *s, size_t n) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (!n) michael@0: return cx->names().empty; michael@0: return js_NewStringCopyN(cx, s, n); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_NewUCStringCopyZ(JSContext *cx, const jschar *s) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (!s) michael@0: return cx->runtime()->emptyString; michael@0: return js_NewStringCopyZ(cx, s); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_InternUCStringN(JSContext *cx, const jschar *s, size_t length) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JSAtom *atom = AtomizeChars(cx, s, length, InternAtom); michael@0: JS_ASSERT_IF(atom, JS_StringHasBeenInterned(cx, atom)); michael@0: return atom; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_InternUCString(JSContext *cx, const jschar *s) michael@0: { michael@0: return JS_InternUCStringN(cx, s, js_strlen(s)); michael@0: } michael@0: michael@0: JS_PUBLIC_API(size_t) michael@0: JS_GetStringLength(JSString *str) michael@0: { michael@0: return str->length(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const jschar *) michael@0: JS_GetStringCharsZ(JSContext *cx, JSString *str) michael@0: { michael@0: size_t dummy; michael@0: return JS_GetStringCharsZAndLength(cx, str, &dummy); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const jschar *) michael@0: JS_GetStringCharsZAndLength(JSContext *cx, JSString *str, size_t *plength) michael@0: { michael@0: /* michael@0: * Don't require |cx->compartment()| to be |str|'s compartment. We don't need michael@0: * it, and it's annoying for callers. michael@0: */ michael@0: JS_ASSERT(plength); michael@0: AssertHeapIsIdleOrStringIsFlat(cx, str); michael@0: CHECK_REQUEST(cx); michael@0: JSFlatString *flat = str->ensureFlat(cx); michael@0: if (!flat) michael@0: return nullptr; michael@0: *plength = flat->length(); michael@0: return flat->chars(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const jschar *) michael@0: JS_GetStringCharsAndLength(JSContext *cx, JSString *str, size_t *plength) michael@0: { michael@0: JS_ASSERT(plength); michael@0: AssertHeapIsIdleOrStringIsFlat(cx, str); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, str); michael@0: JSLinearString *linear = str->ensureLinear(cx); michael@0: if (!linear) michael@0: return nullptr; michael@0: *plength = linear->length(); michael@0: return linear->chars(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const jschar *) michael@0: JS_GetInternedStringChars(JSString *str) michael@0: { michael@0: JS_ASSERT(str->isAtom()); michael@0: JSFlatString *flat = str->ensureFlat(nullptr); michael@0: if (!flat) michael@0: return nullptr; michael@0: return flat->chars(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const jschar *) michael@0: JS_GetInternedStringCharsAndLength(JSString *str, size_t *plength) michael@0: { michael@0: JS_ASSERT(str->isAtom()); michael@0: JS_ASSERT(plength); michael@0: JSFlatString *flat = str->ensureFlat(nullptr); michael@0: if (!flat) michael@0: return nullptr; michael@0: *plength = flat->length(); michael@0: return flat->chars(); michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(JSFlatString *) michael@0: JS_FlattenString(JSContext *cx, JSString *str) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, str); michael@0: JSFlatString *flat = str->ensureFlat(cx); michael@0: if (!flat) michael@0: return nullptr; michael@0: return flat; michael@0: } michael@0: michael@0: extern JS_PUBLIC_API(const jschar *) michael@0: JS_GetFlatStringChars(JSFlatString *str) michael@0: { michael@0: return str->chars(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_CompareStrings(JSContext *cx, JSString *str1, JSString *str2, int32_t *result) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: return CompareStrings(cx, str1, str2, result); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_StringEqualsAscii(JSContext *cx, JSString *str, const char *asciiBytes, bool *match) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: JSLinearString *linearStr = str->ensureLinear(cx); michael@0: if (!linearStr) michael@0: return false; michael@0: *match = StringEqualsAscii(linearStr, asciiBytes); michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_FlatStringEqualsAscii(JSFlatString *str, const char *asciiBytes) michael@0: { michael@0: return StringEqualsAscii(str, asciiBytes); michael@0: } michael@0: michael@0: JS_PUBLIC_API(size_t) michael@0: JS_PutEscapedFlatString(char *buffer, size_t size, JSFlatString *str, char quote) michael@0: { michael@0: return PutEscapedString(buffer, size, str, quote); michael@0: } michael@0: michael@0: JS_PUBLIC_API(size_t) michael@0: JS_PutEscapedString(JSContext *cx, char *buffer, size_t size, JSString *str, char quote) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: JSLinearString *linearStr = str->ensureLinear(cx); michael@0: if (!linearStr) michael@0: return size_t(-1); michael@0: return PutEscapedString(buffer, size, linearStr, quote); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_FileEscapedString(FILE *fp, JSString *str, char quote) michael@0: { michael@0: JSLinearString *linearStr = str->ensureLinear(nullptr); michael@0: return linearStr && FileEscapedString(fp, linearStr, quote); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_NewDependentString(JSContext *cx, HandleString str, size_t start, size_t length) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return js_NewDependentString(cx, str, start, length); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_ConcatStrings(JSContext *cx, HandleString left, HandleString right) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return ConcatStrings(cx, left, right); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_DecodeBytes(JSContext *cx, const char *src, size_t srclen, jschar *dst, size_t *dstlenp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: if (!dst) { michael@0: *dstlenp = srclen; michael@0: return true; michael@0: } michael@0: michael@0: size_t dstlen = *dstlenp; michael@0: michael@0: if (srclen > dstlen) { michael@0: InflateStringToBuffer(src, dstlen, dst); michael@0: michael@0: AutoSuppressGC suppress(cx); michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BUFFER_TOO_SMALL); michael@0: return false; michael@0: } michael@0: michael@0: InflateStringToBuffer(src, srclen, dst); michael@0: *dstlenp = srclen; michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(char *) michael@0: JS_EncodeString(JSContext *cx, JSString *str) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: JSLinearString *linear = str->ensureLinear(cx); michael@0: if (!linear) michael@0: return nullptr; michael@0: michael@0: return LossyTwoByteCharsToNewLatin1CharsZ(cx, linear->range()).c_str(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(char *) michael@0: JS_EncodeStringToUTF8(JSContext *cx, HandleString str) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: JSLinearString *linear = str->ensureLinear(cx); michael@0: if (!linear) michael@0: return nullptr; michael@0: michael@0: return TwoByteCharsToNewUTF8CharsZ(cx, linear->range()).c_str(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(size_t) michael@0: JS_GetStringEncodingLength(JSContext *cx, JSString *str) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: const jschar *chars = str->getChars(cx); michael@0: if (!chars) michael@0: return size_t(-1); michael@0: return str->length(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(size_t) michael@0: JS_EncodeStringToBuffer(JSContext *cx, JSString *str, char *buffer, size_t length) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: /* michael@0: * FIXME bug 612141 - fix DeflateStringToBuffer interface so the result michael@0: * would allow to distinguish between insufficient buffer and encoding michael@0: * error. michael@0: */ michael@0: size_t writtenLength = length; michael@0: const jschar *chars = str->getChars(nullptr); michael@0: if (!chars) michael@0: return size_t(-1); michael@0: if (DeflateStringToBuffer(nullptr, chars, str->length(), buffer, &writtenLength)) { michael@0: JS_ASSERT(writtenLength <= length); michael@0: return writtenLength; michael@0: } michael@0: JS_ASSERT(writtenLength <= length); michael@0: size_t necessaryLength = str->length(); michael@0: if (necessaryLength == size_t(-1)) michael@0: return size_t(-1); michael@0: JS_ASSERT(writtenLength == length); // C strings are NOT encoded. michael@0: return necessaryLength; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_Stringify(JSContext *cx, MutableHandleValue vp, HandleObject replacer, michael@0: HandleValue space, JSONWriteCallback callback, void *data) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, replacer, space); michael@0: StringBuffer sb(cx); michael@0: if (!js_Stringify(cx, vp, replacer, space, sb)) michael@0: return false; michael@0: if (sb.empty()) { michael@0: HandlePropertyName null = cx->names().null; michael@0: return callback(null->chars(), null->length(), data); michael@0: } michael@0: return callback(sb.begin(), sb.length(), data); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ParseJSON(JSContext *cx, const jschar *chars, uint32_t len, JS::MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: RootedValue reviver(cx, NullValue()); michael@0: return ParseJSONWithReviver(cx, ConstTwoByteChars(chars, len), len, reviver, vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ParseJSONWithReviver(JSContext *cx, const jschar *chars, uint32_t len, HandleValue reviver, MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return ParseJSONWithReviver(cx, ConstTwoByteChars(chars, len), len, reviver, vp); michael@0: } michael@0: michael@0: /************************************************************************/ michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ReportError(JSContext *cx, const char *format, ...) michael@0: { michael@0: va_list ap; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: va_start(ap, format); michael@0: js_ReportErrorVA(cx, JSREPORT_ERROR, format, ap); michael@0: va_end(ap); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ReportErrorNumber(JSContext *cx, JSErrorCallback errorCallback, michael@0: void *userRef, const unsigned errorNumber, ...) michael@0: { michael@0: va_list ap; michael@0: va_start(ap, errorNumber); michael@0: JS_ReportErrorNumberVA(cx, errorCallback, userRef, errorNumber, ap); michael@0: va_end(ap); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ReportErrorNumberVA(JSContext *cx, JSErrorCallback errorCallback, michael@0: void *userRef, const unsigned errorNumber, michael@0: va_list ap) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: js_ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, michael@0: errorNumber, ArgumentsAreASCII, ap); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ReportErrorNumberUC(JSContext *cx, JSErrorCallback errorCallback, michael@0: void *userRef, const unsigned errorNumber, ...) michael@0: { michael@0: va_list ap; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: va_start(ap, errorNumber); michael@0: js_ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef, michael@0: errorNumber, ArgumentsAreUnicode, ap); michael@0: va_end(ap); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ReportErrorNumberUCArray(JSContext *cx, JSErrorCallback errorCallback, michael@0: void *userRef, const unsigned errorNumber, michael@0: const jschar **args) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: js_ReportErrorNumberUCArray(cx, JSREPORT_ERROR, errorCallback, userRef, michael@0: errorNumber, args); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ReportWarning(JSContext *cx, const char *format, ...) michael@0: { michael@0: va_list ap; michael@0: bool ok; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: va_start(ap, format); michael@0: ok = js_ReportErrorVA(cx, JSREPORT_WARNING, format, ap); michael@0: va_end(ap); michael@0: return ok; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ReportErrorFlagsAndNumber(JSContext *cx, unsigned flags, michael@0: JSErrorCallback errorCallback, void *userRef, michael@0: const unsigned errorNumber, ...) michael@0: { michael@0: va_list ap; michael@0: bool ok; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: va_start(ap, errorNumber); michael@0: ok = js_ReportErrorNumberVA(cx, flags, errorCallback, userRef, michael@0: errorNumber, ArgumentsAreASCII, ap); michael@0: va_end(ap); michael@0: return ok; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ReportErrorFlagsAndNumberUC(JSContext *cx, unsigned flags, michael@0: JSErrorCallback errorCallback, void *userRef, michael@0: const unsigned errorNumber, ...) michael@0: { michael@0: va_list ap; michael@0: bool ok; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: va_start(ap, errorNumber); michael@0: ok = js_ReportErrorNumberVA(cx, flags, errorCallback, userRef, michael@0: errorNumber, ArgumentsAreUnicode, ap); michael@0: va_end(ap); michael@0: return ok; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ReportOutOfMemory(JSContext *cx) michael@0: { michael@0: js_ReportOutOfMemory(cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ReportAllocationOverflow(JSContext *cx) michael@0: { michael@0: js_ReportAllocationOverflow(cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSErrorReporter) michael@0: JS_GetErrorReporter(JSContext *cx) michael@0: { michael@0: return cx->errorReporter; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSErrorReporter) michael@0: JS_SetErrorReporter(JSContext *cx, JSErrorReporter er) michael@0: { michael@0: JSErrorReporter older; michael@0: michael@0: older = cx->errorReporter; michael@0: cx->errorReporter = er; michael@0: return older; michael@0: } michael@0: michael@0: /************************************************************************/ michael@0: michael@0: /* michael@0: * Dates. michael@0: */ michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewDateObject(JSContext *cx, int year, int mon, int mday, int hour, int min, int sec) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return js_NewDateObject(cx, year, mon, mday, hour, min, sec); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewDateObjectMsec(JSContext *cx, double msec) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return js_NewDateObjectMsec(cx, msec); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ObjectIsDate(JSContext *cx, HandleObject obj) michael@0: { michael@0: assertSameCompartment(cx, obj); michael@0: return ObjectClassIs(obj, ESClass_Date, cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ClearDateCaches(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: cx->runtime()->dateTimeInfo.updateTimeZoneAdjustment(); michael@0: } michael@0: michael@0: /************************************************************************/ michael@0: michael@0: /* michael@0: * Regular Expressions. michael@0: */ michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewRegExpObject(JSContext *cx, HandleObject obj, char *bytes, size_t length, unsigned flags) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: jschar *chars = InflateString(cx, bytes, &length); michael@0: if (!chars) michael@0: return nullptr; michael@0: michael@0: RegExpStatics *res = obj->as().getRegExpStatics(); michael@0: RegExpObject *reobj = RegExpObject::create(cx, res, chars, length, michael@0: RegExpFlag(flags), nullptr); michael@0: js_free(chars); michael@0: return reobj; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewUCRegExpObject(JSContext *cx, HandleObject obj, jschar *chars, size_t length, michael@0: unsigned flags) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: RegExpStatics *res = obj->as().getRegExpStatics(); michael@0: return RegExpObject::create(cx, res, chars, length, michael@0: RegExpFlag(flags), nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetRegExpInput(JSContext *cx, HandleObject obj, HandleString input, bool multiline) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, input); michael@0: michael@0: obj->as().getRegExpStatics()->reset(cx, input, !!multiline); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ClearRegExpStatics(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: JS_ASSERT(obj); michael@0: michael@0: obj->as().getRegExpStatics()->clear(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ExecuteRegExp(JSContext *cx, HandleObject obj, HandleObject reobj, jschar *chars, michael@0: size_t length, size_t *indexp, bool test, MutableHandleValue rval) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: RegExpStatics *res = obj->as().getRegExpStatics(); michael@0: michael@0: return ExecuteRegExpLegacy(cx, res, reobj->as(), NullPtr(), chars, length, indexp, michael@0: test, rval); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewRegExpObjectNoStatics(JSContext *cx, char *bytes, size_t length, unsigned flags) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: jschar *chars = InflateString(cx, bytes, &length); michael@0: if (!chars) michael@0: return nullptr; michael@0: RegExpObject *reobj = RegExpObject::createNoStatics(cx, chars, length, michael@0: RegExpFlag(flags), nullptr); michael@0: js_free(chars); michael@0: return reobj; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_NewUCRegExpObjectNoStatics(JSContext *cx, jschar *chars, size_t length, unsigned flags) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: return RegExpObject::createNoStatics(cx, chars, length, michael@0: RegExpFlag(flags), nullptr); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ExecuteRegExpNoStatics(JSContext *cx, HandleObject obj, jschar *chars, size_t length, michael@0: size_t *indexp, bool test, MutableHandleValue rval) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: return ExecuteRegExpLegacy(cx, nullptr, obj->as(), NullPtr(), chars, length, michael@0: indexp, test, rval); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ObjectIsRegExp(JSContext *cx, HandleObject obj) michael@0: { michael@0: assertSameCompartment(cx, obj); michael@0: return ObjectClassIs(obj, ESClass_RegExp, cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(unsigned) michael@0: JS_GetRegExpFlags(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: return obj->as().getFlags(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSString *) michael@0: JS_GetRegExpSource(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: return obj->as().getSource(); michael@0: } michael@0: michael@0: /************************************************************************/ michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_SetDefaultLocale(JSRuntime *rt, const char *locale) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: return rt->setDefaultLocale(locale); michael@0: } michael@0: michael@0: JS_PUBLIC_API(const char*) michael@0: JS_GetDefaultLocale(JSRuntime *rt) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: return rt->getDefaultLocale(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ResetDefaultLocale(JSRuntime *rt) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: rt->resetDefaultLocale(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetLocaleCallbacks(JSRuntime *rt, JSLocaleCallbacks *callbacks) michael@0: { michael@0: AssertHeapIsIdle(rt); michael@0: rt->localeCallbacks = callbacks; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSLocaleCallbacks *) michael@0: JS_GetLocaleCallbacks(JSRuntime *rt) michael@0: { michael@0: /* This function can be called by a finalizer. */ michael@0: return rt->localeCallbacks; michael@0: } michael@0: michael@0: /************************************************************************/ michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsExceptionPending(JSContext *cx) michael@0: { michael@0: /* This function can be called by a finalizer. */ michael@0: return (bool) cx->isExceptionPending(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_GetPendingException(JSContext *cx, MutableHandleValue vp) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (!cx->isExceptionPending()) michael@0: return false; michael@0: return cx->getPendingException(vp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetPendingException(JSContext *cx, HandleValue value) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: cx->setPendingException(value); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ClearPendingException(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: cx->clearPendingException(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ReportPendingException(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: michael@0: // This can only fail due to oom. michael@0: bool ok = js_ReportUncaughtException(cx); michael@0: JS_ASSERT(!cx->isExceptionPending()); michael@0: return ok; michael@0: } michael@0: michael@0: JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext *cx) michael@0: : context(cx), wasThrowing(cx->throwing), exceptionValue(cx) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (wasThrowing) { michael@0: exceptionValue = cx->unwrappedException_; michael@0: cx->clearPendingException(); michael@0: } michael@0: } michael@0: michael@0: void michael@0: JS::AutoSaveExceptionState::restore() michael@0: { michael@0: context->throwing = wasThrowing; michael@0: context->unwrappedException_ = exceptionValue; michael@0: drop(); michael@0: } michael@0: michael@0: JS::AutoSaveExceptionState::~AutoSaveExceptionState() michael@0: { michael@0: if (wasThrowing && !context->isExceptionPending()) { michael@0: context->throwing = true; michael@0: context->unwrappedException_ = exceptionValue; michael@0: } michael@0: } michael@0: michael@0: struct JSExceptionState { michael@0: bool throwing; michael@0: jsval exception; michael@0: }; michael@0: michael@0: JS_PUBLIC_API(JSExceptionState *) michael@0: JS_SaveExceptionState(JSContext *cx) michael@0: { michael@0: JSExceptionState *state; michael@0: michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: state = cx->pod_malloc(); michael@0: if (state) { michael@0: state->throwing = michael@0: JS_GetPendingException(cx, MutableHandleValue::fromMarkedLocation(&state->exception)); michael@0: if (state->throwing && JSVAL_IS_GCTHING(state->exception)) michael@0: AddValueRoot(cx, &state->exception, "JSExceptionState.exception"); michael@0: } michael@0: return state; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_RestoreExceptionState(JSContext *cx, JSExceptionState *state) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (state) { michael@0: if (state->throwing) michael@0: JS_SetPendingException(cx, HandleValue::fromMarkedLocation(&state->exception)); michael@0: else michael@0: JS_ClearPendingException(cx); michael@0: JS_DropExceptionState(cx, state); michael@0: } michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_DropExceptionState(JSContext *cx, JSExceptionState *state) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: if (state) { michael@0: if (state->throwing && JSVAL_IS_GCTHING(state->exception)) { michael@0: assertSameCompartment(cx, state->exception); michael@0: RemoveRoot(cx->runtime(), &state->exception); michael@0: } michael@0: js_free(state); michael@0: } michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSErrorReport *) michael@0: JS_ErrorFromException(JSContext *cx, HandleObject obj) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, obj); michael@0: return js_ErrorFromException(cx, obj); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_ThrowStopIteration(JSContext *cx) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: return js_ThrowStopIteration(cx); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsStopIteration(jsval v) michael@0: { michael@0: return v.isObject() && v.toObject().is(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(intptr_t) michael@0: JS_GetCurrentThread() michael@0: { michael@0: #ifdef JS_THREADSAFE michael@0: return reinterpret_cast(PR_GetCurrentThread()); michael@0: #else michael@0: return 0; michael@0: #endif michael@0: } michael@0: michael@0: extern MOZ_NEVER_INLINE JS_PUBLIC_API(void) michael@0: JS_AbortIfWrongThread(JSRuntime *rt) michael@0: { michael@0: if (!CurrentThreadCanAccessRuntime(rt)) michael@0: MOZ_CRASH(); michael@0: if (!js::TlsPerThreadData.get()->associatedWith(rt)) michael@0: MOZ_CRASH(); michael@0: } michael@0: michael@0: #ifdef JS_GC_ZEAL michael@0: JS_PUBLIC_API(void) michael@0: JS_SetGCZeal(JSContext *cx, uint8_t zeal, uint32_t frequency) michael@0: { michael@0: SetGCZeal(cx->runtime(), zeal, frequency); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_ScheduleGC(JSContext *cx, uint32_t count) michael@0: { michael@0: cx->runtime()->gcNextScheduled = count; michael@0: } michael@0: #endif michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetParallelParsingEnabled(JSRuntime *rt, bool enabled) michael@0: { michael@0: #ifdef JS_ION michael@0: rt->setParallelParsingEnabled(enabled); michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetParallelIonCompilationEnabled(JSRuntime *rt, bool enabled) michael@0: { michael@0: #ifdef JS_ION michael@0: rt->setParallelIonCompilationEnabled(enabled); michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS_SetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt, uint32_t value) michael@0: { michael@0: #ifdef JS_ION michael@0: michael@0: switch (opt) { michael@0: case JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER: michael@0: if (value == uint32_t(-1)) { michael@0: jit::JitOptions defaultValues; michael@0: value = defaultValues.baselineUsesBeforeCompile; michael@0: } michael@0: jit::js_JitOptions.baselineUsesBeforeCompile = value; michael@0: break; michael@0: case JSJITCOMPILER_ION_USECOUNT_TRIGGER: michael@0: if (value == uint32_t(-1)) { michael@0: jit::js_JitOptions.resetUsesBeforeCompile(); michael@0: break; michael@0: } michael@0: jit::js_JitOptions.setUsesBeforeCompile(value); michael@0: if (value == 0) michael@0: jit::js_JitOptions.setEagerCompilation(); michael@0: break; michael@0: case JSJITCOMPILER_ION_ENABLE: michael@0: if (value == 1) { michael@0: JS::RuntimeOptionsRef(rt).setIon(true); michael@0: IonSpew(js::jit::IonSpew_Scripts, "Enable ion"); michael@0: } else if (value == 0) { michael@0: JS::RuntimeOptionsRef(rt).setIon(false); michael@0: IonSpew(js::jit::IonSpew_Scripts, "Disable ion"); michael@0: } michael@0: break; michael@0: case JSJITCOMPILER_BASELINE_ENABLE: michael@0: if (value == 1) { michael@0: JS::RuntimeOptionsRef(rt).setBaseline(true); michael@0: IonSpew(js::jit::IonSpew_BaselineScripts, "Enable baseline"); michael@0: } else if (value == 0) { michael@0: JS::RuntimeOptionsRef(rt).setBaseline(false); michael@0: IonSpew(js::jit::IonSpew_BaselineScripts, "Disable baseline"); michael@0: } michael@0: break; michael@0: case JSJITCOMPILER_PARALLEL_COMPILATION_ENABLE: michael@0: if (value == 1) { michael@0: rt->setParallelIonCompilationEnabled(true); michael@0: IonSpew(js::jit::IonSpew_Scripts, "Enable parallel compilation"); michael@0: } else if (value == 0) { michael@0: rt->setParallelIonCompilationEnabled(false); michael@0: IonSpew(js::jit::IonSpew_Scripts, "Disable parallel compilation"); michael@0: } michael@0: break; michael@0: default: michael@0: break; michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: JS_PUBLIC_API(int) michael@0: JS_GetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt) michael@0: { michael@0: #ifdef JS_ION michael@0: switch (opt) { michael@0: case JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER: michael@0: return jit::js_JitOptions.baselineUsesBeforeCompile; michael@0: case JSJITCOMPILER_ION_USECOUNT_TRIGGER: michael@0: return jit::js_JitOptions.forcedDefaultIonUsesBeforeCompile; michael@0: case JSJITCOMPILER_ION_ENABLE: michael@0: return JS::RuntimeOptionsRef(rt).ion(); michael@0: case JSJITCOMPILER_BASELINE_ENABLE: michael@0: return JS::RuntimeOptionsRef(rt).baseline(); michael@0: case JSJITCOMPILER_PARALLEL_COMPILATION_ENABLE: michael@0: return rt->canUseParallelIonCompilation(); michael@0: default: michael@0: break; michael@0: } michael@0: #endif michael@0: return 0; michael@0: } michael@0: michael@0: /************************************************************************/ michael@0: michael@0: #if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && defined(XP_WIN) michael@0: michael@0: #include "jswin.h" michael@0: michael@0: /* michael@0: * Initialization routine for the JS DLL. michael@0: */ michael@0: BOOL WINAPI DllMain (HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved) michael@0: { michael@0: return TRUE; michael@0: } michael@0: michael@0: #endif michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IndexToId(JSContext *cx, uint32_t index, MutableHandleId id) michael@0: { michael@0: return IndexToId(cx, index, id); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_CharsToId(JSContext* cx, JS::TwoByteChars chars, MutableHandleId idp) michael@0: { michael@0: RootedAtom atom(cx, AtomizeChars(cx, chars.start().get(), chars.length())); michael@0: if (!atom) michael@0: return false; michael@0: #ifdef DEBUG michael@0: uint32_t dummy; michael@0: MOZ_ASSERT(!atom->isIndex(&dummy), "API misuse: |chars| must not encode an index"); michael@0: #endif michael@0: idp.set(AtomToId(atom)); michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_IsIdentifier(JSContext *cx, HandleString str, bool *isIdentifier) michael@0: { michael@0: assertSameCompartment(cx, str); michael@0: michael@0: JSLinearString* linearStr = str->ensureLinear(cx); michael@0: if (!linearStr) michael@0: return false; michael@0: michael@0: *isIdentifier = js::frontend::IsIdentifier(linearStr); michael@0: return true; michael@0: } michael@0: michael@0: namespace JS { michael@0: michael@0: void michael@0: AutoFilename::reset(void *newScriptSource) michael@0: { michael@0: if (newScriptSource) michael@0: reinterpret_cast(newScriptSource)->incref(); michael@0: if (scriptSource_) michael@0: reinterpret_cast(scriptSource_)->decref(); michael@0: scriptSource_ = newScriptSource; michael@0: } michael@0: michael@0: const char * michael@0: AutoFilename::get() const michael@0: { michael@0: JS_ASSERT(scriptSource_); michael@0: return reinterpret_cast(scriptSource_)->filename(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: DescribeScriptedCaller(JSContext *cx, AutoFilename *filename, unsigned *lineno) michael@0: { michael@0: if (lineno) michael@0: *lineno = 0; michael@0: michael@0: NonBuiltinFrameIter i(cx); michael@0: if (i.done()) michael@0: return false; michael@0: michael@0: // If the caller is hidden, the embedding wants us to return false here so michael@0: // that it can check its own stack (see HideScriptedCaller). michael@0: if (i.activation()->scriptedCallerIsHidden()) michael@0: return false; michael@0: michael@0: if (filename) michael@0: filename->reset(i.scriptSource()); michael@0: if (lineno) michael@0: *lineno = i.computeLine(); michael@0: return true; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: GetScriptedCallerGlobal(JSContext *cx) michael@0: { michael@0: NonBuiltinFrameIter i(cx); michael@0: if (i.done()) michael@0: return nullptr; michael@0: michael@0: // If the caller is hidden, the embedding wants us to return null here so michael@0: // that it can check its own stack (see HideScriptedCaller). michael@0: if (i.activation()->scriptedCallerIsHidden()) michael@0: return nullptr; michael@0: michael@0: GlobalObject *global = i.activation()->compartment()->maybeGlobal(); michael@0: michael@0: // Noone should be running code in the atoms compartment or running code in michael@0: // a compartment without any live objects, so there should definitely be a michael@0: // live global. michael@0: JS_ASSERT(global); michael@0: michael@0: return global; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: HideScriptedCaller(JSContext *cx) michael@0: { michael@0: MOZ_ASSERT(cx); michael@0: michael@0: // If there's no accessible activation on the stack, we'll return null from michael@0: // DescribeScriptedCaller anyway, so there's no need to annotate anything. michael@0: Activation *act = cx->runtime()->mainThread.activation(); michael@0: if (!act) michael@0: return; michael@0: act->hideScriptedCaller(); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: UnhideScriptedCaller(JSContext *cx) michael@0: { michael@0: Activation *act = cx->runtime()->mainThread.activation(); michael@0: if (!act) michael@0: return; michael@0: act->unhideScriptedCaller(); michael@0: } michael@0: michael@0: } /* namespace JS */ michael@0: michael@0: #ifdef JS_THREADSAFE michael@0: static PRStatus michael@0: CallOnce(void *func) michael@0: { michael@0: JSInitCallback init = JS_DATA_TO_FUNC_PTR(JSInitCallback, func); michael@0: return init() ? PR_SUCCESS : PR_FAILURE; michael@0: } michael@0: #endif michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_CallOnce(JSCallOnceType *once, JSInitCallback func) michael@0: { michael@0: #ifdef JS_THREADSAFE michael@0: return PR_CallOnceWithArg(once, CallOnce, JS_FUNC_TO_DATA_PTR(void *, func)) == PR_SUCCESS; michael@0: #else michael@0: if (!*once) { michael@0: *once = true; michael@0: return func(); michael@0: } else { michael@0: return true; michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: AutoGCRooter::AutoGCRooter(JSContext *cx, ptrdiff_t tag) michael@0: : down(ContextFriendFields::get(cx)->autoGCRooters), michael@0: tag_(tag), michael@0: stackTop(&ContextFriendFields::get(cx)->autoGCRooters) michael@0: { michael@0: JS_ASSERT(this != *stackTop); michael@0: *stackTop = this; michael@0: } michael@0: michael@0: AutoGCRooter::AutoGCRooter(ContextFriendFields *cx, ptrdiff_t tag) michael@0: : down(cx->autoGCRooters), michael@0: tag_(tag), michael@0: stackTop(&cx->autoGCRooters) michael@0: { michael@0: JS_ASSERT(this != *stackTop); michael@0: *stackTop = this; michael@0: } michael@0: michael@0: #ifdef DEBUG michael@0: JS_PUBLIC_API(void) michael@0: JS::AssertArgumentsAreSane(JSContext *cx, HandleValue value) michael@0: { michael@0: AssertHeapIsIdle(cx); michael@0: CHECK_REQUEST(cx); michael@0: assertSameCompartment(cx, value); michael@0: } michael@0: #endif /* DEBUG */ michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_EncodeScript(JSContext *cx, HandleScript scriptArg, uint32_t *lengthp) michael@0: { michael@0: XDREncoder encoder(cx); michael@0: RootedScript script(cx, scriptArg); michael@0: if (!encoder.codeScript(&script)) michael@0: return nullptr; michael@0: return encoder.forgetData(lengthp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void *) michael@0: JS_EncodeInterpretedFunction(JSContext *cx, HandleObject funobjArg, uint32_t *lengthp) michael@0: { michael@0: XDREncoder encoder(cx); michael@0: RootedObject funobj(cx, funobjArg); michael@0: if (!encoder.codeFunction(&funobj)) michael@0: return nullptr; michael@0: return encoder.forgetData(lengthp); michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSScript *) michael@0: JS_DecodeScript(JSContext *cx, const void *data, uint32_t length, michael@0: JSPrincipals *originPrincipals) michael@0: { michael@0: XDRDecoder decoder(cx, data, length, originPrincipals); michael@0: RootedScript script(cx); michael@0: if (!decoder.codeScript(&script)) michael@0: return nullptr; michael@0: return script; michael@0: } michael@0: michael@0: JS_PUBLIC_API(JSObject *) michael@0: JS_DecodeInterpretedFunction(JSContext *cx, const void *data, uint32_t length, michael@0: JSPrincipals *originPrincipals) michael@0: { michael@0: XDRDecoder decoder(cx, data, length, originPrincipals); michael@0: RootedObject funobj(cx); michael@0: if (!decoder.codeFunction(&funobj)) michael@0: return nullptr; michael@0: return funobj; michael@0: } michael@0: michael@0: JS_PUBLIC_API(bool) michael@0: JS_PreventExtensions(JSContext *cx, JS::HandleObject obj) michael@0: { michael@0: bool extensible; michael@0: if (!JSObject::isExtensible(cx, obj, &extensible)) michael@0: return false; michael@0: if (!extensible) michael@0: return true; michael@0: return JSObject::preventExtensions(cx, obj); michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::SetAsmJSCacheOps(JSRuntime *rt, const JS::AsmJSCacheOps *ops) michael@0: { michael@0: rt->asmJSCacheOps = *ops; michael@0: } michael@0: michael@0: char * michael@0: JSAutoByteString::encodeLatin1(ExclusiveContext *cx, JSString *str) michael@0: { michael@0: JSLinearString *linear = str->ensureLinear(cx); michael@0: if (!linear) michael@0: return nullptr; michael@0: michael@0: mBytes = LossyTwoByteCharsToNewLatin1CharsZ(cx, linear->range()).c_str(); michael@0: return mBytes; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::SetLargeAllocationFailureCallback(JSRuntime *rt, JS::LargeAllocationFailureCallback lafc) michael@0: { michael@0: rt->largeAllocationFailureCallback = lafc; michael@0: } michael@0: michael@0: JS_PUBLIC_API(void) michael@0: JS::SetOutOfMemoryCallback(JSRuntime *rt, OutOfMemoryCallback cb) michael@0: { michael@0: rt->oomCallback = cb; michael@0: } michael@0: