Exemple #1
0
bool
Throw(JSContext* aCx, nsresult aRv, const char* aMessage)
{
  if (JS_IsExceptionPending(aCx)) {
    // Don't clobber the existing exception.
    return false;
  }

  CycleCollectedJSRuntime* runtime = CycleCollectedJSRuntime::Get();
  nsCOMPtr<nsIException> existingException = runtime->GetPendingException();
  if (existingException) {
    nsresult nr;
    if (NS_SUCCEEDED(existingException->GetResult(&nr)) && 
        aRv == nr) {
      // Reuse the existing exception.

      // Clear pending exception
      runtime->SetPendingException(nullptr);

      if (!ThrowExceptionObject(aCx, existingException)) {
        // If we weren't able to throw an exception we're
        // most likely out of memory
        JS_ReportOutOfMemory(aCx);
      }
      return false;
    }
  }

  nsRefPtr<Exception> finalException;

  // Do we use DOM exceptions for this error code?
  switch (NS_ERROR_GET_MODULE(aRv)) {
  case NS_ERROR_MODULE_DOM:
  case NS_ERROR_MODULE_SVG:
  case NS_ERROR_MODULE_DOM_XPATH:
  case NS_ERROR_MODULE_DOM_INDEXEDDB:
  case NS_ERROR_MODULE_DOM_FILEHANDLE:
    finalException = DOMException::Create(aRv);
    break;

  default:
      break;
  }

  // If not, use the default.
  if (!finalException) {
    // aMessage can be null.
    finalException = new Exception(nsCString(aMessage), aRv,
                                   EmptyCString(), nullptr, nullptr);
  }

  MOZ_ASSERT(finalException);
  if (!ThrowExceptionObject(aCx, finalException)) {
    // If we weren't able to throw an exception we're
    // most likely out of memory
    JS_ReportOutOfMemory(aCx);
  }

  return false;
}
Exemple #2
0
nsresult
Dashboard::GetDNSCacheEntries()
{
    JSContext* cx = nsContentUtils::GetSafeJSContext();
    JSAutoRequest request(cx);

    mozilla::dom::DNSCacheDict dict;
    dict.mExpiration.Construct();
    dict.mFamily.Construct();
    dict.mHostaddr.Construct();
    dict.mHostname.Construct();

    Sequence<double> &expiration = dict.mExpiration.Value();
    Sequence<nsString> &family = dict.mFamily.Value();
    Sequence<Sequence<nsString> > &hostaddr = dict.mHostaddr.Value();
    Sequence<nsString> &hostname = dict.mHostname.Value();

    uint32_t length = mDns.data.Length();
    if (!expiration.SetCapacity(length) || !family.SetCapacity(length) ||
        !hostaddr.SetCapacity(length) || !hostname.SetCapacity(length)) {
            mDns.cb = nullptr;
            mDns.data.Clear();
            JS_ReportOutOfMemory(cx);
            return NS_ERROR_OUT_OF_MEMORY;
    }

    for (uint32_t i = 0; i < mDns.data.Length(); i++) {
        CopyASCIItoUTF16(mDns.data[i].hostname, *hostname.AppendElement());
        *expiration.AppendElement() = mDns.data[i].expiration;

        Sequence<nsString> &addrs = *hostaddr.AppendElement();
        if (!addrs.SetCapacity(mDns.data[i].hostaddr.Length())) {
            mDns.cb = nullptr;
            mDns.data.Clear();
            JS_ReportOutOfMemory(cx);
            return NS_ERROR_OUT_OF_MEMORY;
        }
        for (uint32_t j = 0; j < mDns.data[i].hostaddr.Length(); j++) {
            CopyASCIItoUTF16(mDns.data[i].hostaddr[j], *addrs.AppendElement());
        }

        if (mDns.data[i].family == PR_AF_INET6)
            CopyASCIItoUTF16("ipv6", *family.AppendElement());
        else
            CopyASCIItoUTF16("ipv4", *family.AppendElement());
    }

    JS::Value val;
    if (!dict.ToObject(cx, JS::NullPtr(), &val)) {
        mDns.cb = nullptr;
        mDns.data.Clear();
        return NS_ERROR_FAILURE;
    }
    mDns.cb->OnDashboardDataAvailable(val);
    mDns.cb = nullptr;

    return NS_OK;
}
Exemple #3
0
JS_XDRRegisterClass(JSXDRState *xdr, JSClass *clasp, uint32 *idp)
{
    uintN numclasses, maxclasses;
    JSClass **registry;

    numclasses = xdr->numclasses;
    maxclasses = xdr->maxclasses;
    if (numclasses == maxclasses) {
        maxclasses = (maxclasses == 0) ? CLASS_REGISTRY_MIN : maxclasses << 1;
        registry = (JSClass **)
            JS_realloc(xdr->cx, xdr->registry, maxclasses * sizeof(JSClass *));
        if (!registry)
            return JS_FALSE;
        xdr->registry = registry;
        xdr->maxclasses = maxclasses;
    } else {
        JS_ASSERT(numclasses && numclasses < maxclasses);
        registry = xdr->registry;
    }

    registry[numclasses] = clasp;
    if (xdr->reghash) {
        JSRegHashEntry *entry = (JSRegHashEntry *)
            JS_DHashTableOperate(xdr->reghash, clasp->name, JS_DHASH_ADD);
        if (!entry) {
            JS_ReportOutOfMemory(xdr->cx);
            return JS_FALSE;
        }
        entry->name = clasp->name;
        entry->index = numclasses;
    }
    *idp = CLASS_INDEX_TO_ID(numclasses);
    xdr->numclasses = ++numclasses;
    return JS_TRUE;
}
Exemple #4
0
JSBool JsPointBinding::Create(JSContext *context, unsigned int argc, jsval *vp) {
	if (argc == 1) {
		jsval *args = JS_ARGV(context, vp);
		JSObject *jsonObj;
		JS_ValueToObject(context, args[0], &jsonObj);
		jsval xVal;
		JSBool isContainedX = JS_GetProperty(context, jsonObj, "x", &xVal);
		jsval yVal;
		JSBool isContainedY = JS_GetProperty(context, jsonObj, "y", &yVal);
		if (isContainedX == JS_TRUE && isContainedY == JS_TRUE) {
			double x = 0;
			double y = 0;
			JS_ValueToNumber(context, xVal, &x);
			JS_ValueToNumber(context, yVal, &y);
			CCPoint *pPoint = new CCPoint(x, y);

			if (pPoint == NULL) {
				JS_ReportOutOfMemory(context);
				return JS_FALSE;
			}
			JSObject *newObj = JS_NewObject(context, &clz, obj, NULL);
			JS_SetPrivate(context, newObj, pPoint);
			JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(newObj));
		}
	}
	return JS_TRUE;
}
Exemple #5
0
// static
void
XPCThrower::BuildAndThrowException(JSContext* cx, nsresult rv, const char* sz)
{
    JSBool success = false;

    /* no need to set an expection if the security manager already has */
    if (rv == NS_ERROR_XPC_SECURITY_MANAGER_VETO && JS_IsExceptionPending(cx))
        return;
    nsCOMPtr<nsIException> finalException;
    nsCOMPtr<nsIException> defaultException;
    nsXPCException::NewException(sz, rv, nsnull, nsnull, getter_AddRefs(defaultException));

    nsIExceptionManager * exceptionManager = XPCJSRuntime::Get()->GetExceptionManager();
    if (exceptionManager) {
        // Ask the provider for the exception, if there is no provider
        // we expect it to set e to null
        exceptionManager->GetExceptionFromProvider(rv,
                                                   defaultException,
                                                   getter_AddRefs(finalException));
        // We should get at least the defaultException back,
        // but just in case
        if (finalException == nsnull) {
            finalException = defaultException;
        }
    }

    // XXX Should we put the following test and call to JS_ReportOutOfMemory
    // inside this test?
    if (finalException)
        success = ThrowExceptionObject(cx, finalException);
    // If we weren't able to build or throw an exception we're
    // most likely out of memory
    if (!success)
        JS_ReportOutOfMemory(cx);
}
Exemple #6
0
/*
 * Convert a JavaSignature object into a string format as used by
 * the JNI functions, e.g. java.lang.Object ==> "Ljava/lang/Object;"
 * The caller is responsible for freeing the resulting string.
 *
 * If an error is encountered, NULL is returned and an error reported.
 */
