コード例 #1
0
static size_t file_callback(void *ptr, size_t size, size_t nmemb, void *data)
{
	register unsigned int realsize = (unsigned int) (size * nmemb);
	struct curl_obj *co = data;
	uintN argc = 0;
	jsval argv[4];


	if (!co) {
		return 0;
	}
	if (co->function) {
		char *ret;
		argv[argc++] = STRING_TO_JSVAL(JS_NewStringCopyZ(co->cx, (char *) ptr));
		if (co->user_data) {
			argv[argc++] = OBJECT_TO_JSVAL(co->user_data);
		}
		JS_ResumeRequest(co->cx, co->saveDepth);
		JS_CallFunction(co->cx, co->obj, co->function, argc, argv, &co->ret);
		co->saveDepth = JS_SuspendRequest(co->cx);

		if ((ret = JS_GetStringBytes(JS_ValueToString(co->cx, co->ret)))) {
			if (!strcmp(ret, "true") || !strcmp(ret, "undefined")) {
				return realsize;
			} else {
				return 0;
			}
		}
	}

	return realsize;
}
コード例 #2
0
ファイル: ScriptInterface.cpp プロジェクト: Rektosauros/0ad
bool ScriptInterface::LoadScript(const VfsPath& filename, const std::string& code)
{

	JSAutoRequest rq(m->m_cx);
	JS::RootedObject global(m->m_cx, m->m_glob);
	utf16string codeUtf16(code.begin(), code.end());
	uint lineNo = 1;
	// CompileOptions does not copy the contents of the filename string pointer.
	// Passing a temporary string there will cause undefined behaviour, so we create a separate string to avoid the temporary.
	std::string filenameStr(utf8_from_wstring(filename.string()));

	JS::CompileOptions options(m->m_cx);
	options.setFileAndLine(filenameStr.c_str(), lineNo);
	options.setCompileAndGo(true);

	JS::RootedFunction func(m->m_cx,
	JS_CompileUCFunction(m->m_cx, global, NULL, 0, NULL,
			reinterpret_cast<const jschar*> (codeUtf16.c_str()), (uint)(codeUtf16.length()), options)
	);
	if (!func)
		return false;

	JS::RootedValue rval(m->m_cx);
	return JS_CallFunction(m->m_cx, JS::NullPtr(), func, JS::HandleValueArray::empty(), &rval);
}
コード例 #3
0
//---------------------------------------------------------------------------
inline JSBool ejs_throw_error(JSContext *cx, JSObject *obj, const char *msg) {
    JSString *jsstr;

    // if we get errors during error reporting we report those
    if (((jsstr = JS_NewStringCopyZ(cx, msg))) &&
        (JS_AddNamedRoot(cx, &jsstr, "jsstr"))) {
        jsval dummy;
        // We can't use JS_EvaluateScript since the stack would be wrong
        JSFunction *func;
        JSObject   *fobj;
        const char *fbody      = "throw new Error(msg);";
        const char *argnames[] = { "msg" };
        if ((func = JS_CompileFunction(cx, obj, NULL,
                                       1, argnames,
                                       fbody, strlen(fbody),
                                       NULL, 0))) {
            // root function
            if (((fobj = JS_GetFunctionObject(func))) &&
                (JS_AddNamedRoot(cx, &fobj, "fobj"))) {
                jsval args[] = { STRING_TO_JSVAL(jsstr) };
                JS_CallFunction(cx, obj, func, 1, args, &dummy);
                JS_RemoveRoot(cx, &fobj);
            }
        }
        JS_RemoveRoot(cx, &jsstr);
    }

    return JS_FALSE;
}//---------------------------------------------------------------------------
コード例 #4
0
ファイル: jsInput.cpp プロジェクト: boundarydevices/bdScript
void jsInputPoll_t::onData( struct input_event const &event )
{
	JSFunction *function = JS_ValueToFunction( execContext_, handlerCode_ );
	JSObject   *obj = JSVAL_TO_OBJECT(handlerObj_);
	if( function && obj ){
		jsval args[3] = {
                        INT_TO_JSVAL( event.type )
		,	INT_TO_JSVAL( event.code )
		,	INT_TO_JSVAL( event.value )
		};
		jsval rval ;
                JS_CallFunction(execContext_, obj, function, 3, args, &rval );
	}
}
コード例 #5
0
ファイル: test.cpp プロジェクト: obastemur/node-apphost
void sampleMethod(JS_Value *results, int argc) {
  for (int i = 0; i < argc; i++) {
    std::string str;
    ConvertResult(results[i], str);
    if (compare_base[i] != str.c_str()[0]) {
      flush_console("FAIL! Item(%d) : %s \n", i, str.c_str());
      exit(-1);
    }
  }

  JS_Value out;
  JS_CallFunction(results + 9, (results + 3), 2, &out);

  assert(JS_GetDataLength(&out) == 11 &&
         "Expected return value was 'test{\"a\":3}");
  JS_Free(&out);
  assert(out.data_ == NULL && out.size_ == 0 && "JS_FreeResultData leaks?");
}
コード例 #6
0
bool ScriptInterface::LoadScript(const VfsPath& filename, const std::string& code)
{
	// Compile the code in strict mode, to encourage better coding practices and
	// to possibly help SpiderMonkey with optimisations
	std::wstring codeStrict = L"\"use strict\";\n" + wstring_from_utf8(code);
	utf16string codeUtf16(codeStrict.begin(), codeStrict.end());
	uintN lineNo = 0; // put the automatic 'use strict' on line 0, so the real code starts at line 1

	JSFunction* func = JS_CompileUCFunction(m->m_cx, NULL, NULL, 0, NULL,
			reinterpret_cast<const jschar*> (codeUtf16.c_str()), (uintN)(codeUtf16.length()),
			utf8_from_wstring(filename.string()).c_str(), lineNo);

	if (!func)
		return false;

	jsval scriptRval;
	JSBool ok = JS_CallFunction(m->m_cx, NULL, func, 0, NULL, &scriptRval);

	return ok ? true : false;
}
コード例 #7
0
ファイル: spidermonkey.c プロジェクト: Efreak/elinks
int
spidermonkey_eval_boolback(struct ecmascript_interpreter *interpreter,
			   struct string *code)
{
	JSContext *ctx;
	JSFunction *fun;
	jsval rval;
	int ret;

