static JSBool teletone_generate(JSContext * cx, JSObject * obj, uintN argc, jsval * argv, jsval * rval) { struct teletone_obj *tto = JS_GetPrivate(cx, obj); int32 loops = 0; if (argc > 0) { char *script; switch_core_session_t *session; switch_frame_t write_frame = { 0 }; unsigned char *fdata[1024]; switch_frame_t *read_frame; switch_channel_t *channel; if (argc > 1) { if (!JS_ValueToInt32(cx, argv[1], &loops)) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Cannot Convert to INT\n"); return JS_FALSE; } loops--; } if (tto->audio_buffer) { switch_buffer_zero(tto->audio_buffer); } tto->ts.debug = 1; tto->ts.debug_stream = switch_core_get_console(); script = JS_GetStringBytes(JS_ValueToString(cx, argv[0])); teletone_run(&tto->ts, script); session = tto->session; write_frame.codec = &tto->codec; write_frame.data = fdata; write_frame.buflen = sizeof(fdata); channel = switch_core_session_get_channel(session); if (tto->timer) { switch_core_service_session(session); } if (loops) { switch_buffer_set_loops(tto->audio_buffer, loops); } for (;;) { if (switch_test_flag(tto, TTF_DTMF)) { char dtmf[128]; char *ret; if (switch_channel_has_dtmf(channel)) { uintN aargc = 0; jsval aargv[4]; switch_channel_dequeue_dtmf_string(channel, dtmf, sizeof(dtmf)); aargv[aargc++] = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, dtmf)); JS_CallFunction(cx, obj, tto->function, aargc, aargv, &tto->ret); ret = JS_GetStringBytes(JS_ValueToString(cx, tto->ret)); if (strcmp(ret, "true") && strcmp(ret, "undefined")) { *rval = tto->ret; return JS_TRUE; } } } if (tto->timer) { if (switch_core_timer_next(tto->timer) != SWITCH_STATUS_SUCCESS) { break; } } else { switch_status_t status; status = switch_core_session_read_frame(session, &read_frame, SWITCH_IO_FLAG_NONE, 0); if (!SWITCH_READ_ACCEPTABLE(status)) { break; } } if ((write_frame.datalen = (uint32_t) switch_buffer_read_loop(tto->audio_buffer, fdata, write_frame.codec->implementation->decoded_bytes_per_packet)) <= 0) { break; } write_frame.samples = write_frame.datalen / 2; if (switch_core_session_write_frame(session, &write_frame, SWITCH_IO_FLAG_NONE, 0) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Bad Write\n"); break; } } if (tto->timer) { switch_core_thread_session_end(session); } return JS_TRUE; } return JS_FALSE; }
static JSBool InitExceptionObject(JSContext *cx, JSObject *obj, JSString *message, JSString *filename, uintN lineno) { JSCheckAccessOp checkAccess; JSErrorReporter older; JSExceptionState *state; jschar *stackbuf; size_t stacklen, stackmax; JSStackFrame *fp; jsval callerid, v; JSBool ok; JSString *argsrc, *stack; uintN i, ulineno; const char *cp; char ulnbuf[11]; if (!JS_DefineProperty(cx, obj, js_message_str, STRING_TO_JSVAL(message), NULL, NULL, JSPROP_ENUMERATE)) { return JS_FALSE; } if (!JS_DefineProperty(cx, obj, js_filename_str, STRING_TO_JSVAL(filename), NULL, NULL, JSPROP_ENUMERATE)) { return JS_FALSE; } if (!JS_DefineProperty(cx, obj, js_lineno_str, INT_TO_JSVAL(lineno), NULL, NULL, JSPROP_ENUMERATE)) { return JS_FALSE; } /* * Set the 'stack' property. * * First, set aside any error reporter for cx and save its exception state * so we can suppress any checkAccess failures. Such failures should stop * the backtrace procedure, not result in a failure of this constructor. */ checkAccess = cx->runtime->checkObjectAccess; if (checkAccess) { older = JS_SetErrorReporter(cx, NULL); state = JS_SaveExceptionState(cx); } #ifdef __GNUC__ /* suppress bogus gcc warnings */ else { older = NULL; state = NULL; } #endif callerid = ATOM_KEY(cx->runtime->atomState.callerAtom); /* * Prepare to allocate a jschar buffer at stackbuf, where stacklen indexes * the next free jschar slot, and with room for at most stackmax non-null * jschars. If stackbuf is non-null, it always contains an extra slot for * the null terminator we'll store at the end, as a backstop. * * All early returns must goto done after this point, till the after-loop * cleanup code has run! */ stackbuf = NULL; stacklen = stackmax = 0; ok = JS_TRUE; #define APPEND_CHAR_TO_STACK(c) \ JS_BEGIN_MACRO \ if (stacklen == stackmax) { \ void *ptr_; \ stackmax = stackmax ? 2 * stackmax : 64; \ ptr_ = JS_realloc(cx, stackbuf, (stackmax+1) * sizeof(jschar)); \ if (!ptr_) { \ ok = JS_FALSE; \ goto done; \ } \ stackbuf = ptr_; \ } \ stackbuf[stacklen++] = (c); \ JS_END_MACRO #define APPEND_STRING_TO_STACK(str) \ JS_BEGIN_MACRO \ JSString *str_ = str; \ size_t length_ = JSSTRING_LENGTH(str_); \ if (stacklen + length_ > stackmax) { \ void *ptr_; \ stackmax = JS_BIT(JS_CeilingLog2(stacklen + length_)); \ ptr_ = JS_realloc(cx, stackbuf, (stackmax+1) * sizeof(jschar)); \ if (!ptr_) { \ ok = JS_FALSE; \ goto done; \ } \ stackbuf = ptr_; \ } \ js_strncpy(stackbuf + stacklen, JSSTRING_CHARS(str_), length_); \ stacklen += length_; \ JS_END_MACRO for (fp = cx->fp; fp; fp = fp->down) { if (checkAccess) { v = (fp->fun && fp->argv) ? fp->argv[-2] : JSVAL_NULL; if (!JSVAL_IS_PRIMITIVE(v)) { ok = checkAccess(cx, fp->fun->object, callerid, JSACC_READ, &v); if (!ok) { ok = JS_TRUE; break; } } } if (fp->fun) { if (fp->fun->atom) APPEND_STRING_TO_STACK(ATOM_TO_STRING(fp->fun->atom)); APPEND_CHAR_TO_STACK('('); for (i = 0; i < fp->argc; i++) { /* Avoid toSource bloat and fallibility for object types. */ v = fp->argv[i]; if (JSVAL_IS_PRIMITIVE(v)) { argsrc = js_ValueToSource(cx, v); } else if (JSVAL_IS_FUNCTION(cx, v)) { /* XXX Avoid function decompilation bloat for now. */ argsrc = JS_GetFunctionId(JS_ValueToFunction(cx, v)); if (!argsrc) argsrc = js_ValueToSource(cx, v); } else { /* XXX Avoid toString on objects, it takes too long and uses too much memory, for too many classes (see Mozilla bug 166743). */ char buf[100]; JS_snprintf(buf, sizeof buf, "[object %s]", OBJ_GET_CLASS(cx, JSVAL_TO_OBJECT(v))->name); argsrc = JS_NewStringCopyZ(cx, buf); } if (!argsrc) { ok = JS_FALSE; goto done; } if (i > 0) APPEND_CHAR_TO_STACK(','); APPEND_STRING_TO_STACK(argsrc); } APPEND_CHAR_TO_STACK(')'); } APPEND_CHAR_TO_STACK('@'); if (fp->script && fp->script->filename) { for (cp = fp->script->filename; *cp; cp++) APPEND_CHAR_TO_STACK(*cp); } APPEND_CHAR_TO_STACK(':'); if (fp->script && fp->pc) { ulineno = js_PCToLineNumber(fp->script, fp->pc); JS_snprintf(ulnbuf, sizeof ulnbuf, "%u", ulineno); for (cp = ulnbuf; *cp; cp++) APPEND_CHAR_TO_STACK(*cp); } else { APPEND_CHAR_TO_STACK('0'); } APPEND_CHAR_TO_STACK('\n'); } #undef APPEND_CHAR_TO_STACK #undef APPEND_STRING_TO_STACK done: if (checkAccess) { if (ok) JS_RestoreExceptionState(cx, state); else JS_DropExceptionState(cx, state); JS_SetErrorReporter(cx, older); } if (!ok) { JS_free(cx, stackbuf); return JS_FALSE; } if (!stackbuf) { stack = cx->runtime->emptyString; } else { /* NB: if stackbuf was allocated, it has room for the terminator. */ JS_ASSERT(stacklen <= stackmax); if (stacklen < stackmax) { /* * Realloc can fail when shrinking on some FreeBSD versions, so * don't use JS_realloc here; simply let the oversized allocation * be owned by the string in that rare case. */ void *shrunk = realloc(stackbuf, (stacklen+1) * sizeof(jschar)); if (shrunk) stackbuf = shrunk; } stackbuf[stacklen] = 0; stack = js_NewString(cx, stackbuf, stacklen, 0); if (!stack) { JS_free(cx, stackbuf); return JS_FALSE; } } return JS_DefineProperty(cx, obj, js_stack_str, STRING_TO_JSVAL(stack), NULL, NULL, JSPROP_ENUMERATE); }
JSBool js_ErrorToException(JSContext *cx, const char *message, JSErrorReport *reportp) { JSErrNum errorNumber; JSExnType exn; JSBool ok; JSObject *errProto, *errObject; JSString *messageStr, *filenameStr; uintN lineno; JSExnPrivate *privateData; /* * Tell our caller to report immediately if cx has no active frames, or if * this report is just a warning. */ JS_ASSERT(reportp); if (!cx->fp || JSREPORT_IS_WARNING(reportp->flags)) return JS_FALSE; /* Find the exception index associated with this error. */ errorNumber = (JSErrNum) reportp->errorNumber; exn = errorToExceptionNum[errorNumber]; JS_ASSERT(exn < JSEXN_LIMIT); #if defined( DEBUG_mccabe ) && defined ( PRINTNAMES ) /* Print the error name and the associated exception name to stderr */ fprintf(stderr, "%s\t%s\n", errortoexnname[errorNumber].name, errortoexnname[errorNumber].exception); #endif /* * Return false (no exception raised) if no exception is associated * with the given error number. */ if (exn == JSEXN_NONE) return JS_FALSE; /* * Prevent runaway recursion, just as the Exception native constructor * must do, via cx->creatingException. If an out-of-memory error occurs, * no exception object will be created, but we don't assume that OOM is * the only kind of error that subroutines of this function called below * might raise. */ if (cx->creatingException) return JS_FALSE; cx->creatingException = JS_TRUE; /* * Try to get an appropriate prototype by looking up the corresponding * exception constructor name in the scope chain of the current context's * top stack frame, or in the global object if no frame is active. * * XXXbe hack around JSCLASS_NEW_RESOLVE code in js_LookupProperty that * checks cx->fp, cx->fp->pc, and js_CodeSpec[*cx->fp->pc] in order * to compute resolve flags such as JSRESOLVE_ASSIGNING. The bug * is that this "internal" js_GetClassPrototype call may trigger a * resolve of exceptions[exn].name if the global object uses a lazy * standard class resolver (see JS_ResolveStandardClass), but the * current frame and bytecode end up affecting the resolve flags. */ { JSStackFrame *fp = cx->fp; jsbytecode *pc = NULL; if (fp) { pc = fp->pc; fp->pc = NULL; } ok = js_GetClassPrototype(cx, exceptions[exn].name, &errProto); if (pc) fp->pc = pc; if (!ok) goto out; } errObject = js_NewObject(cx, &ExceptionClass, errProto, NULL); if (!errObject) { ok = JS_FALSE; goto out; } /* * Set the generated Exception object early, so it won't be GC'd by a last * ditch attempt to collect garbage, or a GC that otherwise nests or races * under any of the following calls. If one of the following calls fails, * it will overwrite this exception object with one of its own (except in * case of OOM errors, of course). */ JS_SetPendingException(cx, OBJECT_TO_JSVAL(errObject)); messageStr = JS_NewStringCopyZ(cx, message); if (!messageStr) { ok = JS_FALSE; goto out; } if (reportp) { filenameStr = JS_NewStringCopyZ(cx, reportp->filename); if (!filenameStr) { ok = JS_FALSE; goto out; } lineno = reportp->lineno; } else { filenameStr = cx->runtime->emptyString; lineno = 0; } ok = InitExceptionObject(cx, errObject, messageStr, filenameStr, lineno); if (!ok) goto out; /* * Construct a new copy of the error report struct, and store it in the * exception object's private data. We can't use the error report struct * that was passed in, because it's stack-allocated, and also because it * may point to transient data in the JSTokenStream. */ privateData = exn_newPrivate(cx, reportp); if (!privateData) { ok = JS_FALSE; goto out; } OBJ_SET_SLOT(cx, errObject, JSSLOT_PRIVATE, PRIVATE_TO_JSVAL(privateData)); /* Flag the error report passed in to indicate an exception was raised. */ reportp->flags |= JSREPORT_EXCEPTION; out: cx->creatingException = JS_FALSE; return ok; }
url_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) { jsval slot; JSURL *url; JSString * str; char *port; const char *cstr, *tmp; if (!JSVAL_IS_INT(id)) return JS_TRUE; slot = JSVAL_TO_INT(id); url = JS_GetInstancePrivate(cx, obj, &lm_url_class, NULL); if (!url) { url = JS_GetInstancePrivate(cx, obj, &lm_location_class, NULL); if (!url) return JS_TRUE; } str = 0; cstr = 0; switch (slot) { case URL_HREF: str = url->href; break; case URL_PROTOCOL: if (url->href) cstr = ParseURL(JS_GetStringBytes(url->href), GET_PROTOCOL_PART); break; case URL_HOST: if (url->href) cstr = ParseURL(JS_GetStringBytes(url->href), GET_HOST_PART); break; case URL_HOSTNAME: if (url->href) cstr = ParseURL(JS_GetStringBytes(url->href), GET_HOST_PART); if (cstr && (port = XP_STRCHR(cstr, ':')) != 0) *port = '\0'; break; case URL_PORT: if (url->href) cstr = ParseURL(JS_GetStringBytes(url->href), GET_HOST_PART); if (cstr && (port = XP_STRCHR(cstr, ':')) != 0) port++; else port = ""; tmp = cstr; cstr = JS_strdup(cx, port); XP_FREE((void *)tmp); break; case URL_PATHNAME: if (url->href) cstr = ParseURL(JS_GetStringBytes(url->href), GET_PATH_PART); break; case URL_HASH: if (url->href) cstr = ParseURL(JS_GetStringBytes(url->href), GET_HASH_PART); break; case URL_SEARCH: if (url->href) cstr = ParseURL(JS_GetStringBytes(url->href), GET_SEARCH_PART); break; case URL_TARGET: if (!url->target) { *vp = JSVAL_NULL; return JS_TRUE; } str = url->target; break; case URL_TEXT: if (!url->text) { *vp = JSVAL_NULL; return JS_TRUE; } str = url->text; break; case URL_X: case URL_Y: return url_get_coord(cx, url, slot, vp); default: /* Don't mess with user-defined or method properties. */ return JS_TRUE; } if (!str && cstr) str = JS_NewStringCopyZ(cx, cstr); if (cstr) XP_FREE((char *)cstr); if (!str) return JS_FALSE; *vp = STRING_TO_JSVAL(str); return JS_TRUE; }
JSURL * lm_NewURL(JSContext *cx, MochaDecoder *decoder, LO_AnchorData *anchor_data, JSObject *document) { JSObject *obj; JSURL *url; JSString *str; if (!decoder->url_prototype) { obj = JS_InitClass(cx, decoder->window_object, decoder->event_receiver_prototype, &lm_url_class, Url, 0, url_props, NULL, NULL, NULL); if (!obj) return NULL; decoder->url_prototype = obj; } url = JS_malloc(cx, sizeof *url); if (!url) return NULL; XP_BZERO(url, sizeof *url); obj = JS_NewObject(cx, &lm_url_class, decoder->url_prototype, lm_GetOuterObject(decoder)); if (!obj || !JS_SetPrivate(cx, obj, url)) { JS_free(cx, url); return NULL; } if (!JS_DefineFunctions(cx, obj, url_methods)) return NULL; url->url_decoder = HOLD_BACK_COUNT(decoder); url->url_type = FORM_TYPE_NONE; url->index = URL_NOT_INDEXED; url->url_object = obj; str = JS_NewStringCopyZ(cx, (char *) anchor_data->anchor); if (!str) return NULL; url->href = str; if (!JS_AddNamedRoot(cx, &url->href, "url.href")) return NULL; if (anchor_data->target) { str = JS_NewStringCopyZ(cx, (char *) anchor_data->target); if (!str) return NULL; url->target = str; } if (!JS_AddNamedRoot(cx, &url->target, "url.target")) return NULL; if (anchor_data->element && anchor_data->element->type == LO_TEXT) { str = lm_LocalEncodingToStr(decoder->window_context, (char *) anchor_data->element->lo_text.text); if (!str) return NULL; url->text = str; } if (!JS_AddNamedRoot(cx, &url->text, "url.text")) return NULL; return url; }
BOOL DLLCALL js_CreateXtrnProgProperties(JSContext* cx, JSObject* obj, xtrn_t* xtrn) { JSString* js_str; if((js_str=JS_NewStringCopyZ(cx, xtrn->code))==NULL) return(FALSE); if(!JS_DefineProperty(cx, obj, "code", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if((js_str=JS_NewStringCopyZ(cx, xtrn->name))==NULL) return(FALSE); if(!JS_DefineProperty(cx, obj, "name", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if((js_str=JS_NewStringCopyZ(cx, xtrn->cmd))==NULL) return(FALSE); if(!JS_DefineProperty(cx, obj, "cmd", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if((js_str=JS_NewStringCopyZ(cx, xtrn->clean))==NULL) return(FALSE); if(!JS_DefineProperty(cx, obj, "clean_cmd", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if((js_str=JS_NewStringCopyZ(cx, xtrn->path))==NULL) return(FALSE); if(!JS_DefineProperty(cx, obj, "startup_dir", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if((js_str=JS_NewStringCopyZ(cx, xtrn->arstr))==NULL) return(FALSE); if(!JS_DefineProperty(cx, obj, "ars", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if((js_str=JS_NewStringCopyZ(cx, xtrn->run_arstr))==NULL) return(FALSE); if(!JS_DefineProperty(cx, obj, "execution_ars", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if(!JS_DefineProperty(cx, obj, "settings", INT_TO_JSVAL(xtrn->misc) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if(!JS_DefineProperty(cx, obj, "type", INT_TO_JSVAL(xtrn->type) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if(!JS_DefineProperty(cx, obj, "event", INT_TO_JSVAL(xtrn->event) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if(!JS_DefineProperty(cx, obj, "textra", INT_TO_JSVAL(xtrn->textra) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if(!JS_DefineProperty(cx, obj, "max_time", INT_TO_JSVAL(xtrn->maxtime) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); if(!JS_DefineProperty(cx, obj, "cost", INT_TO_JSVAL(xtrn->cost) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(FALSE); #ifdef BUILD_JSDOCS js_CreateArrayOfStrings(cx, obj, "_property_desc_list", xtrn_prog_prop_desc, JSPROP_READONLY); #endif return(TRUE); }
/** Needs nargs to be at least 2 for GC roots. * * JS method returns true if values were read. */ static JSBool query_readQuery(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { extern cfgHnd cfg; query_private_t *hnd = JS_GetPrivate(cx, obj); node *n; JSString *str; int retval; jsrefcount depth; jsval val; if (hnd->query) return gpsee_throw(cx, OBJECT_ID ".readQuery.alreadyRead"); else hnd->query = JS_malloc(cx, sizeof(*hnd->query)); if (argc > 0) { str = JS_ValueToString(cx, argv[0]); hnd->uploadDir = JS_strdup(cx, JS_GetStringBytes(str)); } else hnd->uploadDir = cfg_value(cfg, OBJECT_ID ".default_upload_dir"); /* fix this later by making upload files == /dev/null in libcgihtml.so when upload dir is null */ if (!hnd->uploadDir) gpsee_log(cx, GLOG_NOTICE, "Unspecified upload dir is a security problem! Specify rc." OBJECT_ID ".default_upload_dir!"); depth = JS_SuspendRequest(cx); retval = read_cgi_input(cx, hnd->query, hnd->uploadDir); JS_ResumeRequest(cx, depth); *rval = retval ? JSVAL_TRUE : JSVAL_FALSE; for (n = hnd->query->head; n; n = n->next) { /* temporary fix? we don't want to overwrite our module readQuery() member */ if (!n->entry.name || !strcmp(n->entry.name,"readQuery")) continue; if (n->entry.value == NULL) n->entry.value = strdup(""); /* Match eekim's horrible semantics */ /* later optimization note: almost all of the cases where we'd need to * create arrays instead of strings are also cases where the CGI * variables of the same name are adjacent in the query */ if ((JS_GetProperty(cx, obj, n->entry.name, &val) == JS_TRUE) && (!JSVAL_IS_VOID(val))) { /* Already seen a CGI variable with this name */ if (JSVAL_IS_STRING(val)) /* Only seen one, create a new array */ { argv[0] = val; argv[1] = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, n->entry.value)); argv[0] = OBJECT_TO_JSVAL(JS_NewArrayObject(cx, 2, argv)); if (JS_SetProperty(cx, obj, n->entry.name, argv + 0) == JS_FALSE) return gpsee_throw(cx, OBJECT_ID ".readQuery.property.recreate.%s", n->entry.name); } else { jsuint length; /* seen many: append to the array */ if (JS_IsArrayObject(cx, JSVAL_TO_OBJECT(val)) != JS_TRUE) return gpsee_throw(cx, OBJECT_ID ".readQuery.property.type.%s", n->entry.name); if (JS_GetArrayLength(cx, JSVAL_TO_OBJECT(val), &length) != JS_TRUE) return gpsee_throw(cx, OBJECT_ID ".readQuery.property.%s.length.get", n->entry.name); if (JS_DefineElement(cx, JSVAL_TO_OBJECT(val), length, STRING_TO_JSVAL(JS_NewStringCopyZ(cx, n->entry.value)), JS_PropertyStub, JS_PropertyStub, JSPROP_ENUMERATE) != JS_TRUE) return gpsee_throw(cx, OBJECT_ID ".readQuery.property.%s.element.%u", n->entry.name, length); if (JS_SetArrayLength(cx, JSVAL_TO_OBJECT(val), length + 1) != JS_TRUE) return gpsee_throw(cx, OBJECT_ID ".readQuery.property.%s.length.set", n->entry.name); } } else { /* First time for this property, insert it as a string */ argv[0] = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, n->entry.value)); if (JS_SetProperty(cx, obj, n->entry.name, argv + 0) == JS_FALSE) return gpsee_throw(cx, OBJECT_ID ".readQuery.property.create.%s", n->entry.name); } } return JS_TRUE; }
JSBool js_ErrorToException(JSContext *cx, const char *message, JSErrorReport *reportp, JSErrorCallback callback, void *userRef) { JSErrNum errorNumber; const JSErrorFormatString *errorString; JSExnType exn; jsval tv[4]; JSTempValueRooter tvr; JSBool ok; JSObject *errProto, *errObject; JSString *messageStr, *filenameStr; /* * Tell our caller to report immediately if this report is just a warning. */ JS_ASSERT(reportp); if (JSREPORT_IS_WARNING(reportp->flags)) return JS_FALSE; /* Find the exception index associated with this error. */ errorNumber = (JSErrNum) reportp->errorNumber; if (!callback || callback == js_GetErrorMessage) errorString = js_GetLocalizedErrorMessage(cx, NULL, NULL, errorNumber); else errorString = callback(userRef, NULL, errorNumber); exn = errorString ? (JSExnType) errorString->exnType : JSEXN_NONE; JS_ASSERT(exn < JSEXN_LIMIT); #if defined( DEBUG_mccabe ) && defined ( PRINTNAMES ) /* Print the error name and the associated exception name to stderr */ fprintf(stderr, "%s\t%s\n", errortoexnname[errorNumber].name, errortoexnname[errorNumber].exception); #endif /* * Return false (no exception raised) if no exception is associated * with the given error number. */ if (exn == JSEXN_NONE) return JS_FALSE; /* * Prevent runaway recursion, via cx->generatingError. If an out-of-memory * error occurs, no exception object will be created, but we don't assume * that OOM is the only kind of error that subroutines of this function * called below might raise. */ if (cx->generatingError) return JS_FALSE; MUST_FLOW_THROUGH("out"); cx->generatingError = JS_TRUE; /* Protect the newly-created strings below from nesting GCs. */ memset(tv, 0, sizeof tv); JS_PUSH_TEMP_ROOT(cx, JS_ARRAY_LENGTH(tv), tv, &tvr); /* * Try to get an appropriate prototype by looking up the corresponding * exception constructor name in the scope chain of the current context's * top stack frame, or in the global object if no frame is active. */ ok = js_GetClassPrototype(cx, NULL, INT_TO_JSID(GetExceptionProtoKey(exn)), &errProto); if (!ok) goto out; tv[0] = OBJECT_TO_JSVAL(errProto); errObject = js_NewObject(cx, &js_ErrorClass, errProto, NULL); if (!errObject) { ok = JS_FALSE; goto out; } tv[1] = OBJECT_TO_JSVAL(errObject); messageStr = JS_NewStringCopyZ(cx, message); if (!messageStr) { ok = JS_FALSE; goto out; } tv[2] = STRING_TO_JSVAL(messageStr); filenameStr = JS_NewStringCopyZ(cx, reportp->filename); if (!filenameStr) { ok = JS_FALSE; goto out; } tv[3] = STRING_TO_JSVAL(filenameStr); ok = InitExnPrivate(cx, errObject, messageStr, filenameStr, reportp->lineno, reportp); if (!ok) goto out; JS_SetPendingException(cx, OBJECT_TO_JSVAL(errObject)); /* Flag the error report passed in to indicate an exception was raised. */ reportp->flags |= JSREPORT_EXCEPTION; out: JS_POP_TEMP_ROOT(cx, &tvr); cx->generatingError = JS_FALSE; return ok; }
/* XXXbe Consolidate the ugly truth that we don't treat filename as UTF-8 with these two functions. */ static JSString * FilenameToString(JSContext *cx, const char *filename) { return JS_NewStringCopyZ(cx, filename); }
int main(int argc, const char *argv[]) { /* JS variables. */ JSRuntime* rt; JSContext* cx; JSObject* global; /* Create a JS runtime. */ rt = JS_NewRuntime(8L * 1024L * 1024L); if (rt == NULL) return 1; /* Create a context. */ cx = JS_NewContext(rt, 8192); if (cx == NULL) return 1; JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_METHODJIT); JS_SetVersion(cx, JSVERSION_LATEST); JS_SetErrorReporter(cx, reportError); /* Create the global object in a new compartment. */ global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL); if (global == NULL) return 1; /* Populate the global object with the standard globals, like Object and Array. */ if (!JS_InitStandardClasses(cx, global)) return 1; JSObject* alpha = JS_DefineObject(cx, global, "alpha", NULL, NULL, 0); /* Attach the global functions */ if (!JS_DefineFunctions(cx, alpha, global_functions)) return 1; /* expose the binding functions for require to use */ JSObject* bindings = JS_DefineObject(cx, alpha, "bindings", NULL, NULL, 0); if (!JS_DefineFunctions(cx, bindings, binding_functions)) return 1; /* Set global on alpha */ jsval global_val = OBJECT_TO_JSVAL(global); if (!JS_SetProperty(cx, alpha, "global", &global_val)) return 1; /* Set args on alpha */ JSObject* args = JS_NewArrayObject(cx, 0, NULL); jsval args_val = OBJECT_TO_JSVAL(args); if (!JS_SetProperty(cx, alpha, "args", &args_val)) return 1; int index; for (index = 0; index < argc; index++) { jsval arg = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, argv[index])); if (!JS_SetElement(cx, args, index, &arg)) return 1; } /* Bootstrap using the code in main.js */ JS_EvaluateScript(cx, global, embedded_src_main_js, strlen(embedded_src_main_js), "main.js", 1, NULL); /* Cleanup. */ JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); return 0; }
JSBool JsGlobal::event_GetProperty (JSContext *cx, JSObject *obj, jsid id, jsval *vp) { fsm::StateMachine * pstateMachine = NULL; static log4cplus::Logger log = log4cplus::Logger::getInstance("TUserManager.GetProperty"); pstateMachine = (fsm::StateMachine *)JS_GetContextPrivate(cx); if (!pstateMachine){ LOG4CPLUS_WARN(log,"GetContextPrivate is null."); } if (!JSID_IS_INT(id)) return JS_TRUE; int proid = JSID_TO_INT(id); jsval *val = (jsval *) JS_GetPrivate(cx, obj); if (val) { if(JSVAL_IS_NULL(*vp) || JSVAL_IS_VOID(*vp)) *vp = val[proid]; return JS_TRUE; } val = new jsval[4]; if (!val) { JS_ReportOutOfMemory(cx); JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } if (!JS_AddValueRoot(cx, val)) { delete[] val; JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } if (!JS_SetPrivate(cx, obj, (void*)val)) { JS_RemoveValueRoot(cx, val); delete[] val; JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } std::string prefix = "getting [_event] property:"; fsm::env::Js::IdToString idString(cx, id); if(pstateMachine ){ val[name] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->m_currentEvt.getEventName().c_str())); //val[bodydata] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->m_currentEvt.getData().c_str())); //val[messagetype] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->m_currentEvt.getMsgType().c_str())); //val[ip] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->m_currentEvt.getIP().c_str())); //val[port] = INT_TO_JSVAL(pstateMachine->m_currentEvt.getPort()); val[serviceid] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->getName().c_str())); val[sessionid] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->getSessionId().c_str())); val[callid] = STRING_TO_JSVAL(JS_NewStringCopyZ (cx,pstateMachine->getSessionId().c_str())); switch (proid) { case name: prefix.append("_name"); break; case serviceid: prefix.append("_serviceid"); break; case sessionid: prefix.append("_sessionid"); break; case callid: prefix.append("_callid"); break; //case from:{ // vp.setInt32(pstateMachine->getFrom().c_str()); // break; //case Enable: // vp.setBoolean(extPtr->m_bEnable); // break; default: prefix.append(idString.getBytes()); break; } }else{ prefix.append(idString.getBytes()); } fsm::env::Js::ToString valueString(cx, val[proid]); //fsm::env::Js::ToString objString(cx,OBJECT_TO_JSVAL(obj)); *vp = val[proid]; LOG4CPLUS_DEBUG(log,prefix<< ",value:" << valueString.getBytes()); return JS_TRUE; }
NPT_Result GPAC_GenericController::OnActionResponse(NPT_Result res, PLT_ActionReference& action, void* userdata) { #ifdef GPAC_HAS_SPIDERMONKEY u32 i, count; GPAC_DeviceItem *item = NULL; GPAC_ServiceItem *serv = NULL; GPAC_ActionArgListener *argl, *act_l; PLT_Service* service = action->GetActionDesc().GetService(); NPT_String uuid; GPAC_ActionUDTA *act_udta = (GPAC_ActionUDTA *)userdata; /*this is NOT an actionResponse to an action triggered on a generic device*/ if (act_udta && act_udta->m_Reserved) act_udta = NULL; GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Receive %s Response - error code %d\n", (char *) action->GetActionDesc().GetName(), res)); gf_mx_p(m_ControlPointLock); /*get our device*/ uuid = service->GetDevice()->GetUUID(); count = gf_list_count(m_Devices); for (i=0; i<count; i++) { item = (GPAC_DeviceItem *) gf_list_get(m_Devices, i); if (item->m_UUID == uuid ) { break; } item = NULL; } gf_mx_v(m_ControlPointLock); if (!item) { GF_LOG(GF_LOG_ERROR, GF_LOG_NETWORK, ("[UPnP] Receive %s Response on unknown device (uuid %s)\n", (char *) action->GetActionDesc().GetName(), (char *) uuid)); goto exit; } /*get our service*/ count = gf_list_count(item->m_Services); for (i=0; i<count; i++) { serv = (GPAC_ServiceItem *)gf_list_get(item->m_Services, i); if (serv->m_service == service) break; } if (!serv) { GF_LOG(GF_LOG_ERROR, GF_LOG_NETWORK, ("[UPnP] Receive %s Response on unknown service %s\n", (char *) action->GetActionDesc().GetName(), (char *) service->GetServiceType())); goto exit; } /*locate our listeners*/ act_l = NULL; i=0; while ((argl = (GPAC_ActionArgListener *)gf_list_enum(serv->m_ArgListeners, &i))) { NPT_String value; GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] checking argument %s\n", (char *) argl->action->GetName() )); if (argl->action->GetName() != action->GetActionDesc().GetName() ) continue; /*global action listener*/ if (argl->arg==NULL) { act_l = argl; continue; } /*if error don't trigger listeners*/ if (res != NPT_SUCCESS) { GF_LOG(GF_LOG_WARNING, GF_LOG_NETWORK, ("[UPnP] Receive %s Response: error on remote device %d\n", (char *) action->GetActionDesc().GetName(), res)); continue; } /*action arg listener*/ if (action->GetArgumentValue(argl->arg->GetName(), value) == NPT_SUCCESS) { jsval argv[1], rval; GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Calling handler for response %s argument %s\n", (char *) action->GetActionDesc().GetName(), (char *) argl->arg->GetName() )); m_pUPnP->LockJavascript(1); argv[0] = STRING_TO_JSVAL( JS_NewStringCopyZ(serv->js_ctx, value) ); JS_CallFunctionValue(serv->js_ctx, serv->obj, argl->on_event, 1, argv, &rval); m_pUPnP->LockJavascript(0); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_NETWORK, ("[UPnP] %s Response: couldn't get argument %s value\n", (char *) action->GetActionDesc().GetName(), (char *) argl->arg->GetName() )); } } if (act_l) { jsval rval; m_pUPnP->LockJavascript(1); if (act_l->is_script) { JSObject *act_obj; jsval argv[2]; GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Calling handler for response %s\n", (char *) action->GetActionDesc().GetName())); act_obj = JS_NewObject(serv->js_ctx, &item->m_pUPnP->upnpDeviceClass, 0, item->obj); JS_SetPrivate(serv->js_ctx, act_obj, (void *)action.AsPointer() ); JS_DefineFunction(serv->js_ctx, act_obj, "GetArgumentValue", upnp_action_get_argument_value, 1, 0); JS_DefineFunction(serv->js_ctx, act_obj, "GetErrorCode", upnp_action_get_error_code, 1, 0); JS_DefineFunction(serv->js_ctx, act_obj, "GetError", upnp_action_get_error, 1, 0); gf_js_add_root(serv->js_ctx, &act_obj, GF_JSGC_OBJECT); argv[0] = OBJECT_TO_JSVAL(act_obj); if (act_udta) { argv[1] = act_udta->udta; JS_CallFunctionValue(serv->js_ctx, serv->obj, act_l->on_event, 2, argv, &rval); } else { JS_CallFunctionValue(serv->js_ctx, serv->obj, act_l->on_event, 1, argv, &rval); } gf_js_remove_root(serv->js_ctx, &act_obj, GF_JSGC_OBJECT); } /*if error don't trigger listeners*/ else if (res == NPT_SUCCESS) { GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Calling handler for response %s\n", (char *) action->GetActionDesc().GetName())); JS_CallFunctionValue(serv->js_ctx, serv->obj, act_l->on_event, 0, 0, &rval); } else { GF_LOG(GF_LOG_ERROR, GF_LOG_NETWORK, ("[UPnP] response %s has error %d\n", (char *) action->GetActionDesc().GetName(), res )); } m_pUPnP->LockJavascript(0); } GF_LOG(GF_LOG_INFO, GF_LOG_NETWORK, ("[UPnP] Done processing response %s\n", (char *) action->GetActionDesc().GetName())); exit: if (act_udta) { gf_js_remove_root(serv->js_ctx, &act_udta->udta, GF_JSGC_VAL); delete act_udta; } return NPT_SUCCESS; #else return NPT_SUCCESS; #endif }
/** * Define OS-specific constants. * * This function creates or uses JS object |OS.Constants| to store * all its constants. */ bool DefineOSFileConstants(JSContext *cx, JSObject *global) { MOZ_ASSERT(gInitialized); if (gPaths == NULL) { // If an initialization error was ignored, we may end up with // |gInitialized == true| but |gPaths == NULL|. We cannot // |MOZ_ASSERT| this, as this would kill precompile_cache.js, // so we simply return an error. JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_CANT_OPEN, "OSFileConstants", "initialization has failed"); return false; } JSObject *objOS; if (!(objOS = GetOrCreateObjectProperty(cx, global, "OS"))) { return false; } JSObject *objConstants; if (!(objConstants = GetOrCreateObjectProperty(cx, objOS, "Constants"))) { return false; } // Build OS.Constants.libc JSObject *objLibc; if (!(objLibc = GetOrCreateObjectProperty(cx, objConstants, "libc"))) { return false; } if (!dom::DefineConstants(cx, objLibc, gLibcProperties)) { return false; } #if defined(XP_WIN) // Build OS.Constants.Win JSObject *objWin; if (!(objWin = GetOrCreateObjectProperty(cx, objConstants, "Win"))) { return false; } if (!dom::DefineConstants(cx, objWin, gWinProperties)) { return false; } #endif // defined(XP_WIN) // Build OS.Constants.Sys JSObject *objSys; if (!(objSys = GetOrCreateObjectProperty(cx, objConstants, "Sys"))) { return false; } nsCOMPtr<nsIXULRuntime> runtime = do_GetService(XULRUNTIME_SERVICE_CONTRACTID); if (runtime) { nsAutoCString os; DebugOnly<nsresult> rv = runtime->GetOS(os); MOZ_ASSERT(NS_SUCCEEDED(rv)); JSString* strVersion = JS_NewStringCopyZ(cx, os.get()); if (!strVersion) { return false; } jsval valVersion = STRING_TO_JSVAL(strVersion); if (!JS_SetProperty(cx, objSys, "Name", &valVersion)) { return false; } } // Build OS.Constants.Path JSObject *objPath; if (!(objPath = GetOrCreateObjectProperty(cx, objConstants, "Path"))) { return false; } // Locate libxul { nsAutoString xulPath(gPaths->libDir); xulPath.Append(PR_GetDirectorySeparator()); #if defined(XP_MACOSX) // Under MacOS X, for some reason, libxul is called simply "XUL" xulPath.Append(NS_LITERAL_STRING("XUL")); #else // On other platforms, libxul is a library "xul" with regular // library prefix/suffix xulPath.Append(NS_LITERAL_STRING(DLL_PREFIX)); xulPath.Append(NS_LITERAL_STRING("xul")); xulPath.Append(NS_LITERAL_STRING(DLL_SUFFIX)); #endif // defined(XP_MACOSX) if (!SetStringProperty(cx, objPath, "libxul", xulPath)) { return false; } } if (!SetStringProperty(cx, objPath, "libDir", gPaths->libDir)) { return false; } if (!SetStringProperty(cx, objPath, "tmpDir", gPaths->tmpDir)) { return false; } if (!SetStringProperty(cx, objPath, "profileDir", gPaths->profileDir)) { return false; } return true; }
JSObject * js_InitExceptionClasses(JSContext *cx, JSObject *obj) { JSObject *obj_proto, *protos[JSEXN_LIMIT]; int i; /* * If lazy class initialization occurs for any Error subclass, then all * classes are initialized, starting with Error. To avoid reentry and * redundant initialization, we must not pass a null proto parameter to * js_NewObject below, when called for the Error superclass. We need to * ensure that Object.prototype is the proto of Error.prototype. * * See the equivalent code to ensure that parent_proto is non-null when * JS_InitClass calls js_NewObject, in jsapi.c. */ if (!js_GetClassPrototype(cx, obj, INT_TO_JSID(JSProto_Object), &obj_proto)) { return NULL; } if (!js_EnterLocalRootScope(cx)) return NULL; /* Initialize the prototypes first. */ for (i = 0; exceptions[i].name != 0; i++) { JSAtom *atom; JSFunction *fun; JSString *nameString; int protoIndex = exceptions[i].protoIndex; /* Make the prototype for the current constructor name. */ protos[i] = js_NewObject(cx, &js_ErrorClass, (protoIndex != JSEXN_NONE) ? protos[protoIndex] : obj_proto, obj, 0); if (!protos[i]) break; /* So exn_finalize knows whether to destroy private data. */ STOBJ_SET_SLOT(protos[i], JSSLOT_PRIVATE, JSVAL_VOID); /* Make a constructor function for the current name. */ atom = cx->runtime->atomState.classAtoms[exceptions[i].key]; fun = js_DefineFunction(cx, obj, atom, exceptions[i].native, 3, 0); if (!fun) break; /* Make this constructor make objects of class Exception. */ FUN_CLASP(fun) = &js_ErrorClass; /* Make the prototype and constructor links. */ if (!js_SetClassPrototype(cx, FUN_OBJECT(fun), protos[i], JSPROP_READONLY | JSPROP_PERMANENT)) { break; } /* proto bootstrap bit from JS_InitClass omitted. */ nameString = JS_NewStringCopyZ(cx, exceptions[i].name); if (!nameString) break; /* Add the name property to the prototype. */ if (!JS_DefineProperty(cx, protos[i], js_name_str, STRING_TO_JSVAL(nameString), NULL, NULL, JSPROP_ENUMERATE)) { break; } /* Finally, stash the constructor for later uses. */ if (!js_SetClassObject(cx, obj, exceptions[i].key, FUN_OBJECT(fun))) break; } js_LeaveLocalRootScope(cx); if (exceptions[i].name) return NULL; /* * Add an empty message property. (To Exception.prototype only, * because this property will be the same for all the exception * protos.) */ if (!JS_DefineProperty(cx, protos[0], js_message_str, STRING_TO_JSVAL(cx->runtime->emptyString), NULL, NULL, JSPROP_ENUMERATE)) { return NULL; } if (!JS_DefineProperty(cx, protos[0], js_fileName_str, STRING_TO_JSVAL(cx->runtime->emptyString), NULL, NULL, JSPROP_ENUMERATE)) { return NULL; } if (!JS_DefineProperty(cx, protos[0], js_lineNumber_str, INT_TO_JSVAL(0), NULL, NULL, JSPROP_ENUMERATE)) { return NULL; } /* * Add methods only to Exception.prototype, because ostensibly all * exception types delegate to that. */ if (!JS_DefineFunctions(cx, protos[0], exception_methods)) return NULL; return protos[0]; }
JSString * DeadObjectProxy::obj_toString(JSContext *cx, JSObject *wrapper) { return JS_NewStringCopyZ(cx, "[object DeadObject]"); }
PRBool CreateFakeBrowserWindow(JSContext* cx, JSObject* parent, nsIPrincipal* systemPrincipal) { nsresult rv; jsval value; nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID()); if (xpc == nsnull) { JS_ReportError(cx, "Adblock Plus: Coult not retrieve nsIXPConnect - wrong Gecko version?"); return PR_FALSE; } rv = xpc->FlagSystemFilenamePrefix("adblockplus.dll/"); if (NS_FAILED(rv)) { JS_ReportError(cx, "Adblock Plus: Failed to enable protection for inline JavaScript"); return PR_FALSE; } JSObject* obj = JS_NewObject(cx, nsnull, nsnull, parent); if (obj == nsnull) { JS_ReportError(cx, "Adblock Plus: Failed to create fake browser window object - out of memory?"); return PR_FALSE; } JS_SetGlobalObject(cx, obj); // Have to loop through the methods manually because JS_DefineFunctions won't do anything for some reason for (JSFunctionSpec *fs = window_methods; fs->name; fs++) { JSFunction *fun = JS_DefineFunction(cx, obj, fs->name, fs->call, fs->nargs, fs->flags); if (!fun) { JS_ReportError(cx, "Adblock Plus: Failed to attach native methods to fake browser window"); return PR_FALSE; } } if (!JS_DefineProperties(cx, obj, window_properties)) { JS_ReportError(cx, "Adblock Plus: Failed to attach native properties to fake browser window"); return PR_FALSE; } JSPrincipals* principals; rv = systemPrincipal->GetJSPrincipals(cx, &principals); if (NS_FAILED(rv)) { JS_ReportError(cx, "Adblock Plus: Could not convert system principal into JavaScript principals"); return PR_FALSE; } for (int i = 0; includes[i]; i += 2) { JSScript* inlineScript = JS_CompileScriptForPrincipals(cx, obj, principals, includes[i+1], strlen(includes[i+1]), includes[i], 1); if (inlineScript == nsnull) { JS_ReportError(cx, "Adblock Plus: Failed to compile %s", includes[i]); return PR_FALSE; } if (!JS_ExecuteScript(cx, obj, inlineScript, &value)) { JS_ReportError(cx, "Adblock Plus: Failed to execute %s", includes[i]); return PR_FALSE; } JS_DestroyScript(cx, inlineScript); } JSPRINCIPALS_DROP(cx, principals); nsCOMPtr<nsISupports> wrapped; rv = xpc->WrapJS(cx, obj, NS_GET_IID(nsISupports), getter_AddRefs(wrapped)); if (NS_FAILED(rv)) { JS_ReportError(cx, "Adblock Plus: Failed to create XPConnect wrapper for fake browser window"); return PR_FALSE; } fakeBrowserWindow = do_QueryInterface(wrapped); if (fakeBrowserWindow == nsnull) { JS_ReportError(cx, "Adblock Plus: Failed to QI fake browser window"); return PR_FALSE; } jsval readerVal; JS_GetProperty(cx, obj, "_dtdReader", &readerVal); if (readerVal == JSVAL_VOID) { JS_ReportError(cx, "Adblock Plus: Failed to retrieve DTD reader object"); return PR_FALSE; } JSObject* reader = JSVAL_TO_OBJECT(readerVal); for (int i = 0; i < NUM_LABELS; i++) { JSString* str = JS_NewStringCopyZ(cx, context_labels[i]); if (str == nsnull) { JS_ReportError(cx, "Adblock Plus: Could not create JavaScript string for '%s' - out of memory?", context_labels[i]); return PR_FALSE; } jsval args[] = {STRING_TO_JSVAL(str)}; jsval retval; if (!JS_CallFunctionName(cx, reader, "getEntity", 1, args, &retval)) { JS_ReportError(cx, "Adblock Plus: Failed to retrieve entity '%s' from overlay.dtd", context_labels[i]); return PR_FALSE; } str = JS_ValueToString(cx, retval); if (str == nsnull) { JS_ReportError(cx, "Adblock Plus: Could not convert return value of _dtdReader.getEntity() to string"); return PR_FALSE; } strcpy_s(labelValues[i], sizeof(labelValues[i]), JS_GetStringBytes(str)); } return PR_TRUE; }
NS_IMETHODIMP TelemetryImpl::GetChromeHangs(JSContext *cx, jsval *ret) { MutexAutoLock hangReportMutex(mHangReportsMutex); JSObject *reportArray = JS_NewArrayObject(cx, 0, nsnull); if (!reportArray) { return NS_ERROR_FAILURE; } *ret = OBJECT_TO_JSVAL(reportArray); // Each hang report is an object in the 'chromeHangs' array for (size_t i = 0; i < mHangReports.Length(); ++i) { JSObject *reportObj = JS_NewObject(cx, NULL, NULL, NULL); if (!reportObj) { return NS_ERROR_FAILURE; } jsval reportObjVal = OBJECT_TO_JSVAL(reportObj); if (!JS_SetElement(cx, reportArray, i, &reportObjVal)) { return NS_ERROR_FAILURE; } // Record the hang duration (expressed in seconds) JSBool ok = JS_DefineProperty(cx, reportObj, "duration", INT_TO_JSVAL(mHangReports[i].duration), NULL, NULL, JSPROP_ENUMERATE); if (!ok) { return NS_ERROR_FAILURE; } // Represent call stack PCs as strings // (JS can't represent all 64-bit integer values) JSObject *pcArray = JS_NewArrayObject(cx, 0, nsnull); if (!pcArray) { return NS_ERROR_FAILURE; } ok = JS_DefineProperty(cx, reportObj, "stack", OBJECT_TO_JSVAL(pcArray), NULL, NULL, JSPROP_ENUMERATE); if (!ok) { return NS_ERROR_FAILURE; } const uint32_t pcCount = mHangReports[i].callStack.Length(); for (size_t pcIndex = 0; pcIndex < pcCount; ++pcIndex) { nsCAutoString pcString; pcString.AppendPrintf("0x%p", mHangReports[i].callStack[pcIndex]); JSString *str = JS_NewStringCopyZ(cx, pcString.get()); if (!str) { return NS_ERROR_FAILURE; } jsval v = STRING_TO_JSVAL(str); if (!JS_SetElement(cx, pcArray, pcIndex, &v)) { return NS_ERROR_FAILURE; } } // Record memory map info JSObject *moduleArray = JS_NewArrayObject(cx, 0, nsnull); if (!moduleArray) { return NS_ERROR_FAILURE; } ok = JS_DefineProperty(cx, reportObj, "memoryMap", OBJECT_TO_JSVAL(moduleArray), NULL, NULL, JSPROP_ENUMERATE); if (!ok) { return NS_ERROR_FAILURE; } #if defined(MOZ_ENABLE_PROFILER_SPS) const uint32_t moduleCount = mHangReports[i].moduleMap.GetSize(); for (size_t moduleIndex = 0; moduleIndex < moduleCount; ++moduleIndex) { // Current module const SharedLibrary &module = mHangReports[i].moduleMap.GetEntry(moduleIndex); JSObject *moduleInfoArray = JS_NewArrayObject(cx, 0, nsnull); if (!moduleInfoArray) { return NS_ERROR_FAILURE; } jsval val = OBJECT_TO_JSVAL(moduleInfoArray); if (!JS_SetElement(cx, moduleArray, moduleIndex, &val)) { return NS_ERROR_FAILURE; } // Start address nsCAutoString addressString; addressString.AppendPrintf("0x%p", module.GetStart()); JSString *str = JS_NewStringCopyZ(cx, addressString.get()); if (!str) { return NS_ERROR_FAILURE; } val = STRING_TO_JSVAL(str); if (!JS_SetElement(cx, moduleInfoArray, 0, &val)) { return NS_ERROR_FAILURE; } // Module name str = JS_NewStringCopyZ(cx, module.GetName()); if (!str) { return NS_ERROR_FAILURE; } val = STRING_TO_JSVAL(str); if (!JS_SetElement(cx, moduleInfoArray, 1, &val)) { return NS_ERROR_FAILURE; } // Module size in memory val = INT_TO_JSVAL(int32_t(module.GetEnd() - module.GetStart())); if (!JS_SetElement(cx, moduleInfoArray, 2, &val)) { return NS_ERROR_FAILURE; } // "PDB Age" identifier val = INT_TO_JSVAL(0); #if defined(MOZ_PROFILING) && defined(XP_WIN) val = INT_TO_JSVAL(module.GetPdbAge()); #endif if (!JS_SetElement(cx, moduleInfoArray, 3, &val)) { return NS_ERROR_FAILURE; } // "PDB Signature" GUID char guidString[NSID_LENGTH] = { 0 }; #if defined(MOZ_PROFILING) && defined(XP_WIN) module.GetPdbSignature().ToProvidedString(guidString); #endif str = JS_NewStringCopyZ(cx, guidString); if (!str) { return NS_ERROR_FAILURE; } val = STRING_TO_JSVAL(str); if (!JS_SetElement(cx, moduleInfoArray, 4, &val)) { return NS_ERROR_FAILURE; } // Name of associated PDB file const char *pdbName = ""; #if defined(MOZ_PROFILING) && defined(XP_WIN) pdbName = module.GetPdbName(); #endif str = JS_NewStringCopyZ(cx, pdbName); if (!str) { return NS_ERROR_FAILURE; } val = STRING_TO_JSVAL(str); if (!JS_SetElement(cx, moduleInfoArray, 5, &val)) { return NS_ERROR_FAILURE; } } #endif } return NS_OK; }
void WrapperPromiseCallback::Call(JS::Handle<JS::Value> aValue) { ThreadsafeAutoSafeJSContext cx; JSAutoCompartment ac(cx, mGlobal); JS::Rooted<JS::Value> value(cx, aValue); if (!JS_WrapValue(cx, &value)) { NS_WARNING("Failed to wrap value into the right compartment."); return; } ErrorResult rv; // If invoking callback threw an exception, run resolver's reject with the // thrown exception as argument and the synchronous flag set. JS::Rooted<JS::Value> retValue(cx, mCallback->Call(value, rv, CallbackObject::eRethrowExceptions)); rv.WouldReportJSException(); if (rv.Failed() && rv.IsJSException()) { JS::Rooted<JS::Value> value(cx); rv.StealJSException(cx, &value); if (!JS_WrapValue(cx, &value)) { NS_WARNING("Failed to wrap value into the right compartment."); return; } mNextPromise->RejectInternal(cx, value, Promise::SyncTask); return; } // If the return value is the same as the promise itself, throw TypeError. if (retValue.isObject()) { JS::Rooted<JSObject*> valueObj(cx, &retValue.toObject()); Promise* returnedPromise; nsresult r = UNWRAP_OBJECT(Promise, valueObj, returnedPromise); if (NS_SUCCEEDED(r) && returnedPromise == mNextPromise) { const char* fileName = nullptr; uint32_t lineNumber = 0; // Try to get some information about the callback to report a sane error, // but don't try too hard (only deals with scripted functions). JS::Rooted<JSObject*> unwrapped(cx, js::CheckedUnwrap(mCallback->Callback())); if (unwrapped) { JSAutoCompartment ac(cx, unwrapped); if (JS_ObjectIsFunction(cx, unwrapped)) { JS::Rooted<JS::Value> asValue(cx, JS::ObjectValue(*unwrapped)); JS::Rooted<JSFunction*> func(cx, JS_ValueToFunction(cx, asValue)); MOZ_ASSERT(func); JSScript* script = JS_GetFunctionScript(cx, func); if (script) { fileName = JS_GetScriptFilename(script); lineNumber = JS_GetScriptBaseLineNumber(cx, script); } } } // We're back in aValue's compartment here. JS::Rooted<JSString*> stack(cx, JS_GetEmptyString(JS_GetRuntime(cx))); JS::Rooted<JSString*> fn(cx, JS_NewStringCopyZ(cx, fileName)); if (!fn) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } JS::Rooted<JSString*> message(cx, JS_NewStringCopyZ(cx, "then() cannot return same Promise that it resolves.")); if (!message) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } JS::Rooted<JS::Value> typeError(cx); if (!JS::CreateTypeError(cx, stack, fn, lineNumber, 0, nullptr, message, &typeError)) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } mNextPromise->RejectInternal(cx, typeError, Promise::SyncTask); return; } } // Otherwise, run resolver's resolve with value and the synchronous flag // set. if (!JS_WrapValue(cx, &retValue)) { NS_WARNING("Failed to wrap value into the right compartment."); return; } mNextPromise->ResolveInternal(cx, retValue, Promise::SyncTask); }
JSObject* DLLCALL js_CreateXtrnAreaObject(JSContext* cx, JSObject* parent, scfg_t* cfg ,user_t* user, client_t* client) { JSObject* areaobj; JSObject* allsec; JSObject* allprog; JSObject* secobj; JSObject* progobj; JSObject* eventobj; JSObject* event_array; JSObject* xeditobj; JSObject* xedit_array; JSObject* sec_list; JSObject* prog_list; JSString* js_str; jsval val; jsuint sec_index; jsuint prog_index; uint l,d; /* Return existing object if it's already been created */ if(JS_GetProperty(cx,parent,"xtrn_area",&val) && val!=JSVAL_VOID) areaobj = JSVAL_TO_OBJECT(val); else areaobj = JS_DefineObject(cx, parent, "xtrn_area", NULL , NULL, JSPROP_ENUMERATE|JSPROP_READONLY); if(areaobj==NULL) return(NULL); #ifdef BUILD_JSDOCS js_DescribeSyncObject(cx,areaobj,"External Program Areas",310); #endif /* xtrn_area.sec[] */ if((allsec=JS_NewObject(cx,NULL,NULL,areaobj))==NULL) return(NULL); val=OBJECT_TO_JSVAL(allsec); if(!JS_SetProperty(cx, areaobj, "sec", &val)) return(NULL); /* xtrn_area.prog[] */ if((allprog=JS_NewObject(cx,NULL,NULL,areaobj))==NULL) return(NULL); val=OBJECT_TO_JSVAL(allprog); if(!JS_SetProperty(cx, areaobj, "prog", &val)) return(NULL); /* xtrn_area.sec_list[] */ if((sec_list=JS_NewArrayObject(cx, 0, NULL))==NULL) return(NULL); val=OBJECT_TO_JSVAL(sec_list); if(!JS_SetProperty(cx, areaobj, "sec_list", &val)) return(NULL); for(l=0;l<cfg->total_xtrnsecs;l++) { if((secobj=JS_NewObject(cx, NULL, NULL, NULL))==NULL) return(NULL); sec_index=-1; if(user==NULL || chk_ar(cfg,cfg->xtrnsec[l]->ar,user,client)) { if(!JS_GetArrayLength(cx, sec_list, &sec_index)) return(NULL); val=OBJECT_TO_JSVAL(secobj); if(!JS_SetElement(cx, sec_list, sec_index, &val)) return(NULL); } /* Add as property (associative array element) */ if(!JS_DefineProperty(cx, allsec, cfg->xtrnsec[l]->code, val ,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE)) return(NULL); val=INT_TO_JSVAL(sec_index); if(!JS_SetProperty(cx, secobj, "index", &val)) return(NULL); val=INT_TO_JSVAL(l); if(!JS_SetProperty(cx, secobj, "number", &val)) return(NULL); if((js_str=JS_NewStringCopyZ(cx, cfg->xtrnsec[l]->code))==NULL) return(NULL); val=STRING_TO_JSVAL(js_str); if(!JS_SetProperty(cx, secobj, "code", &val)) return(NULL); if((js_str=JS_NewStringCopyZ(cx, cfg->xtrnsec[l]->name))==NULL) return(NULL); val=STRING_TO_JSVAL(js_str); if(!JS_SetProperty(cx, secobj, "name", &val)) return(NULL); if((js_str=JS_NewStringCopyZ(cx, cfg->xtrnsec[l]->arstr))==NULL) return(NULL); val=STRING_TO_JSVAL(js_str); if(!JS_SetProperty(cx, secobj, "ars", &val)) return(NULL); if(user==NULL || chk_ar(cfg,cfg->xtrnsec[l]->ar,user,client)) val=JSVAL_TRUE; else val=JSVAL_FALSE; if(!JS_SetProperty(cx, secobj, "can_access", &val)) return(NULL); /* prog_list[] */ if((prog_list=JS_NewArrayObject(cx, 0, NULL))==NULL) return(NULL); val=OBJECT_TO_JSVAL(prog_list); if(!JS_SetProperty(cx, secobj, "prog_list", &val)) return(NULL); #ifdef BUILD_JSDOCS js_DescribeSyncObject(cx,secobj,"Online Program (door) Sections (current user has access to)",310); #endif for(d=0;d<cfg->total_xtrns;d++) { if(cfg->xtrn[d]->sec!=l) continue; if((progobj=JS_NewObject(cx, NULL, NULL, NULL))==NULL) return(NULL); prog_index=-1; if((user==NULL || chk_ar(cfg,cfg->xtrn[d]->ar,user,client)) && !(cfg->xtrn[d]->event && cfg->xtrn[d]->misc&EVENTONLY)) { if(!JS_GetArrayLength(cx, prog_list, &prog_index)) return(NULL); val=OBJECT_TO_JSVAL(progobj); if(!JS_SetElement(cx, prog_list, prog_index, &val)) return(NULL); } /* Add as property (associative array element) */ if(!JS_DefineProperty(cx, allprog, cfg->xtrn[d]->code, val ,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE)) return(NULL); val=INT_TO_JSVAL(prog_index); if(!JS_SetProperty(cx, progobj, "index", &val)) return(NULL); val=INT_TO_JSVAL(d); if(!JS_SetProperty(cx, progobj, "number", &val)) return(NULL); val=INT_TO_JSVAL(sec_index); if(!JS_SetProperty(cx, progobj, "sec_index", &val)) return(NULL); val=INT_TO_JSVAL(l); if(!JS_SetProperty(cx, progobj, "sec_number", &val)) return(NULL); val=STRING_TO_JSVAL(JS_NewStringCopyZ(cx,cfg->xtrnsec[l]->code)); if(!JS_SetProperty(cx, progobj, "sec_code", &val)) return(NULL); if(!js_CreateXtrnProgProperties(cx, progobj, cfg->xtrn[d])) return(NULL); if(user==NULL || chk_ar(cfg,cfg->xtrn[d]->ar,user,client)) val=JSVAL_TRUE; else val=JSVAL_FALSE; if(!JS_SetProperty(cx, progobj, "can_access", &val)) return(NULL); if(user==NULL || chk_ar(cfg,cfg->xtrn[d]->run_ar,user,client)) val=JSVAL_TRUE; else val=JSVAL_FALSE; if(!JS_SetProperty(cx, progobj, "can_run", &val)) return(NULL); #ifdef BUILD_JSDOCS js_DescribeSyncObject(cx,progobj,"Online External Programs (doors) (current user has access to)",310); #endif } #ifdef BUILD_JSDOCS js_CreateArrayOfStrings(cx, secobj, "_property_desc_list", xtrn_sec_prop_desc, JSPROP_READONLY); #endif } #ifdef BUILD_JSDOCS js_DescribeSyncObject(cx,allsec,"Associative array of all external program sections (use internal code as index)",312); JS_DefineProperty(cx,allsec,"_dont_document",JSVAL_TRUE,NULL,NULL,JSPROP_READONLY); js_DescribeSyncObject(cx,allprog,"Associative array of all external programs (use internal code as index)",311); JS_DefineProperty(cx,allprog,"_dont_document",JSVAL_TRUE,NULL,NULL,JSPROP_READONLY); #endif /* Create event property */ if((event_array=JS_NewObject(cx,NULL,NULL,areaobj))==NULL) return(NULL); val=OBJECT_TO_JSVAL(event_array); if(!JS_SetProperty(cx, areaobj, "event", &val)) return(NULL); for(l=0;l<cfg->total_events;l++) { if((eventobj=JS_NewObject(cx, NULL, NULL, NULL))==NULL) return(NULL); if(!JS_DefineProperty(cx, event_array, cfg->event[l]->code, OBJECT_TO_JSVAL(eventobj) ,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE)) return(NULL); if((js_str=JS_NewStringCopyZ(cx, cfg->event[l]->cmd))==NULL) return(NULL); if(!JS_DefineProperty(cx, eventobj, "cmd", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if((js_str=JS_NewStringCopyZ(cx, cfg->event[l]->dir))==NULL) return(NULL); if(!JS_DefineProperty(cx, eventobj, "startup_dir", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, eventobj, "node_num", INT_TO_JSVAL(cfg->event[l]->node) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, eventobj, "time", INT_TO_JSVAL(cfg->event[l]->time) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, eventobj, "freq", INT_TO_JSVAL(cfg->event[l]->freq) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, eventobj, "days", INT_TO_JSVAL(cfg->event[l]->days) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, eventobj, "mdays", INT_TO_JSVAL(cfg->event[l]->mdays) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, eventobj, "months", INT_TO_JSVAL(cfg->event[l]->months) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, eventobj, "last_run", INT_TO_JSVAL(cfg->event[l]->last) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, eventobj, "settings", INT_TO_JSVAL(cfg->event[l]->misc) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); #ifdef BUILD_JSDOCS js_CreateArrayOfStrings(cx, eventobj, "_property_desc_list", event_prop_desc, JSPROP_READONLY); #endif } #ifdef BUILD_JSDOCS js_DescribeSyncObject(cx,event_array,"Associative array of all timed events (use internal code as index)",311); JS_DefineProperty(cx,event_array,"_assoc_array",JSVAL_TRUE,NULL,NULL,JSPROP_READONLY); #endif /* Create editor property */ if((xedit_array=JS_NewObject(cx,NULL,NULL,areaobj))==NULL) return(NULL); val=OBJECT_TO_JSVAL(xedit_array); if(!JS_SetProperty(cx, areaobj, "editor", &val)) return(NULL); for(l=0;l<cfg->total_xedits;l++) { if(user!=NULL && !chk_ar(cfg,cfg->xedit[l]->ar,user,client)) continue; if((xeditobj=JS_NewObject(cx, NULL, NULL, NULL))==NULL) return(NULL); if(!JS_DefineProperty(cx, xedit_array, cfg->xedit[l]->code, OBJECT_TO_JSVAL(xeditobj) ,NULL,NULL,JSPROP_READONLY|JSPROP_ENUMERATE)) return(NULL); if((js_str=JS_NewStringCopyZ(cx, cfg->xedit[l]->name))==NULL) return(NULL); if(!JS_DefineProperty(cx, xeditobj, "name", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if((js_str=JS_NewStringCopyZ(cx, cfg->xedit[l]->rcmd))==NULL) return(NULL); if(!JS_DefineProperty(cx, xeditobj, "cmd", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if((js_str=JS_NewStringCopyZ(cx, cfg->xedit[l]->arstr))==NULL) return(NULL); if(!JS_DefineProperty(cx, xeditobj, "ars", STRING_TO_JSVAL(js_str) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, xeditobj, "settings", INT_TO_JSVAL(cfg->xedit[l]->misc) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); if(!JS_DefineProperty(cx, xeditobj, "type", INT_TO_JSVAL(cfg->xedit[l]->type) ,NULL,NULL,JSPROP_ENUMERATE|JSPROP_READONLY)) return(NULL); #ifdef BUILD_JSDOCS js_CreateArrayOfStrings(cx, xeditobj, "_property_desc_list", xedit_prop_desc, JSPROP_READONLY); #endif } #ifdef BUILD_JSDOCS js_DescribeSyncObject(cx,xedit_array,"Associative array of all external editors (use internal code as index)",311); JS_DefineProperty(cx,xedit_array,"_assoc_array",JSVAL_TRUE,NULL,NULL,JSPROP_READONLY); #endif return(areaobj); }
int js_plugin_load(const char *id, const char *url, char *errbuf, size_t errlen) { char *sbuf; struct fa_stat fs; JSContext *cx; js_plugin_t *jsp; JSObject *pobj, *gobj; JSScript *s; char path[PATH_MAX]; jsval val; fa_handle_t *ref; ref = fa_reference(url); if((sbuf = fa_quickload(url, &fs, NULL, errbuf, errlen)) == NULL) { fa_unreference(ref); return -1; } cx = js_newctx(err_reporter); JS_BeginRequest(cx); /* Remove any plugin with same URL */ LIST_FOREACH(jsp, &js_plugins, jsp_link) if(!strcmp(jsp->jsp_id, id)) break; if(jsp != NULL) js_plugin_unload0(cx, jsp); jsp = calloc(1, sizeof(js_plugin_t)); jsp->jsp_url = strdup(url); jsp->jsp_id = strdup(id); jsp->jsp_ref = ref; LIST_INSERT_HEAD(&js_plugins, jsp, jsp_link); gobj = JS_NewObject(cx, &global_class, NULL, NULL); JS_InitStandardClasses(cx, gobj); JS_DefineProperty(cx, gobj, "showtime", OBJECT_TO_JSVAL(showtimeobj), NULL, NULL, JSPROP_READONLY | JSPROP_PERMANENT); /* Plugin object */ pobj = JS_NewObject(cx, &plugin_class, NULL, gobj); JS_AddNamedRoot(cx, &pobj, "plugin"); JS_SetPrivate(cx, pobj, jsp); JS_DefineFunctions(cx, pobj, plugin_functions); val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, url)); JS_SetProperty(cx, pobj, "url", &val); if(!fa_parent(path, sizeof(path), url)) { val = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, path)); JS_SetProperty(cx, pobj, "path", &val); } JS_DefineProperty(cx, pobj, "URIRouting", BOOLEAN_TO_JSVAL(1), NULL, jsp_setEnableURIRoute, JSPROP_PERMANENT); jsp->jsp_enable_uri_routing = 1; JS_DefineProperty(cx, pobj, "search", BOOLEAN_TO_JSVAL(1), NULL, jsp_setEnableSearch, JSPROP_PERMANENT); jsp->jsp_enable_search = 1; jsp->jsp_protect_object = 1; s = JS_CompileScript(cx, pobj, sbuf, fs.fs_size, url, 1); free(sbuf); if(s != NULL) { JSObject *sobj = JS_NewScriptObject(cx, s); jsval result; JS_AddNamedRoot(cx, &sobj, "script"); JS_ExecuteScript(cx, pobj, s, &result); JS_RemoveRoot(cx, &sobj); } JS_RemoveRoot(cx, &pobj); JS_EndRequest(cx); JS_GC(cx); JS_DestroyContext(cx); return 0; }
void WrapperPromiseCallback::Call(JS::Handle<JS::Value> aValue) { // AutoCxPusher and co. interact with xpconnect, which crashes on // workers. On workers we'll get the right context from // GetDefaultJSContextForThread(), and since there is only one context, we // don't need to push or pop it from the stack. JSContext* cx = nsContentUtils::GetDefaultJSContextForThread(); Maybe<AutoCxPusher> pusher; if (NS_IsMainThread()) { pusher.construct(cx); } Maybe<JSAutoCompartment> ac; EnterCompartment(ac, cx, aValue); ErrorResult rv; // If invoking callback threw an exception, run resolver's reject with the // thrown exception as argument and the synchronous flag set. JS::Rooted<JS::Value> value(cx, mCallback->Call(aValue, rv, CallbackObject::eRethrowExceptions)); rv.WouldReportJSException(); if (rv.Failed() && rv.IsJSException()) { JS::Rooted<JS::Value> value(cx); rv.StealJSException(cx, &value); Maybe<JSAutoCompartment> ac2; EnterCompartment(ac2, cx, value); mNextPromise->RejectInternal(cx, value, Promise::SyncTask); return; } // If the return value is the same as the promise itself, throw TypeError. if (value.isObject()) { JS::Rooted<JSObject*> valueObj(cx, &value.toObject()); Promise* returnedPromise; nsresult r = UNWRAP_OBJECT(Promise, valueObj, returnedPromise); if (NS_SUCCEEDED(r) && returnedPromise == mNextPromise) { const char* fileName = nullptr; uint32_t lineNumber = 0; // Try to get some information about the callback to report a sane error, // but don't try too hard (only deals with scripted functions). JS::Rooted<JSObject*> unwrapped(cx, js::CheckedUnwrap(mCallback->Callback())); if (unwrapped) { JSAutoCompartment ac(cx, unwrapped); if (JS_ObjectIsFunction(cx, unwrapped)) { JS::Rooted<JS::Value> asValue(cx, JS::ObjectValue(*unwrapped)); JS::Rooted<JSFunction*> func(cx, JS_ValueToFunction(cx, asValue)); MOZ_ASSERT(func); JSScript* script = JS_GetFunctionScript(cx, func); if (script) { fileName = JS_GetScriptFilename(cx, script); lineNumber = JS_GetScriptBaseLineNumber(cx, script); } } } // We're back in aValue's compartment here. JS::Rooted<JSString*> stack(cx, JS_GetEmptyString(JS_GetRuntime(cx))); JS::Rooted<JSString*> fn(cx, JS_NewStringCopyZ(cx, fileName)); if (!fn) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } JS::Rooted<JSString*> message(cx, JS_NewStringCopyZ(cx, "then() cannot return same Promise that it resolves.")); if (!message) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } JS::Rooted<JS::Value> typeError(cx); if (!JS::CreateTypeError(cx, stack, fn, lineNumber, 0, nullptr, message, &typeError)) { // Out of memory. Promise will stay unresolved. JS_ClearPendingException(cx); return; } mNextPromise->RejectInternal(cx, typeError, Promise::SyncTask); return; } } // Otherwise, run resolver's resolve with value and the synchronous flag // set. Maybe<JSAutoCompartment> ac2; EnterCompartment(ac2, cx, value); mNextPromise->ResolveInternal(cx, value, Promise::SyncTask); }
static JSBool js_get(JSContext *cx, JSObject *obj, jsid id, jsval *vp) { jsval idval; jsint tiny; jsrefcount rc; JS_IdToValue(cx, id, &idval); tiny = JSVAL_TO_INT(idval); rc=JS_SUSPENDREQUEST(cx); switch(tiny) { case PROP_WSCROLL: *vp=BOOLEAN_TO_JSVAL(_wscroll); break; case PROP_DIRECTVIDEO: *vp=BOOLEAN_TO_JSVAL(directvideo); break; case PROP_HOLD_UPDATE: *vp=BOOLEAN_TO_JSVAL(hold_update); break; case PROP_PUTTEXT_CAN_MOVE: *vp=BOOLEAN_TO_JSVAL(puttext_can_move); break; case PROP_MODE: *vp=INT_TO_JSVAL(cio_api.mode); break; case PROP_MOUSE: *vp=BOOLEAN_TO_JSVAL(cio_api.mouse); break; case PROP_ESCDELAY: *vp=INT_TO_JSVAL(cio_api.ESCDELAY?*cio_api.ESCDELAY:0); break; case PROP_TEXTATTR: *vp=INT_TO_JSVAL(cio_textinfo.attribute); break; case PROP_KBHIT: *vp=BOOLEAN_TO_JSVAL(kbhit()); break; case PROP_WHEREX: *vp=INT_TO_JSVAL(cio_textinfo.curx); break; case PROP_WHEREY: *vp=INT_TO_JSVAL(cio_textinfo.cury); break; case PROP_TEXTMODE: *vp=INT_TO_JSVAL(cio_textinfo.currmode); break; case PROP_WINLEFT: *vp=INT_TO_JSVAL(cio_textinfo.winleft); break; case PROP_WINTOP: *vp=INT_TO_JSVAL(cio_textinfo.wintop); break; case PROP_WINRIGHT: *vp=INT_TO_JSVAL(cio_textinfo.winright); break; case PROP_WINBOTTOM: *vp=INT_TO_JSVAL(cio_textinfo.winbottom); break; case PROP_SCREENWIDTH: *vp=INT_TO_JSVAL(cio_textinfo.screenwidth); break; case PROP_SCREENHEIGHT: *vp=INT_TO_JSVAL(cio_textinfo.screenheight); break; case PROP_NORMATTR: *vp=INT_TO_JSVAL(cio_textinfo.normattr); break; case PROP_TEXTBACKGROUND: *vp=INT_TO_JSVAL((cio_textinfo.attribute & 0x70)>>4); break; case PROP_TEXTCOLOR: *vp=INT_TO_JSVAL(cio_textinfo.attribute & 0xf); break; case PROP_CLIPBOARD: *vp=STRING_TO_JSVAL(JS_NewStringCopyZ(cx,getcliptext())); break; case PROP_HIGHVIDEO: *vp=BOOLEAN_TO_JSVAL(cio_textinfo.attribute & 0x8); break; case PROP_LOWVIDEO: *vp=BOOLEAN_TO_JSVAL(!(cio_textinfo.attribute & 0x8)); break; } JS_RESUMEREQUEST(cx, rc); return(JS_TRUE); }
url_setProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) { JSURL *url; const char *href, *name, *checked_href; char *new_href, *prop_name; JSBool free_href; jsval tmp; JSString *str; MWContext *context; LO_AnchorData *anchor_data; JSBool ok; jsint slot; url = JS_GetInstancePrivate(cx, obj, &lm_url_class, NULL); if (!url) { url = JS_GetInstancePrivate(cx, obj, &lm_location_class, NULL); if (!url) return JS_TRUE; } /* If the property is setting an event handler we find out now so * that we can tell the front end to send the event. */ if (JSVAL_IS_STRING(id)) { prop_name = JS_GetStringBytes(JSVAL_TO_STRING(id)); if (XP_STRCASECMP(prop_name, lm_onClick_str) == 0 || XP_STRCASECMP(prop_name, lm_onMouseDown_str) == 0 || XP_STRCASECMP(prop_name, lm_onMouseOver_str) == 0 || XP_STRCASECMP(prop_name, lm_onMouseOut_str) == 0 || XP_STRCASECMP(prop_name, lm_onMouseUp_str) == 0) { context = url->url_decoder->window_context; if (context) { anchor_data = LO_GetLinkByIndex(context, url->layer_id, url->index); if (anchor_data) anchor_data->event_handler_present = TRUE; } } return JS_TRUE; } XP_ASSERT(JSVAL_IS_INT(id)); slot = JSVAL_TO_INT(id); if (slot < 0) { /* Don't mess with user-defined or method properties. */ return JS_TRUE; } if (!JSVAL_IS_STRING(*vp) && !JS_ConvertValue(cx, *vp, JSTYPE_STRING, vp)) { return JS_FALSE; } ok = JS_TRUE; switch (slot) { case URL_HREF: url->href = JSVAL_TO_STRING(*vp); href = JS_GetStringBytes(url->href); free_href = JS_FALSE; break; case URL_PROTOCOL: case URL_HOST: case URL_HOSTNAME: case URL_PORT: case URL_PATHNAME: case URL_HASH: case URL_SEARCH: /* a component property changed -- recompute href. */ new_href = NULL; #define GET_SLOT(aslot, ptmp) { \ if (aslot == slot) { \ *(ptmp) = *vp; \ } else { \ if (!JS_GetElement(cx, obj, aslot, ptmp)) { \ if (new_href) XP_FREE(new_href); \ return JS_FALSE; \ } \ } \ } #define ADD_SLOT(aslot, separator) { \ GET_SLOT(aslot, &tmp); \ name = JS_GetStringBytes(JSVAL_TO_STRING(tmp)); \ if (*name) { \ if (separator) StrAllocCat(new_href, separator); \ StrAllocCat(new_href, name); \ } \ } GET_SLOT(URL_PROTOCOL, &tmp); StrAllocCopy(new_href, JS_GetStringBytes(JSVAL_TO_STRING(tmp))); if (slot == URL_HOST) { ADD_SLOT(URL_HOST, "//"); } else { ADD_SLOT(URL_HOSTNAME, "//"); ADD_SLOT(URL_PORT, ":"); } ADD_SLOT(URL_PATHNAME, NULL); ADD_SLOT(URL_HASH, NULL); ADD_SLOT(URL_SEARCH, NULL); if (!new_href) { JS_ReportOutOfMemory(cx); return JS_FALSE; } free_href = JS_TRUE; href = new_href; str = JS_NewStringCopyZ(cx, href); if (!str) { ok = JS_FALSE; goto out; } url->href = str; break; case URL_TARGET: url->target = JSVAL_TO_STRING(*vp); if (url->index != URL_NOT_INDEXED) { context = url->url_decoder->window_context; if (context) { anchor_data = LO_GetLinkByIndex(context, url->layer_id, url->index); if (anchor_data) { name = JS_GetStringBytes(url->target); if (!lm_CheckWindowName(cx, name)) return JS_FALSE; if (!lm_SaveParamString(cx, &anchor_data->target, name)) return JS_FALSE; } } } /* Note early return, to bypass href update and freeing. */ return JS_TRUE; default: /* Don't mess with a user-defined property. */ return ok; } if (url->index != URL_NOT_INDEXED) { context = url->url_decoder->window_context; if (context) { anchor_data = LO_GetLinkByIndex(context, url->layer_id, url->index); if (anchor_data) { checked_href = lm_CheckURL(cx, href, JS_FALSE); if (!checked_href || !lm_SaveParamString(cx, &anchor_data->anchor, checked_href)) { ok = JS_FALSE; goto out; } XP_FREE((char *)checked_href); } } } out: if (free_href && href) XP_FREE((char *)href); return ok; }
int ExecShellScript(const char * file, int argc, char** argv, JSContext * context, JSObject * env, jsval * vp) { register FILE * filep; register int c; filep = fopen(file, "rb"); if (!filep) { JS_ReportError(context, "%s: %s", file, "No such file or directory"); return 0; } if (getc(filep) == '#' && getc(filep) == '!') { c = 1; while (c != EOF && c != '\n') c = getc(filep); ungetc(c, filep); } else { fclose(filep); JS_ReportError(context, "%s: %s", file, "is not a shell script"); return 0; } JSObject* argsObj = JS_NewArrayObject(context, 0, NULL); JS_DefineProperty(context, env, "parameter", OBJECT_TO_JSVAL(argsObj), NULL, NULL, 0); JSString* str = JS_NewStringCopyZ(context, file); JS_DefineElement(context, argsObj, 0, STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE); int i; for (i = 0; i < argc; i++) { str = JS_NewStringCopyZ(context, argv[i]); JS_DefineElement(context, argsObj, i + 1, STRING_TO_JSVAL(str), NULL, NULL, JSPROP_ENUMERATE); } setenv(SMASH_RESOURCE_PATH_ENV_ID, GET_STRING_DEF(SMASH_RESOURCE_PATH), 0); JS_InitCTypesClass(context, env); JS_DefineFunctions(context, env, shell_functions); JS_DefineProperties(context, env, shell_properties); jsval fun; JS_GetProperty(context, env, "system", &fun); JS_DefineFunction(context, JSVAL_TO_OBJECT(fun), "read", ShellSystemRead, 1, JSPROP_ENUMERATE); JS_DefineFunction(context, JSVAL_TO_OBJECT(fun), "write", ShellSystemWrite, 2, JSPROP_ENUMERATE); jsval fun2; JS_GetProperty(context, env, "echo", &fun2); JS_DefineFunction(context, JSVAL_TO_OBJECT(fun2), "error", ShellEchoError, 1, JSPROP_ENUMERATE); jsval fun3; JS_GetProperty(context, env, "setFileContent", &fun3); JS_DefineFunction(context, JSVAL_TO_OBJECT(fun3), "append", ShellSetFileContentAppend, 2, JSPROP_ENUMERATE); #ifdef SMASH_MAIN_LOADER //ExecScriptFile(context, env, GET_STRING_DEF(SMASH_MAIN_LOADER), NULL); #endif #ifdef SMASH_SHELL_LOADER ExecScriptFile(context, env, GET_STRING_DEF(SMASH_SHELL_LOADER), NULL); #endif JSObject * jsTemp = JS_CompileFileHandle(context, env, file, filep); fclose(filep); if (jsTemp) { return JS_ExecuteScript(context, env, jsTemp, vp); } else { JS_ReportPendingException(context); return 1; } }
/** * Define OS-specific constants. * * This function creates or uses JS object |OS.Constants| to store * all its constants. */ bool DefineOSFileConstants(JSContext *cx, JS::Handle<JSObject*> global) { MOZ_ASSERT(gInitialized); if (gPaths == nullptr) { // If an initialization error was ignored, we may end up with // |gInitialized == true| but |gPaths == nullptr|. We cannot // |MOZ_ASSERT| this, as this would kill precompile_cache.js, // so we simply return an error. JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_OPEN, "OSFileConstants", "initialization has failed"); return false; } JS::Rooted<JSObject*> objOS(cx); if (!(objOS = GetOrCreateObjectProperty(cx, global, "OS"))) { return false; } JS::Rooted<JSObject*> objConstants(cx); if (!(objConstants = GetOrCreateObjectProperty(cx, objOS, "Constants"))) { return false; } // Build OS.Constants.libc JS::Rooted<JSObject*> objLibc(cx); if (!(objLibc = GetOrCreateObjectProperty(cx, objConstants, "libc"))) { return false; } if (!dom::DefineConstants(cx, objLibc, gLibcProperties)) { return false; } #if defined(XP_WIN) // Build OS.Constants.Win JS::Rooted<JSObject*> objWin(cx); if (!(objWin = GetOrCreateObjectProperty(cx, objConstants, "Win"))) { return false; } if (!dom::DefineConstants(cx, objWin, gWinProperties)) { return false; } #endif // defined(XP_WIN) // Build OS.Constants.Sys JS::Rooted<JSObject*> objSys(cx); if (!(objSys = GetOrCreateObjectProperty(cx, objConstants, "Sys"))) { return false; } nsCOMPtr<nsIXULRuntime> runtime = do_GetService(XULRUNTIME_SERVICE_CONTRACTID); if (runtime) { nsAutoCString os; DebugOnly<nsresult> rv = runtime->GetOS(os); MOZ_ASSERT(NS_SUCCEEDED(rv)); JSString* strVersion = JS_NewStringCopyZ(cx, os.get()); if (!strVersion) { return false; } JS::Rooted<JS::Value> valVersion(cx, STRING_TO_JSVAL(strVersion)); if (!JS_SetProperty(cx, objSys, "Name", valVersion)) { return false; } } #if defined(DEBUG) JS::Rooted<JS::Value> valDebug(cx, JSVAL_TRUE); if (!JS_SetProperty(cx, objSys, "DEBUG", valDebug)) { return false; } #endif // Build OS.Constants.Path JS::Rooted<JSObject*> objPath(cx); if (!(objPath = GetOrCreateObjectProperty(cx, objConstants, "Path"))) { return false; } // Locate libxul // Note that we don't actually provide the full path, only the name of the // library, which is sufficient to link to the library using js-ctypes. #if defined(XP_MACOSX) // Under MacOS X, for some reason, libxul is called simply "XUL", // and we need to provide the full path. nsAutoString libxul; libxul.Append(gPaths->libDir); libxul.Append(NS_LITERAL_STRING("/XUL")); #else // On other platforms, libxul is a library "xul" with regular // library prefix/suffix. nsAutoString libxul; libxul.Append(NS_LITERAL_STRING(DLL_PREFIX)); libxul.Append(NS_LITERAL_STRING("xul")); libxul.Append(NS_LITERAL_STRING(DLL_SUFFIX)); #endif // defined(XP_MACOSX) if (!SetStringProperty(cx, objPath, "libxul", libxul)) { return false; } if (!SetStringProperty(cx, objPath, "libDir", gPaths->libDir)) { return false; } if (!SetStringProperty(cx, objPath, "tmpDir", gPaths->tmpDir)) { return false; } // Configure profileDir only if it is available at this stage if (!gPaths->profileDir.IsVoid() && !SetStringProperty(cx, objPath, "profileDir", gPaths->profileDir)) { return false; } // Configure localProfileDir only if it is available at this stage if (!gPaths->localProfileDir.IsVoid() && !SetStringProperty(cx, objPath, "localProfileDir", gPaths->localProfileDir)) { return false; } if (!SetStringProperty(cx, objPath, "homeDir", gPaths->homeDir)) { return false; } if (!SetStringProperty(cx, objPath, "desktopDir", gPaths->desktopDir)) { return false; } if (!SetStringProperty(cx, objPath, "userApplicationDataDir", gPaths->userApplicationDataDir)) { return false; } #if defined(XP_WIN) if (!SetStringProperty(cx, objPath, "winAppDataDir", gPaths->winAppDataDir)) { return false; } if (!SetStringProperty(cx, objPath, "winStartMenuProgsDir", gPaths->winStartMenuProgsDir)) { return false; } #endif // defined(XP_WIN) #if defined(XP_MACOSX) if (!SetStringProperty(cx, objPath, "macUserLibDir", gPaths->macUserLibDir)) { return false; } if (!SetStringProperty(cx, objPath, "macLocalApplicationsDir", gPaths->macLocalApplicationsDir)) { return false; } #endif // defined(XP_MACOSX) // sqlite3 is linked from different places depending on the platform nsAutoString libsqlite3; #if defined(ANDROID) // On Android, we use the system's libsqlite3 libsqlite3.Append(NS_LITERAL_STRING(DLL_PREFIX)); libsqlite3.Append(NS_LITERAL_STRING("sqlite3")); libsqlite3.Append(NS_LITERAL_STRING(DLL_SUFFIX)); #elif defined(XP_WIN) // On Windows, for some reason, this is part of nss3.dll libsqlite3.Append(NS_LITERAL_STRING(DLL_PREFIX)); libsqlite3.Append(NS_LITERAL_STRING("nss3")); libsqlite3.Append(NS_LITERAL_STRING(DLL_SUFFIX)); #else // On other platforms, we link sqlite3 into libxul libsqlite3 = libxul; #endif // defined(ANDROID) || defined(XP_WIN) if (!SetStringProperty(cx, objPath, "libsqlite3", libsqlite3)) { return false; } return true; }
INT unit_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) { CDebug cDbg("unit getProperty"); BnetData* pData = *p_D2LAUNCH_BnData; GameStructInfo* pInfo = *p_D2CLIENT_GameInfo; switch(JSVAL_TO_INT(id)) { case ME_ACCOUNT: if(!pData) return JS_TRUE; *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szAccountName)); break; case ME_CHARNAME: if(!pInfo) return JS_TRUE; *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szCharName)); break; case ME_CHICKENHP: *vp = INT_TO_JSVAL(Vars.nChickenHP); break; case ME_CHICKENMP: *vp = INT_TO_JSVAL(Vars.nChickenMP); break; case ME_DIFF: *vp = INT_TO_JSVAL(D2CLIENT_GetDifficulty()); break; case ME_GAMENAME: if(!pInfo) return JS_TRUE; *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGameName)); break; case ME_GAMEPASSWORD: if(!pInfo) return JS_TRUE; *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGamePassword)); break; case ME_GAMESERVERIP: if(!pInfo) return JS_TRUE; *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pInfo->szGameServerIp)); break; case ME_GAMESTARTTIME: *vp = INT_TO_JSVAL(Vars.dwGameTime); break; case ME_GAMETYPE: *vp = INT_TO_JSVAL(*p_D2CLIENT_ExpCharFlag); break; case ME_ITEMONCURSOR: *vp = BOOLEAN_TO_JSVAL(!!D2CLIENT_GetCursorItem()); break; case ME_LADDER: if(pData) *vp = BOOLEAN_TO_JSVAL(((pData->nCharFlags & PLAYER_TYPE_LADDER) == TRUE)); break; case ME_QUITONHOSTILE: *vp = BOOLEAN_TO_JSVAL(Vars.bQuitOnHostile); break; case ME_REALM: *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szRealmName)); break; case ME_REALMSHORT: *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pData->szRealmName2)); break; case OOG_SCREENSIZE: *vp = INT_TO_JSVAL(D2GFX_GetScreenSize()); break; case OOG_WINDOWTITLE: CHAR szTitle[128]; GetWindowText(D2WIN_GetHwnd(), szTitle, 128); *vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, szTitle)); break; case ME_PING: *vp = INT_TO_JSVAL(*p_D2CLIENT_Ping); break; case OOG_INGAME: *vp = BOOLEAN_TO_JSVAL(ClientState() == ClientStateMenu ? FALSE : TRUE); break; case OOG_QUITONERROR: *vp = BOOLEAN_TO_JSVAL(Vars.bQuitOnError); break; case OOG_MAXGAMETIME: *vp = INT_TO_JSVAL(Vars.dwMaxGameTime); break; case OOG_DEBUG: *vp = BOOLEAN_TO_JSVAL(Vars.bDebug); break; case ME_MERCREVIVECOST: *vp = INT_TO_JSVAL((*p_D2CLIENT_MercReviveCost)); break; case ME_BLOCKKEYS: *vp = BOOLEAN_TO_JSVAL(Vars.bBlockKeys); break; case ME_BLOCKMOUSE: *vp = BOOLEAN_TO_JSVAL(Vars.bBlockMouse); break; default: break; } /* // TODO: Properly fix this... if ((JSVAL_TO_INT(id) < OOG_WINDOWTITLE) && !GameReady()) return JS_TRUE; */ if(!GameReady()) return JS_TRUE; myUnit* lpUnit = (myUnit*)JS_GetPrivate(cx, obj); if(!lpUnit || IsBadReadPtr(lpUnit, sizeof(myUnit)) || lpUnit->_dwPrivateType != PRIVATE_UNIT) return JS_TRUE; UnitAny* pUnit = D2CLIENT_FindUnit(lpUnit->dwUnitId, lpUnit->dwType); if(!pUnit) return JS_TRUE; char* tmp = NULL; Room1* pRoom = NULL; switch(JSVAL_TO_INT(id)) { case UNIT_TYPE: *vp = INT_TO_JSVAL(pUnit->dwType); break; case UNIT_CLASSID: *vp = INT_TO_JSVAL(pUnit->dwTxtFileNo); break; case UNIT_MODE: *vp = INT_TO_JSVAL(pUnit->dwMode); break; case UNIT_NAME: tmp = new char[8192]; GetUnitName(pUnit, tmp, 8192); *vp = STRING_TO_JSVAL(JS_InternString(cx, tmp)); delete[] tmp; break; case UNIT_ACT: *vp = INT_TO_JSVAL(pUnit->dwAct + 1); break; case UNIT_AREA: pRoom = D2COMMON_GetRoomFromUnit(pUnit); if(pRoom && pRoom->pRoom2 && pRoom->pRoom2->pLevel) *vp = INT_TO_JSVAL(pRoom->pRoom2->pLevel->dwLevelNo); break; case UNIT_ID: *vp = INT_TO_JSVAL(pUnit->dwUnitId); break; case UNIT_XPOS: *vp = INT_TO_JSVAL(GetUnitX(pUnit)); break; case UNIT_YPOS: *vp = INT_TO_JSVAL(GetUnitY(pUnit)); break; case UNIT_HP: *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 6, 0) >> 8); break; case UNIT_HPMAX: *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 7, 0) >> 8); break; case UNIT_MP: *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 8, 0) >> 8); break; case UNIT_MPMAX: *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 9, 0) >> 8); break; case UNIT_STAMINA: *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 10, 0) >> 8); break; case UNIT_STAMINAMAX: *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 11, 0) >> 8); break; case UNIT_CHARLVL: *vp = INT_TO_JSVAL(D2COMMON_GetUnitStat(pUnit, 12, 0)); break; case ME_RUNWALK: *vp = INT_TO_JSVAL(*p_D2CLIENT_AlwaysRun); break; case UNIT_ADDRESS: *vp = INT_TO_JSVAL(pUnit); break; case UNIT_SPECTYPE: DWORD SpecType; SpecType = NULL; if(pUnit->dwType == UNIT_MONSTER && pUnit->pMonsterData) { if(pUnit->pMonsterData->fMinion & 1) SpecType |= 0x08; if(pUnit->pMonsterData->fBoss & 1) SpecType |= 0x04; if(pUnit->pMonsterData->fChamp & 1) SpecType |= 0x02; if((pUnit->pMonsterData->fBoss & 1)&& (pUnit->pMonsterData->fNormal & 1)) SpecType |= 0x01; if(pUnit->pMonsterData->fNormal & 1) SpecType |= 0x00; *vp = INT_TO_JSVAL(SpecType); return JS_TRUE; } break; case UNIT_UNIQUEID: if(pUnit->dwType == UNIT_MONSTER && pUnit->pMonsterData->fBoss && pUnit->pMonsterData->fNormal) *vp = INT_TO_JSVAL(pUnit->pMonsterData->wUniqueNo); else *vp = INT_TO_JSVAL(-1); break; case ITEM_CODE: // replace with better method if found if(!(pUnit->dwType == UNIT_ITEM) && pUnit->pItemData) break; ItemTxt* pTxt; pTxt = D2COMMON_GetItemText(pUnit->dwTxtFileNo); if(!pTxt) { *vp = STRING_TO_JSVAL(JS_InternString(cx, "Unknown")); return JS_TRUE; } CHAR szCode[4]; memcpy(szCode, pTxt->szCode, 3); szCode[3] = 0x00; *vp = STRING_TO_JSVAL(JS_InternString(cx, szCode)); break; case ITEM_PREFIX: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) if (D2COMMON_GetItemMagicalMods(pUnit->pItemData->wPrefix)) *vp = STRING_TO_JSVAL(JS_InternString(cx, D2COMMON_GetItemMagicalMods(pUnit->pItemData->wPrefix))); break; case ITEM_SUFFIX: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) if (D2COMMON_GetItemMagicalMods(pUnit->pItemData->wSuffix)) *vp = STRING_TO_JSVAL(JS_InternString(cx, D2COMMON_GetItemMagicalMods(pUnit->pItemData->wSuffix))); break; case ITEM_PREFIXNUM: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) *vp = INT_TO_JSVAL(pUnit->pItemData->wPrefix); break; case ITEM_SUFFIXNUM: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) *vp = INT_TO_JSVAL(pUnit->pItemData->wSuffix); break; case ITEM_FNAME: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) { wchar_t wszfname[256] = L""; D2CLIENT_GetItemName(pUnit, wszfname, sizeof(wszfname)); if(wszfname) { char* tmp = UnicodeToAnsi(wszfname); *vp = STRING_TO_JSVAL(JS_InternString(cx, tmp)); delete[] tmp; } } break; case ITEM_QUALITY: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) *vp = INT_TO_JSVAL(pUnit->pItemData->dwQuality); break; case ITEM_NODE: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) *vp = INT_TO_JSVAL(pUnit->pItemData->NodePage); break; case ITEM_LOC: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) *vp = INT_TO_JSVAL(pUnit->pItemData->ItemLocation); break; case ITEM_SIZEX: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) { if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo)) break; *vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->xSize); } break; case ITEM_SIZEY: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) { if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo)) break; *vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->ySize); } break; case ITEM_Type: if(pUnit->dwType == UNIT_ITEM && pUnit->pItemData) { if(!D2COMMON_GetItemText(pUnit->dwTxtFileNo)) break; *vp = INT_TO_JSVAL(D2COMMON_GetItemText(pUnit->dwTxtFileNo)->nType); } break; case ITEM_DESC: { if(pUnit->dwType != UNIT_ITEM) break; wchar_t wBuffer[8192] = L""; D2CLIENT_GetItemDesc(pUnit, wBuffer); tmp = UnicodeToAnsi(wBuffer); *vp = STRING_TO_JSVAL(JS_InternString(cx, tmp)); delete[] tmp; } break; case UNIT_ITEMCOUNT: if(pUnit->pInventory) *vp = INT_TO_JSVAL(pUnit->pInventory->dwItemCount); break; case ITEM_BODYLOCATION: if(pUnit->dwType != UNIT_ITEM) break; if(pUnit->pItemData) *vp = INT_TO_JSVAL(pUnit->pItemData->BodyLocation); break; case UNIT_OWNER: *vp = INT_TO_JSVAL(pUnit->dwOwnerId); break; case UNIT_OWNERTYPE: *vp = INT_TO_JSVAL(pUnit->dwOwnerType); break; case ITEM_LEVEL: if(pUnit->dwType != UNIT_ITEM) break; if(pUnit->pItemData) *vp = INT_TO_JSVAL(pUnit->pItemData->dwItemLevel); break; case ITEM_LEVELREQ: if(pUnit->dwType != UNIT_ITEM) break; *vp = INT_TO_JSVAL(D2COMMON_GetItemLevelRequirement(pUnit, D2CLIENT_GetPlayerUnit())); break; case UNIT_DIRECTION: if(pUnit->pPath) *vp = INT_TO_JSVAL(pUnit->pPath->bDirection); break; case OBJECT_TYPE: if(pUnit->dwType == UNIT_OBJECT) if(pUnit->pObjectData) { pRoom = D2COMMON_GetRoomFromUnit(pUnit); if(pRoom && pRoom->pRoom2 && pRoom->pRoom2->pLevel && IsTownLevel(pRoom->pRoom2->pLevel->dwLevelNo)) *vp = INT_TO_JSVAL(pUnit->pObjectData->Type & 255); else *vp = INT_TO_JSVAL(pUnit->pObjectData->Type); } break; case ME_WSWITCH: *vp = INT_TO_JSVAL(*p_D2CLIENT_bWeapSwitch); break; default: break; } return JS_TRUE; }
JSObject * js_InitExceptionClasses(JSContext *cx, JSObject *obj) { int i; JSObject *protos[JSEXN_LIMIT]; /* Initialize the prototypes first. */ for (i = 0; exceptions[i].name != 0; i++) { JSAtom *atom; JSFunction *fun; JSString *nameString; int protoIndex = exceptions[i].protoIndex; /* Make the prototype for the current constructor name. */ protos[i] = js_NewObject(cx, &ExceptionClass, (protoIndex != JSEXN_NONE) ? protos[protoIndex] : NULL, obj); if (!protos[i]) return NULL; /* So exn_finalize knows whether to destroy private data. */ OBJ_SET_SLOT(cx, protos[i], JSSLOT_PRIVATE, JSVAL_VOID); atom = js_Atomize(cx, exceptions[i].name, strlen(exceptions[i].name), 0); if (!atom) return NULL; /* Make a constructor function for the current name. */ fun = js_DefineFunction(cx, obj, atom, exceptions[i].native, 3, 0); if (!fun) return NULL; /* Make this constructor make objects of class Exception. */ fun->clasp = &ExceptionClass; /* Make the prototype and constructor links. */ if (!js_SetClassPrototype(cx, fun->object, protos[i], JSPROP_READONLY | JSPROP_PERMANENT)) { return NULL; } /* proto bootstrap bit from JS_InitClass omitted. */ nameString = JS_NewStringCopyZ(cx, exceptions[i].name); if (!nameString) return NULL; /* Add the name property to the prototype. */ if (!JS_DefineProperty(cx, protos[i], js_name_str, STRING_TO_JSVAL(nameString), NULL, NULL, JSPROP_ENUMERATE)) { return NULL; } } /* * Add an empty message property. (To Exception.prototype only, * because this property will be the same for all the exception * protos.) */ if (!JS_DefineProperty(cx, protos[0], js_message_str, STRING_TO_JSVAL(cx->runtime->emptyString), NULL, NULL, JSPROP_ENUMERATE)) { return NULL; } if (!JS_DefineProperty(cx, protos[0], js_filename_str, STRING_TO_JSVAL(cx->runtime->emptyString), NULL, NULL, JSPROP_ENUMERATE)) { return NULL; } if (!JS_DefineProperty(cx, protos[0], js_lineno_str, INT_TO_JSVAL(0), NULL, NULL, JSPROP_ENUMERATE)) { return NULL; } /* * Add methods only to Exception.prototype, because ostensibly all * exception types delegate to that. */ if (!JS_DefineFunctions(cx, protos[0], exception_methods)) return NULL; return protos[0]; }
jsval charptr_to_jsval( JSContext *cx, const char *str) { JSString *ret_obj = JS_NewStringCopyZ(cx, str); return STRING_TO_JSVAL(ret_obj); }
/** * Define OS-specific constants. * * This function creates or uses JS object |OS.Constants| to store * all its constants. */ bool DefineOSFileConstants(JSContext *cx, JS::Handle<JSObject*> global) { MOZ_ASSERT(gInitialized); if (gPaths == nullptr) { // If an initialization error was ignored, we may end up with // |gInitialized == true| but |gPaths == nullptr|. We cannot // |MOZ_ASSERT| this, as this would kill precompile_cache.js, // so we simply return an error. JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_OPEN, "OSFileConstants", "initialization has failed"); return false; } JS::Rooted<JSObject*> objOS(cx); if (!(objOS = GetOrCreateObjectProperty(cx, global, "OS"))) { return false; } JS::Rooted<JSObject*> objConstants(cx); if (!(objConstants = GetOrCreateObjectProperty(cx, objOS, "Constants"))) { return false; } // Build OS.Constants.libc JS::Rooted<JSObject*> objLibc(cx); if (!(objLibc = GetOrCreateObjectProperty(cx, objConstants, "libc"))) { return false; } if (!dom::DefineConstants(cx, objLibc, gLibcProperties)) { return false; } #if defined(XP_WIN) // Build OS.Constants.Win JS::Rooted<JSObject*> objWin(cx); if (!(objWin = GetOrCreateObjectProperty(cx, objConstants, "Win"))) { return false; } if (!dom::DefineConstants(cx, objWin, gWinProperties)) { return false; } #endif // defined(XP_WIN) // Build OS.Constants.Sys JS::Rooted<JSObject*> objSys(cx); if (!(objSys = GetOrCreateObjectProperty(cx, objConstants, "Sys"))) { return false; } nsCOMPtr<nsIXULRuntime> runtime = do_GetService(XULRUNTIME_SERVICE_CONTRACTID); if (runtime) { nsAutoCString os; DebugOnly<nsresult> rv = runtime->GetOS(os); MOZ_ASSERT(NS_SUCCEEDED(rv)); JSString* strVersion = JS_NewStringCopyZ(cx, os.get()); if (!strVersion) { return false; } JS::Rooted<JS::Value> valVersion(cx, STRING_TO_JSVAL(strVersion)); if (!JS_SetProperty(cx, objSys, "Name", valVersion)) { return false; } } #if defined(DEBUG) JS::Rooted<JS::Value> valDebug(cx, JSVAL_TRUE); if (!JS_SetProperty(cx, objSys, "DEBUG", valDebug)) { return false; } #endif // Build OS.Constants.Path JS::Rooted<JSObject*> objPath(cx); if (!(objPath = GetOrCreateObjectProperty(cx, objConstants, "Path"))) { return false; } // Locate libxul { nsAutoString xulPath(gPaths->libDir); xulPath.Append(PR_GetDirectorySeparator()); #if defined(XP_MACOSX) // Under MacOS X, for some reason, libxul is called simply "XUL" xulPath.Append(NS_LITERAL_STRING("XUL")); #else // On other platforms, libxul is a library "xul" with regular // library prefix/suffix xulPath.Append(NS_LITERAL_STRING(DLL_PREFIX)); xulPath.Append(NS_LITERAL_STRING("xul")); xulPath.Append(NS_LITERAL_STRING(DLL_SUFFIX)); #endif // defined(XP_MACOSX) if (!SetStringProperty(cx, objPath, "libxul", xulPath)) { return false; } } if (!SetStringProperty(cx, objPath, "libDir", gPaths->libDir)) { return false; } if (!SetStringProperty(cx, objPath, "tmpDir", gPaths->tmpDir)) { return false; } // Configure profileDir only if it is available at this stage if (!gPaths->profileDir.IsVoid() && !SetStringProperty(cx, objPath, "profileDir", gPaths->profileDir)) { return false; } // Configure localProfileDir only if it is available at this stage if (!gPaths->localProfileDir.IsVoid() && !SetStringProperty(cx, objPath, "localProfileDir", gPaths->localProfileDir)) { return false; } if (!SetStringProperty(cx, objPath, "homeDir", gPaths->homeDir)) { return false; } if (!SetStringProperty(cx, objPath, "desktopDir", gPaths->desktopDir)) { return false; } #if defined(XP_WIN) if (!SetStringProperty(cx, objPath, "winAppDataDir", gPaths->winAppDataDir)) { return false; } if (!SetStringProperty(cx, objPath, "winStartMenuProgsDir", gPaths->winStartMenuProgsDir)) { return false; } #endif // defined(XP_WIN) #if defined(XP_MACOSX) if (!SetStringProperty(cx, objPath, "macUserLibDir", gPaths->macUserLibDir)) { return false; } if (!SetStringProperty(cx, objPath, "macLocalApplicationsDir", gPaths->macLocalApplicationsDir)) { return false; } #endif // defined(XP_MACOSX) return true; }
static bool JS_SET_STDSTRING_RVAL(JSContext *cx, jsval *vp, const std::string &result) { JSString *jsResult = JS_NewStringCopyZ(cx, result.c_str()); JS_SET_RVAL(cx, vp, STRING_TO_JSVAL(jsResult)); return true; }