const char *
jsj_ConvertJavaSignatureToString(JSContext *cx, JavaSignature *signature)
{
    char *sig;

    if (IS_OBJECT_TYPE(signature->type)) {
        /* A non-array object class */
        sig = JS_smprintf("L%s;", signature->name);
        if (sig)
            jsj_MakeJNIClassname(sig);

    } else if (signature->type == JAVA_SIGNATURE_ARRAY) {
        /* An array class */
        const char *component_signature_string;

        component_signature_string =
            jsj_ConvertJavaSignatureToString(cx, signature->array_component_signature);
        if (!component_signature_string)
            return NULL;
        sig = JS_smprintf("[%s", component_signature_string);
        JS_smprintf_free((char*)component_signature_string);

    } else {
        /* A primitive class */
        sig = JS_smprintf("%c", get_jdk_signature_char(signature->type));
    }

    if (!sig) {
        JS_ReportOutOfMemory(cx);
        return NULL;
    }
    return sig;
}
Exemple #7
0
/*
 * Convert a JavaSignature object into a human-readable string format as seen
 * in Java source files, e.g. "byte", or "int[][]" or "java.lang.String".
 * The caller is responsible for freeing the resulting string.
 *
 * If an error is encountered, NULL is returned and an error reported.
 */
const char *
jsj_ConvertJavaSignatureToHRString(JSContext *cx,
                                   JavaSignature *signature)
{
    char *sig;
    JavaSignature *acs;

    if (signature->type == JAVA_SIGNATURE_ARRAY) {
        /* An array class */
        const char *component_signature_string;
        acs = signature->array_component_signature;
        component_signature_string =
            jsj_ConvertJavaSignatureToHRString(cx, acs);
        if (!component_signature_string)
            return NULL;
        sig = JS_smprintf("%s[]", component_signature_string);
        JS_smprintf_free((char*)component_signature_string);

    } else {
        /* A primitive class or a non-array object class */
        sig = JS_smprintf("%s", signature->name);
    }

    if (!sig) {
        JS_ReportOutOfMemory(cx);
        return NULL;
    }
    return sig;
}
Exemple #8
0
PJS_EXTERN JSBool
PJS_Call_js_function(
    pTHX_
    JSContext *cx,
    JSObject *gobj,
    jsval func,
    AV *av,
    jsval *rval
) {
    jsval *arg_list;
    SV *val;
    int arg_count, i;
    JSBool res;
    
    arg_count = av_len(av);

    Newz(1, arg_list, arg_count + 1, jsval);
    if(!arg_list) {
	JS_ReportOutOfMemory(cx);
	return JS_FALSE;
    }

    for(i = 0; i <= arg_count; i++) {
        val = *av_fetch(av, i, 0);

        if (!PJS_ReflectPerl2JS(aTHX_ cx, gobj, val, &(arg_list[i]))) {
            Safefree(arg_list);
            croak("Can't convert argument number %d to jsval", i);
        }
    }
    res = JS_CallFunctionValue(cx, gobj, func, i, arg_list, rval);
    Safefree(arg_list);
    return res;
}
NS_IMETHODIMP
nsJetpack::NewResolve(nsIXPConnectWrappedNative *wrapper,
                      JSContext * cx, JSObject * obj,
                      jsval id, PRUint32 flags,
                      JSObject * *objp, PRBool *_retval)
{
  if (JSVAL_IS_STRING(id) &&
      strncmp(JS_GetStringBytes(JSVAL_TO_STRING(id)), "get", 3) == 0) {
    JSFunction *get = JS_NewFunction(cx, getEndpoint, 0, 0, 
                                     JS_GetParent(cx, obj), "get");
    if (!get) {
      JS_ReportOutOfMemory(cx);
      *_retval = PR_FALSE;
      return NS_OK;
    }
      
    JSObject *getObj = JS_GetFunctionObject(get);

    jsid idid;
    *objp = obj;
    *_retval = (JS_ValueToId(cx, id, &idid) &&
                JS_DefinePropertyById(cx, obj, idid,
                                      OBJECT_TO_JSVAL(getObj),
                                      nsnull, nsnull,
                                      JSPROP_ENUMERATE |
                                      JSPROP_READONLY |
                                      JSPROP_PERMANENT));
    return NS_OK;
  }

  *objp = nsnull;
  *_retval = PR_TRUE;

  return NS_OK;
}
Exemple #10
0
static JSAtom *
js_AtomizeHashedKey(JSContext *cx, jsval key, JSHashNumber keyHash, uintN flags)
{
    JSAtomState *state;
    JSHashTable *table;
    JSHashEntry *he, **hep;
    JSAtom *atom;

    state = &cx->runtime->atomState;
    JS_LOCK(&state->lock, cx);
    table = state->table;
    hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
    if ((he = *hep) == NULL) {
        he = JS_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
        if (!he) {
            JS_ReportOutOfMemory(cx);
            atom = NULL;
            goto out;
        }
    }

    atom = (JSAtom *)he;
    atom->flags |= flags;
out:
    JS_UNLOCK(&state->lock,cx);
    return atom;
}
Exemple #11
0
static JSAtom *
js_AtomizeHashedKey(JSContext *cx, jsval key, PRHashNumber keyHash, uintN flags)
{
    PRHashTable *table;
    PRHashEntry *he, **hep;
    JSAtom *atom;

    PR_ASSERT(JS_IS_LOCKED(cx));
    table = cx->runtime->atomState.table;
    hep = PR_HashTableRawLookup(table, keyHash, (void *)key);
    if ((he = *hep) == NULL) {
	he = PR_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
	if (!he) {
	    JS_ReportOutOfMemory(cx);
	    return NULL;
	}
    }

    atom = (JSAtom *)he;
#ifdef DEBUG_DUPLICATE_ATOMS
    hep = PR_HashTableRawLookup(table, keyHash, (void *)key);
    he = *hep;
    PR_ASSERT(atom == (JSAtom *)he);
#endif

    if (flags & ATOM_NOHOLD)
	return atom;
    return js_HoldAtom(cx, atom);
}
Exemple #12
0
static JSBool
GrowTokenBuf(JSContext *cx, JSTokenBuf *tb)
{
    jschar *base;
    ptrdiff_t offset, length;
    size_t tbsize;
    JSArenaPool *pool;

    base = tb->base;
    offset = PTRDIFF(tb->ptr, base, jschar);
    pool = &cx->tempPool;
    if (!base) {
        tbsize = TBMIN * sizeof(jschar);
        length = TBMIN;
        JS_ARENA_ALLOCATE_CAST(base, jschar *, pool, tbsize);
    } else {
        length = PTRDIFF(tb->limit, base, jschar);
        tbsize = length * sizeof(jschar);
        length <<= 1;
        JS_ARENA_GROW_CAST(base, jschar *, pool, tbsize, tbsize);
    }
    if (!base) {
        JS_ReportOutOfMemory(cx);
        return JS_FALSE;
    }
    tb->base = base;
    tb->limit = base + length;
    tb->ptr = base + offset;
    return JS_TRUE;
}
Exemple #13
0
bool
Throw(JSContext* aCx, nsresult aRv, const nsACString& aMessage)
{
  if (aRv == NS_ERROR_UNCATCHABLE_EXCEPTION) {
    // Nuke any existing exception on aCx, to make sure we're uncatchable.
    JS_ClearPendingException(aCx);
    return false;
  }

  if (JS_IsExceptionPending(aCx)) {
    // Don't clobber the existing exception.
    return false;
  }

  CycleCollectedJSRuntime* runtime = CycleCollectedJSRuntime::Get();
  nsCOMPtr<nsIException> existingException = runtime->GetPendingException();
  // Make sure to clear the pending exception now.  Either we're going to reuse
  // it (and we already grabbed it), or we plan to throw something else and this
  // pending exception is no longer relevant.
  runtime->SetPendingException(nullptr);

  // Ignore the pending exception if we have a non-default message passed in.
  if (aMessage.IsEmpty() && existingException) {
    nsresult nr;
    if (NS_SUCCEEDED(existingException->GetResult(&nr)) &&
        aRv == nr) {
      // Reuse the existing exception.
      if (!ThrowExceptionObject(aCx, existingException)) {
        // If we weren't able to throw an exception we're
        // most likely out of memory
        JS_ReportOutOfMemory(aCx);
      }
      return false;
    }
  }

  RefPtr<Exception> finalException = CreateException(aCx, aRv, aMessage);

  MOZ_ASSERT(finalException);
  if (!ThrowExceptionObject(aCx, finalException)) {
    // If we weren't able to throw an exception we're
    // most likely out of memory
    JS_ReportOutOfMemory(aCx);
  }

  return false;
}
Exemple #14
0
bool
Throw(JSContext* aCx, nsresult aRv, const char* aMessage)
{
  if (aRv == NS_ERROR_UNCATCHABLE_EXCEPTION) {
    // Nuke any existing exception on aCx, to make sure we're uncatchable.
    JS_ClearPendingException(aCx);
    return false;
  }

  if (JS_IsExceptionPending(aCx)) {
    // Don't clobber the existing exception.
    return false;
  }

  CycleCollectedJSRuntime* runtime = CycleCollectedJSRuntime::Get();
  nsCOMPtr<nsIException> existingException = runtime->GetPendingException();
  if (existingException) {
    nsresult nr;
    if (NS_SUCCEEDED(existingException->GetResult(&nr)) && 
        aRv == nr) {
      // Reuse the existing exception.

      // Clear pending exception
      runtime->SetPendingException(nullptr);

      if (!ThrowExceptionObject(aCx, existingException)) {
        // If we weren't able to throw an exception we're
        // most likely out of memory
        JS_ReportOutOfMemory(aCx);
      }
      return false;
    }
  }

  nsRefPtr<Exception> finalException = CreateException(aCx, aRv, aMessage);

  MOZ_ASSERT(finalException);
  if (!ThrowExceptionObject(aCx, finalException)) {
    // If we weren't able to throw an exception we're
    // most likely out of memory
    JS_ReportOutOfMemory(aCx);
  }

  return false;
}
Exemple #15
0
js_alloc_temp_space(void *priv, size_t size)
{
    JSContext *cx = priv;
    void *space;

    JS_ARENA_ALLOCATE(space, &cx->tempPool, size);
    if (!space)
        JS_ReportOutOfMemory(cx);
    return space;
}
Exemple #16
0
js_alloc_temp_entry(void *priv, const void *key)
{
    JSContext *cx = priv;
    JSAtomListElement *ale;

    JS_ARENA_ALLOCATE_TYPE(ale, JSAtomListElement, &cx->tempPool);
    if (!ale) {
        JS_ReportOutOfMemory(cx);
        return NULL;
    }
    return &ale->entry;
}
Exemple #17
0
bool JSGlobal::JS_setInterval(JSContext *cx, JS::CallArgs &args)
{
    struct nidium_sm_timer *params;
    int ms = 0, i;
    int argc = args.length();

    params = new nidium_sm_timer(cx);

    if (!params) {
        JS_ReportOutOfMemory(cx);
        return false;
    }

    params->cx     = cx;
    params->global = m_Instance;
    params->argc   = nidium_max(0, argc - 2);

    params->argv = new JS::PersistentRootedValue *[params->argc];

    for (i = 0; i < argc - 2; i++) {
        params->argv[i] = new JS::PersistentRootedValue(cx);
    }

    if (!JSUtils::ReportIfNotFunction(cx, args[0])) {
        delete[] params->argv;
        delete params;
        return false;
    }

    params->func = args[0];

    if (argc > 1 && !JS::ToInt32(cx, args[1], &ms)) {
        ms = 0;
    }

    params->ms = nidium_max(8, ms);

    for (i = 0; i < static_cast<int>(argc) - 2; i++) {
        *params->argv[i] = args.array()[i + 2];
    }

    ape_timer_t *timer = APE_timer_create(
        static_cast<ape_global *>(JS_GetContextPrivate(cx)), params->ms,
        nidium_timerng_wrapper, static_cast<void *>(params));

    APE_timer_unprotect(timer);
    APE_timer_setclearfunc(timer, nidium_timer_deleted);

    args.rval().setNumber(static_cast<double>(APE_timer_getid(timer)));

    return true;
}
Exemple #18
0
JSAtom *
js_AtomizeDouble(JSContext *cx, jsdouble d)
{
    JSAtomState *state;
    JSDHashTable *table;
    JSAtomHashEntry *entry;
    uint32 gen;
    jsdouble *key;
    jsval v;

    state = &cx->runtime->atomState;
    table = &state->doubleAtoms;

    JS_LOCK(cx, &state->lock);
    entry = TO_ATOM_ENTRY(JS_DHashTableOperate(table, &d, JS_DHASH_ADD));
    if (!entry)
        goto failed_hash_add;
    if (entry->keyAndFlags == 0) {
        gen = ++table->generation;
        JS_UNLOCK(cx, &state->lock);

        key = js_NewWeaklyRootedDouble(cx, d);
        if (!key)
            return NULL;

        JS_LOCK(cx, &state->lock);
        if (table->generation == gen) {
            JS_ASSERT(entry->keyAndFlags == 0);
        } else {
            entry = TO_ATOM_ENTRY(JS_DHashTableOperate(table, key,
                                                       JS_DHASH_ADD));
            if (!entry)
                goto failed_hash_add;
            if (entry->keyAndFlags != 0)
                goto finish;
            ++table->generation;
        }
        INIT_ATOM_ENTRY(entry, key);
    }

  finish:
    v = DOUBLE_TO_JSVAL((jsdouble *)ATOM_ENTRY_KEY(entry));
    cx->weakRoots.lastAtom = v;
    JS_UNLOCK(cx, &state->lock);

    return (JSAtom *)v;

  failed_hash_add:
    JS_UNLOCK(cx, &state->lock);
    JS_ReportOutOfMemory(cx);
    return NULL;
}
Exemple #19
0
static JSBool
evalcx(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
    JSString *str;
    JSObject *sandbox;
    JSContext *subcx;
    const jschar *src;
    size_t srclen;
    JSBool ret = JS_FALSE;
    char *name = NULL;

    sandbox = NULL;
    if(!JS_ConvertArguments(cx, argc, argv, "S / o", &str, &sandbox)) {
        return JS_FALSE;
    }

    subcx = JS_NewContext(JS_GetRuntime(cx), 8L * 1024L);
    if(!subcx) {
        JS_ReportOutOfMemory(cx);
        return JS_FALSE;
    }

    SETUP_REQUEST(subcx);

    src = JS_GetStringChars(str);
    srclen = JS_GetStringLength(str);

    if(!sandbox) {
        sandbox = JS_NewObject(subcx, NULL, NULL, NULL);
        if(!sandbox || !JS_InitStandardClasses(subcx, sandbox)) {
            goto done;
        }
    }

    if(argc > 2) {
      name = enc_string(cx, argv[2], NULL);
    }

    if(srclen == 0) {
        *rval = OBJECT_TO_JSVAL(sandbox);
    } else {
        JS_EvaluateUCScript(subcx, sandbox, src, srclen, name, 1, rval);
    }
    
    ret = JS_TRUE;

done:
    if(name) JS_free(cx, name);
    FINISH_REQUEST(subcx);
    JS_DestroyContext(subcx);
    return ret;
}
Exemple #20
0
JSAtom *
js_AtomizeDouble(JSContext *cx, jsdouble d, uintN flags)
{
    jsdouble *dp;
    JSHashNumber keyHash;
    jsval key;
    JSAtomState *state;
    JSHashTable *table;
    JSHashEntry *he, **hep;
    JSAtom *atom;
    char buf[2 * ALIGNMENT(double)];

    dp = ALIGN(buf, double);
    *dp = d;
    keyHash = HASH_DOUBLE(dp);
    key = DOUBLE_TO_JSVAL(dp);
    state = &cx->runtime->atomState;
    JS_LOCK(&state->lock, cx);
    table = state->table;
    hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
    if ((he = *hep) == NULL) {
#ifdef JS_THREADSAFE
        uint32 gen = state->tablegen;
#endif
        JS_UNLOCK(&state->lock,cx);
        if (!js_NewDoubleValue(cx, d, &key))
            return NULL;
        JS_LOCK(&state->lock, cx);
#ifdef JS_THREADSAFE
        if (state->tablegen != gen) {
            hep = JS_HashTableRawLookup(table, keyHash, (void *)key);
            if ((he = *hep) != NULL) {
                atom = (JSAtom *)he;
                goto out;
            }
        }
#endif
        he = JS_HashTableRawAdd(table, hep, keyHash, (void *)key, NULL);
        if (!he) {
            JS_ReportOutOfMemory(cx);
            atom = NULL;
            goto out;
        }
    }

    atom = (JSAtom *)he;
    atom->flags |= flags;
    cx->lastAtom = atom;
out:
    JS_UNLOCK(&state->lock,cx);
    return atom;
}
Exemple #21
0
nsresult
Dashboard::GetWebSocketConnections()
{
    JSContext* cx = nsContentUtils::GetSafeJSContext();
    JSAutoRequest request(cx);

    mozilla::dom::WebSocketDict dict;
    dict.mEncrypted.Construct();
    dict.mHostport.Construct();
    dict.mMsgreceived.Construct();
    dict.mMsgsent.Construct();
    dict.mReceivedsize.Construct();
    dict.mSentsize.Construct();

    Sequence<bool> &encrypted = dict.mEncrypted.Value();
    Sequence<nsString> &hostport = dict.mHostport.Value();
    Sequence<uint32_t> &received = dict.mMsgreceived.Value();
    Sequence<uint32_t> &sent = dict.mMsgsent.Value();
    Sequence<double> &receivedSize = dict.mReceivedsize.Value();
    Sequence<double> &sentSize = dict.mSentsize.Value();

    uint32_t length = mWs.data.Length();
    if (!encrypted.SetCapacity(length) || !hostport.SetCapacity(length) ||
        !received.SetCapacity(length) || !sent.SetCapacity(length) ||
        !receivedSize.SetCapacity(length) || !sentSize.SetCapacity(length)) {
            mWs.cb = nullptr;
            mWs.data.Clear();
            JS_ReportOutOfMemory(cx);
            return NS_ERROR_OUT_OF_MEMORY;
    }

    mozilla::MutexAutoLock lock(mWs.lock);
    for (uint32_t i = 0; i < mWs.data.Length(); i++) {
        CopyASCIItoUTF16(mWs.data[i].mHost, *hostport.AppendElement());
        *sent.AppendElement() = mWs.data[i].mMsgSent;
        *received.AppendElement() = mWs.data[i].mMsgReceived;
        *receivedSize.AppendElement() = mWs.data[i].mSizeSent;
        *sentSize.AppendElement() = mWs.data[i].mSizeReceived;
        *encrypted.AppendElement() = mWs.data[i].mEncrypted;
    }

    JS::Value val;
    if (!dict.ToObject(cx, JS::NullPtr(), &val)) {
        mWs.cb = nullptr;
        mWs.data.Clear();
        return NS_ERROR_FAILURE;
    }
    mWs.cb->OnDashboardDataAvailable(val);
    mWs.cb = nullptr;

    return NS_OK;
}
JSBool
JetpackChild::CallMessage(JSContext* cx, uintN argc, jsval* vp)
{
  MessageResult smr;
  if (!MessageCommon(cx, argc, vp, &smr))
    return JS_FALSE;

  InfallibleTArray<Variant> results;
  if (!GetThis(cx)->CallCallMessage(smr.msgName, smr.data, &results)) {
    JS_ReportError(cx, "Failed to callMessage");
    return JS_FALSE;
  }

  nsAutoTArray<jsval, 4> jsvals;
  jsval* rvals = jsvals.AppendElements(results.Length());
  if (!rvals) {
    JS_ReportOutOfMemory(cx);
    return JS_FALSE;
  }
  for (PRUint32 i = 0; i < results.Length(); ++i)
    rvals[i] = JSVAL_VOID;
  js::AutoArrayRooter root(cx, results.Length(), rvals);

  for (PRUint32 i = 0; i < results.Length(); ++i)
    if (!jsval_from_Variant(cx, results.ElementAt(i), rvals + i)) {
      JS_ReportError(cx, "Invalid result from handler %d", i);
      return JS_FALSE;
    }

  JSObject* arrObj = JS_NewArrayObject(cx, results.Length(), rvals);
  if (!arrObj) {
    JS_ReportOutOfMemory(cx);
    return JS_FALSE;
  }
  JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(arrObj));

  return JS_TRUE;
}
Exemple #23
0
JSObject *query_InitObject(JSContext *cx, JSObject *moduleObject)
{
  JSObject 		*queryObject;
  query_private_t	*hnd;

  static JSClass query_class = 	/* not exposed to JS, but finalizer needed when GC */
  {	
    GPSEE_CLASS_NAME(Query),
    JSCLASS_HAS_PRIVATE,
    JS_PropertyStub,  
    JS_PropertyStub,  
    JS_PropertyStub,  
    JS_PropertyStub,
    JS_EnumerateStub, 
    JS_ResolveStub,   
    JS_ConvertStub,   
    query_Finalize,
    JSCLASS_NO_OPTIONAL_MEMBERS
  };

  static JSFunctionSpec query_methods[] = 
  {
    { "readQuery",		query_readQuery,		2, 0, 0 },
    { NULL,			NULL,				0, 0, 0 }
  };

  static JSPropertySpec query_props[] = 
  {
    { NULL, 0, 0, NULL, NULL }
  };

  queryObject = JS_NewObject(cx, &query_class, NULL, moduleObject);
  if (!queryObject)
    return NULL;

  if (!JS_DefineFunctions(cx, queryObject, query_methods) || !JS_DefineProperties(cx, queryObject, query_props))
    return NULL;

  hnd = JS_malloc(cx, sizeof(*hnd));
  if (!hnd)
  {
    JS_ReportOutOfMemory(cx);
    return NULL;
  }

  memset(hnd, 0, sizeof(*hnd));
  JS_SetPrivate(cx, queryObject, hnd);

  return queryObject;
}
Exemple #24
0
/*
 * Sets current thread as owning thread of a context by assigning the
 * thread-private info to the context. If the current thread doesn't have
 * private JSThread info, create one.
 */