	assert(interpreter);
	if (!js_module_init_ok) return 0;
	ctx = interpreter->backend_data;
	interpreter->ret = NULL;
	fun = JS_CompileFunction(ctx, NULL, "", 0, NULL, code->source,
				 code->length, "", 0);
	if (!fun)
		return -1;

#if defined(CONFIG_ECMASCRIPT_SMJS_HEARTBEAT)
	interpreter->heartbeat = add_heartbeat(interpreter);
#elif defined(HAVE_JS_SETBRANCHCALLBACK)
	setup_safeguard(interpreter, ctx);
#endif
	ret = JS_CallFunction(ctx, NULL, fun, 0, NULL, &rval);
#if defined(CONFIG_ECMASCRIPT_SMJS_HEARTBEAT)
	done_heartbeat(interpreter->heartbeat);
#endif
	if (ret == 2) { /* onClick="history.back()" */
		return 0;
	}
	if (ret == JS_FALSE) {
		return -1;
	}
	if (JSVAL_IS_VOID(rval)) {
		/* Undefined value. */
		return -1;
	}

	return jsval_to_boolean(ctx, &rval);
}
コード例 #8
0
ファイル: Thread.c プロジェクト: robn/amber
static void *thread_start(void *arg) {
    thread_stuff ts = (thread_stuff) arg;
    JSContext *cx;
    jsval argv[1], rval;
    uintN argc;

    cx = JS_NewContext(ts->rt, 8192);
    JS_SetContextPrivate(cx, ts);

    if(ts->arg != JSVAL_VOID) {
        argv[0] = ts->arg;
        argc = 1;
    } else
        argc = 0;

    ts->state = THREAD_RUN;
    JS_CallFunction(cx, ts->amber, ts->fun, argc, argv, &rval);
    ts->state = THREAD_DONE;

    JS_DestroyContext(cx);

    return NULL;
}
コード例 #9
0
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;
}
コード例 #10
0
ファイル: task.cpp プロジェクト: BenitoJedai/jslibs
bool
TheTask(JSContext *cx, TaskPrivate *pv) {

	bool ok;
	jsval argv[3] = { JSVAL_NULL }; // argv[0] is rval and code

	JSObject *globalObj;
	globalObj = JL_GetGlobal(cx);
	ASSERT( globalObj );

	// no need to mutex this because this and the constructor are the only places that access pv->serializedCode.
	ok = UnserializeJsval(cx, pv->serializedCode, &argv[0]);
	SerializerFree(&pv->serializedCode);
	JL_CHK( ok );

	JSFunction *fun;
	fun = JS_ValueToFunction(cx, argv[0]);
	JL_CHK( fun );
/*
	JSObject *funObj;
	funObj = JS_GetFunctionObject(fun);
	ASSERT( funObj );
	// JL_CHK( JS_SetParent(cx, funObj, globalObj) ); // re-scope the function
	ASSERT( JS_GetParent(funObj) );
*/

	size_t index;
	index = 0;

	for (;;) {

		JL_CHK( JLSemaphoreAcquire(pv->requestSem) ); // -1 // wait for a request

		JLMutexAcquire(pv->mutex); // --
		if ( pv->end ) { // manage the end of the thread

			JLMutexRelease(pv->mutex); // ++
			break;
		}

		SerializedData *serializedRequest;
		serializedRequest = (SerializedData*)QueueShift(&pv->requestList);
		pv->pendingRequestCount--;
		pv->processingRequestCount++; // = 1;
		JLMutexRelease(pv->mutex); // ++

		ASSERT( serializedRequest );
		ok = UnserializeJsval(cx, serializedRequest, &argv[1]);
		SerializerFree(&serializedRequest);
		JL_CHK( ok );

		argv[2] = INT_TO_JSVAL(index++);

		ok = JS_CallFunction(cx, globalObj, fun, COUNTOF(argv)-1, argv+1, argv);
		if ( ok ) {

			SerializedData *serializedResponse;
			SerializerCreate(&serializedResponse);
			JL_CHK( SerializeJsval(cx, serializedResponse, &argv[0]) );

			JLMutexAcquire(pv->mutex); // --
			QueuePush(&pv->responseList, serializedResponse);
			pv->pendingResponseCount++;
			pv->processingRequestCount--;
			JLMutexRelease(pv->mutex); // ++
		} else {

			jsval ex;
			if ( JL_IsExceptionPending(cx) ) { // manageable error

				ok = JS_GetPendingException(cx, &ex);
				JS_ClearPendingException(cx);
				JL_CHK( ok );
			} else {

				ex = JSVAL_VOID; // unknown exception
			}

			SerializedData *serializedException;
			SerializerCreate(&serializedException);
			JL_CHK( SerializeJsval(cx, serializedException, &ex) );

			JLMutexAcquire(pv->mutex); // --
			QueuePush(&pv->exceptionList, serializedException);
			QueuePush(&pv->responseList, NULL); // signals an exception
			pv->pendingResponseCount++;
			pv->processingRequestCount--;
			JLMutexRelease(pv->mutex); // ++
		}

		ASSERT( pv->processingRequestCount == 0 );

		JLSemaphoreRelease(pv->responseSem); // +1 // signals a response
		JLEventTrigger(pv->responseEvent);
	}

	return true;
	JL_BAD;
}