JSBool
js_SetContextThread(JSContext *cx)
{
    JSThread *thread = js_GetCurrentThread(cx->runtime);

    if (!thread) {
        JS_ReportOutOfMemory(cx);
        return JS_FALSE;
    }
    cx->thread = thread;
    JS_REMOVE_LINK(&cx->threadLinks);
    JS_APPEND_LINK(&cx->threadLinks, &thread->contextList);
    return JS_TRUE;
}
Exemple #25
0
static JSBool
evalcx(JSContext *cx, uintN argc, jsval* vp)
{
    jsval* argv = JS_ARGV(cx, vp);
    JSString *str;
    JSObject *sandbox;
    JSContext *subcx;
    const jschar *src;
    size_t srclen;
    jsval rval;
    JSBool ret = JS_FALSE;

    sandbox = NULL;
    if(!JS_ConvertArguments(cx, argc, argv, "S / o", &str, &sandbox)) {
        return JS_FALSE;
    }

    subcx = JS_NewContext(JS_GetRuntime(cx), 8L * 1024L);
    if(!subcx) {
        JS_ReportOutOfMemory(cx);
        return JS_FALSE;
    }

    SETUP_REQUEST(subcx);

    src = JS_GetStringChars(str);
    srclen = JS_GetStringLength(str);

    if(!sandbox) {
        sandbox = JS_NewObject(subcx, NULL, NULL, NULL);
        if(!sandbox || !JS_InitStandardClasses(subcx, sandbox)) {
            goto done;
        }
    }

    if(srclen == 0) {
        JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(sandbox));
    } else {
        JS_EvaluateUCScript(subcx, sandbox, src, srclen, NULL, 0, &rval);
        JS_SET_RVAL(cx, vp, rval);
    }

    ret = JS_TRUE;

done:
    FINISH_REQUEST(subcx);
    JS_DestroyContext(subcx);
    return ret;
}
Exemple #26
0
PRHashEntry *
js_EnterSharpObject(JSContext *cx, JSObject *obj, jschar **sp)
{
    JSSharpObjectMap *map;
    PRHashTable *table;
    PRHashNumber hash;
    PRHashEntry *he;
    jsatomid sharpid;
    char buf[20];
    size_t len;

    map = &cx->sharpObjectMap;
    table = map->table;
    if (!table) {
	table = PR_NewHashTable(8, js_hash_object, PR_CompareValues,
				PR_CompareValues, NULL, NULL);
	if (!table) {
	    JS_ReportOutOfMemory(cx);
	    return NULL;
	}
	map->table = table;
    }

    if (map->depth == 0) {
	he = MarkSharpObjects(cx, obj);
	if (!he)
	    return NULL;
    } else {
	hash = js_hash_object(obj);
	he = *PR_HashTableRawLookup(table, hash, obj);
	PR_ASSERT(he);
    }

    sharpid = (jsatomid) he->value;
    if (sharpid == 0) {
	*sp = NULL;
    } else {
	len = PR_snprintf(buf, sizeof buf, "#%u%c",
			  sharpid >> 1, (sharpid & SHARP_BIT) ? '#' : '=');
	*sp = js_InflateString(cx, buf, len);
	if (!*sp)
	    return NULL;
    }

    if ((sharpid & SHARP_BIT) == 0)
	map->depth++;
    return he;
}
Exemple #27
0
JSBool
js_InitAtomState(JSContext *cx, JSAtomState *state)
{
    uintN i;

    state->number = 0;
    state->table = PR_NewHashTable(JS_ATOM_HASH_SIZE, js_hash_atom_key,
				   js_compare_atom_keys, js_compare_stub,
				   &atomAllocOps, state);
    if (!state->table) {
	JS_ReportOutOfMemory(cx);
	return JS_FALSE;
    }

#define FROB(lval,str) {                                                      \
    if (!(state->lval = js_Atomize(cx, str, strlen(str), 0))) {               \
	js_FreeAtomState(cx, state);                                          \
	return JS_FALSE;                                                      \
    }                                                                         \
}

    PR_ASSERT(sizeof js_type_str / sizeof js_type_str[0] == JSTYPE_LIMIT);
    for (i = 0; i < JSTYPE_LIMIT; i++)
	FROB(typeAtoms[i],        js_type_str[i]);

    FROB(booleanAtoms[0],         js_false_str);
    FROB(booleanAtoms[1],         js_true_str);
    FROB(nullAtom,                js_null_str);

    FROB(ArrayAtom,               js_Array_str);
    FROB(ObjectAtom,              js_Object_str);
    FROB(anonymousAtom,           js_anonymous_str);
    FROB(assignAtom,              js_assign_str);
    FROB(classPrototypeAtom,      js_class_prototype_str);
    FROB(constructorAtom,         js_constructor_str);
    FROB(countAtom,               js_count_str);
    FROB(indexAtom,               js_index_str);
    FROB(inputAtom,               js_input_str);
    FROB(lengthAtom,              js_length_str);
    FROB(parentAtom,              js_parent_str);
    FROB(protoAtom,               js_proto_str);
    FROB(toStringAtom,            js_toString_str);
    FROB(valueOfAtom,             js_valueOf_str);

#undef FROB

    return JS_TRUE;
}
Exemple #28
0
JavaPackage_convert(JSContext *cx, JSObject *obj, JSType type, jsval *vp)
{
    JSString *str;
    char *name, *cp;

    JavaPackage_Private *package = JS_GetPrivate(cx, obj);
    if (!package) {
        fprintf(stderr, "JavaPackage_resolve: no private data!\n");
        return JS_FALSE;
    }

    switch (type) {

    /* Pretty-printing of JavaPackage */
    case JSTYPE_VOID:   /* Default value */
    case JSTYPE_NUMBER:
    case JSTYPE_STRING:
        /* Convert '/' to '.' so that it looks like Java language syntax. */
        if (!package->path)
            break;
        name = JS_smprintf("[JavaPackage %s]", package->path);
        if (!name) {
            JS_ReportOutOfMemory(cx);
            return JS_FALSE;
        }
        for (cp = name; *cp != '\0'; cp++)
            if (*cp == '/')
                *cp = '.';
        str = JS_NewString(cx, name, strlen(name));
        if (!str) {
            free(name);
            /* It's not necessary to call JS_ReportOutOfMemory(), as
               JS_NewString() will do so on failure. */
            return JS_FALSE;
        }

        *vp = STRING_TO_JSVAL(str);
        break;

    case JSTYPE_OBJECT:
        *vp = OBJECT_TO_JSVAL(obj);
        break;

    default:
        break;
    }
    return JS_TRUE;
}
Exemple #29
0
    static bool chk(JSContext *cx, unsigned argc, jsval *vp)
    {
        JSRuntime *rt = JS_GetRuntime(cx);
        JSContext *acx = JS_NewContext(rt, 8192);
        if (!acx) {
            JS_ReportOutOfMemory(cx);
            return false;
        }

        // acx should not be running
        bool ok = !JS_IsRunning(acx);
        if (!ok)
            JS_ReportError(cx, "Assertion failed: brand new context claims to be running");
        JS_DestroyContext(acx);
        return ok;
    }
    static JSBool chk(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
    {
        JSRuntime *rt = JS_GetRuntime(cx);
        JSContext *acx = JS_NewContext(rt, 8192);
        if (!acx) {
            JS_ReportOutOfMemory(cx);
            return JS_FALSE;
        }

        // acx should not be running
        bool ok = !JS_IsRunning(acx);
        if (!ok)
            JS_ReportError(cx, "Assertion failed: brand new context claims to be running");
        JS_DestroyContext(acx);
        return ok;
    }