Esempio n. 1
0
void
test_AsciiValue_length()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "toString";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  do_check_eq(str->Length(), TEST_LENGTH);
  String::AsciiValue k(str);
  do_check_eq(k.length(), TEST_LENGTH);
  context.Dispose();
}
Esempio n. 2
0
void
test_Constructor()
{
  HandleScope handle_scope;
  Handle<ObjectTemplate> templ = ObjectTemplate::New();
  Handle<FunctionTemplate> fnT = v8::FunctionTemplate::New(AddOne);
  templ->Set("AddOne", fnT);

  Persistent<Context> context = Context::New(NULL, templ);
  Handle<Script> script = Script::New(String::New("new AddOne(4);"));

  Context::Scope scope(context);
  script->Run();
  context.Dispose();
}
Esempio n. 3
0
void
test_Utf8Value_length()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "this is a UTF-8 test!  This is pi: π";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  do_check_eq(str->Length(), TEST_LENGTH - 1);
  String::Utf8Value k(str);
  do_check_eq(k.length(), TEST_LENGTH);
  do_check_true(0 == strcmp(TEST_STRING, *k));
  context.Dispose();
}
Esempio n. 4
0
void
test_PartialWriteAscii() {
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "toString";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  do_check_eq(str->Length(), TEST_LENGTH);
  char buffer[] = "hag";
  int written = str->WriteAscii(buffer, 0, 1);
  do_check_eq(strlen(buffer), 3);
  do_check_eq(strcmp(buffer, "tag"), 0);
  context.Dispose();
}
Esempio n. 5
0
  void DisposeOpenCLObject (Persistent<Value> value, void* release) {
    if (release && value->IsObject()) {
      Local<Object> object = value->ToObject();
      if (object->InternalFieldCount()) {
        void *ptr = object->GetPointerFromInternalField(0);

        int32_t (CALL *clRelease) (void* smth);
        *(void**) &clRelease = release;

        clRelease(ptr); // Returned value is omitted. Check when debugging.
      }
    }

    value.Dispose();
    value.Clear();
  }
// Load up the JS engine
void initJsEngine(){
    char path[1024];
    uint32_t size = sizeof(path);
    if (_NSGetExecutablePath(path, &size) != 0)
       printf("buffer too small; need size %u\n", size);
    
    string script_path;
    char *pch, *next_pch;
    pch = strtok(path, "/");
    next_pch = strtok(NULL, "/");
    //Rebuild the path, ommitting the last part (the exe name)
    while (next_pch != NULL) {
        script_path.append( "/" );
        script_path.append( pch );
        pch = next_pch;
        next_pch = strtok(NULL, "/");
    }
    script_path.append("/script.js");
    ifstream infile;
    
    infile.open (script_path.c_str(), ifstream::in);
    string file = "";
    while (infile.good()){
        file += (char) infile.get();
    }
    //Get rid of the of character
    file[file.length() - 1] = ' ';
    setJsFile( file.c_str() );
    infile.close();

    // Lock this v8 instance to this thread?
    Locker locker;
    HandleScope handle_scope;
    Persistent<Context> context = Context::New();
    Context::Scope context_scope(context);
    

    context->Global()->Set(String::New("System"), getSystemTemplate()->NewInstance() ); 
    context->Global()->Set(String::New("Player"), getPlayerTemplate()->NewInstance() );
    context->Global()->Set(String::New("Games"),  getGamesTemplate()->NewInstance() );
    
    Handle<String> source = String::New(js_file);
    Handle<Script> script = Script::Compile(source);
    Handle<Value> result = script->Run();
    context.Dispose();
}
Esempio n. 7
0
void
test_AsciiValue_operators()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "ascii string value";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  do_check_eq(str->Length(), TEST_LENGTH);
  String::AsciiValue asciiString(str);
  const char* one = *asciiString;
  char* two = *asciiString;
  do_check_true(0 == strcmp(TEST_STRING, one));
  do_check_true(0 == strcmp(TEST_STRING, two));
  context.Dispose();
}
Esempio n. 8
0
void
test_Utf8Length()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "this is a UTF-8 test!  This is pi: π";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  do_check_eq(str->Utf8Length(), TEST_LENGTH);

  // Now, make a string with an embedded NULL.
  TEST_STRING[8] = '\0';
  str = String::New(TEST_STRING, TEST_LENGTH);
  do_check_eq(str->Utf8Length(), TEST_LENGTH);
  context.Dispose();
}
Esempio n. 9
0
   bool ScriptSystem::RemoveFromComponentMap(dtEntity::ComponentType ct, dtEntity::EntityId eid)
   {
      ComponentMap::iterator it = mComponentMap.find(std::make_pair(ct, eid));
      if(it == mComponentMap.end())
      {
         return false;
      }
      HandleScope scope;
      Persistent<Object> obj = it->second;
      assert(!obj.IsEmpty() && obj->IsObject());
      // invalidate component wrapper
      obj->SetInternalField(0, External::New(0));
      obj.Dispose();
      mComponentMap.erase(it);
      V8::AdjustAmountOfExternalAllocatedMemory(-(int)sizeof(dtEntity::Component));
      return true;

   }
Esempio n. 10
0
void
test_obj_getprop()
{
  HandleScope handle_scope;

  Persistent<Context> context = Context::New();

  Context::Scope context_scope(context);

  Handle<Object> obj = Object::New();

  Handle<Value> k = String::New("toString");
  Handle<Value> v = obj->Get(k);

  do_check_true(v->IsFunction());

  context.Dispose();
}
Esempio n. 11
0
void
test_Name()
{
  HandleScope handle_scope;
  Handle<ObjectTemplate> templ = ObjectTemplate::New();
  Handle<FunctionTemplate> fnT = v8::FunctionTemplate::New(AddOne);
  templ->Set("AddOne", fnT);
  fnT->SetClassName(String::NewSymbol("AddOne"));

  Persistent<Context> context = Context::New(NULL, templ);
  Handle<Script> script = Script::New(String::New("AddOne.name;"));

  Context::Scope scope(context);
  Handle<Value> v = script->Run();
  do_check_true(!v.IsEmpty());
  Handle<String> s = v->ToString();
  do_check_eq(s, String::NewSymbol("AddOne"));
  context.Dispose();
}
Esempio n. 12
0
File: main.cpp Progetto: simonask/js
int main (int argc, char const *argv[])
{
	HandleScope handle_scope;
	
	Handle<ObjectTemplate> global = ObjectTemplate::New();
	
	global->Set(String::New("load"), FunctionTemplate::New(js_load));
	Persistent<Context> context = Context::New(NULL, global);
	Context::Scope context_scope(context);
	Handle<Object> global_obj(context->Global());
	IO::initialize(global_obj);
	Process::initialize(global_obj);
	
	Handle<Value> result = LoadScript(argv[1]);
	
	context.Dispose();
	
	return 0;
}
Esempio n. 13
0
void
test_nested()
{
  HandleScope handle_scope;
  TryCatch trycatch;

  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  Handle<String> source = String::New("oasdohuasdnlqwoi");
  Handle<Script> script = Script::Compile(source);
  {
    TryCatch innerCatcher;
    Handle<Value> result = script->Run();

    do_check_true(innerCatcher.HasCaught());
  }
  context.Dispose();

  do_check_true(!trycatch.HasCaught());
}
Esempio n. 14
0
Handle<Value> HashTable::Remove(const Arguments& args) {
  HandleScope scope;

  HashTable *obj = ObjectWrap::Unwrap<HashTable>(args.This());

  Local<Value> key = Local<Value>(args[0]);
  String::AsciiValue keyStr(key);

  auto itr = obj->map.find(std::string(*keyStr));

  if(itr == obj->map.end()) {
    return scope.Close(Local<Value>()); //do nothing and return undefined
  } 

  Persistent<Value> value = itr->second;
  value.Dispose();

  obj->map.erase(itr);

  return scope.Close(Local<Value>());
}
Esempio n. 15
0
void
test_V8DocExample()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
  t->Set("func_property", v8::Number::New(1));

  v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
  proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
  proto_t->Set("proto_const", v8::Number::New(2));

  v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
  instance_t->SetAccessor(String::New("instance_accessor"), InstanceAccessorCallback);
  instance_t->Set("instance_property", Number::New(3));

  v8::Local<v8::Function> function = t->GetFunction();
  v8::Local<v8::Object> instance = function->NewInstance();
  // TODO: test that we created the objects we were supposed to
  context.Dispose();
}
Esempio n. 16
0
void
test_WriteUtf8()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "this is a UTF-8 test!  This is pi: π";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  char* buf = new char[TEST_LENGTH * 2];
  // Fill the buffer with 'a' to ensure there are no NULLs to start with.
  fill_string(buf, 'a', TEST_LENGTH * 2);
  int charsWritten;
  int copied = str->WriteUtf8(buf, TEST_LENGTH * 2, &charsWritten);
  do_check_eq(copied, TEST_LENGTH + 1);
  // π is 2 bytes, so strlen (TEST_LENGTH) returns 1 larger than charsWritten
  do_check_eq(charsWritten, TEST_LENGTH - 1);
  do_check_eq(strlen(buf), TEST_LENGTH);

  delete[] buf;
  context.Dispose();
}
Esempio n. 17
0
void
test_Write()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "this is a UTF-8 test!  This is pi: π";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  char* buf = new char[TEST_LENGTH * 2];

  for (int start = 0; start < TEST_LENGTH; start++) {
    // Fill the buffer with 'a' to ensure there are no NULLs to start with.
    fill_string(buf, 'a', TEST_LENGTH * 2);
    int copied = str->WriteAscii(buf, start, TEST_LENGTH * 2);
    do_check_eq(copied, TEST_LENGTH - start);
    do_check_eq(strlen(buf), TEST_LENGTH - start);
  }

  delete[] buf;
  context.Dispose();
}
Esempio n. 18
0
char* js_eval(UDF_INIT *initid, UDF_ARGS* args, char *result_buf, unsigned long *res_length, char *null_value, char *error) {

    HandleScope handle_scope;

    Persistent<Context> context = Context::New();
    Context::Scope context_scope(context);

    //fprintf(stderr, "[mylog] input: %s\n", (char*)(args->args[0]));

    Handle<String> source = String::New((char*)(args->args[0]));
    Handle<Script> script = Script::Compile(source);

    TryCatch trycatch;
    Handle<Value> result = script->Run();

    if ( result.IsEmpty() ) {
        Handle<Value> exception = trycatch.Exception();
        String::AsciiValue exception_str(exception);

        //fprintf(stderr, "[mylog] exception: %s\n", *exception_str);

        strcpy(result_buf, *exception_str);
        *res_length = strlen(*exception_str);
    }
    else {
        String::AsciiValue ascii(result);

        //fprintf(stderr, "[mylog] output: %s\n", *ascii);

        strcpy(result_buf, *ascii);
        *res_length = strlen(*ascii);
    }

    context.Dispose();

    return result_buf;
}
Esempio n. 19
0
char* ReadLineEditor::CompletionGenerator(const char* text, int state) {
  static unsigned current_index;
  static Persistent<Array> current_completions;
  if (state == 0) {
    i::SmartPointer<char> full_text(i::StrNDup(rl_line_buffer, rl_point));
    HandleScope scope;
    Handle<Array> completions =
      Shell::GetCompletions(String::New(text), String::New(*full_text));
    current_completions = Persistent<Array>::New(completions);
    current_index = 0;
  }
  if (current_index < current_completions->Length()) {
    HandleScope scope;
    Handle<Integer> index = Integer::New(current_index);
    Handle<Value> str_obj = current_completions->Get(index);
    current_index++;
    String::Utf8Value str(str_obj);
    return strdup(*str);
  } else {
    current_completions.Dispose();
    current_completions.Clear();
    return NULL;
  }
}
Esempio n. 20
0
void
test_Length()
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  char TEST_STRING[] = "this is a test";
  int TEST_LENGTH = strlen(TEST_STRING);
  Handle<String> str = String::New(TEST_STRING);
  do_check_eq(str->Length(), TEST_LENGTH);

  // Now, make a string with an embedded NULL.
  TEST_STRING[8] = '\0';
  str = String::New(TEST_STRING, TEST_LENGTH);
  do_check_eq(str->Length(), TEST_LENGTH);

  // Finally, make sure that we end up calling strlen if no length is passed.
  str = String::New(TEST_STRING);

  int strlength = strlen(TEST_STRING);
  do_check_eq(str->Length(), strlength);
  context.Dispose();
}
Esempio n. 21
0
void
test_obj_tmplexn() {
  HandleScope scope;

  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  Handle<ObjectTemplate> tmpl = ObjectTemplate::New();
  tmpl->SetNamedPropertyHandler(NamedGetterThrows, NamedSetterThrows, 0, NamedDeleterThrows);
  tmpl->SetIndexedPropertyHandler(IndexedGetterThrows, IndexedSetterThrows, 0, IndexedDeleterThrows);
  Handle<Object> obj = tmpl->NewInstance();
  Local<Object> global = context->Global();
  global->Set(String::New("testobj"), obj);

  Handle<String> source = String::New("var n = 0;"
                                      "try { testobj.myprop; } catch (e) { n += e; };"
                                      "try { testobj.myprop = (n+9); } catch (e) { n += e; }"
                                      "try { delete testobj.myprop; } catch (e) { n += e; };"
                                      "try { testobj[4]; } catch (e) { n += e; };"
                                      "try { testobj[5] = (n+9); } catch (e) { n += e; }"
                                      "try { delete testobj[6]; } catch (e) { n += e; }; n");

  // Compile the source code.
  Handle<Script> script = Script::Compile(source);

  TryCatch trycatch;
  // Run the script to get the result.
  Handle<Value> result = script->Run();

  do_check_false(result.IsEmpty());
  do_check_true(result->IsInt32());
  do_check_false(trycatch.HasCaught());
  JSInt32 i = result->Int32Value();
  do_check_eq(i, 21);
  context.Dispose();
}
Esempio n. 22
0
void Java_me_sarim_myfirstapp_MainActivity_killjs( JNIEnv* env,jobject thiz){
	
	Context::Scope context_scope(context);
	context.Dispose();
	
}
Esempio n. 23
0
void Java_com_omicronlab_avrokeyboard_PhoneticIM_killjs( JNIEnv* env,jobject thiz){
	
	Context::Scope context_scope(context);
	context.Dispose();
	
}
Esempio n. 24
0
/* static */
void V8Runtime::collectWeakRef(Persistent<Value> ref, void *parameter)
{
	jobject v8Object = (jobject) parameter;
	ref.Dispose();
	JNIScope::getEnv()->DeleteGlobalRef(v8Object);
}
Esempio n. 25
0
JNIEXPORT void JNICALL Java_org_appcelerator_kroll_runtime_v8_V8Runtime_nativeDispose(JNIEnv *env, jobject runtime)
{
	JNIScope jniScope(env);

	// We use a new scope here so any new handles we create
	// while disposing are cleaned up before our global context
	// is disposed below.
	{
		HandleScope scope;

		// Any module that has been require()'d or opened via Window URL
		// will be cleaned up here. We setup the initial "moduleContexts"
		// Array and expose it on kroll above in nativeInit, and
		// module.js will insert module contexts into this array in
		// Module.prototype._runScript
		uint32_t length = V8Runtime::moduleContexts->Length();
		for (uint32_t i = 0; i < length; ++i) {
			Handle<Value> moduleContext = V8Runtime::moduleContexts->Get(i);

			// WrappedContext is simply a C++ wrapper for the V8 Context object,
			// and is used to expose the Context to javascript. See ScriptsModule for
			// implementation details
			WrappedContext *wrappedContext = NativeObject::Unwrap<WrappedContext>(moduleContext->ToObject());

			// Detach each context's global object, and dispose the context
			wrappedContext->GetV8Context()->DetachGlobal();
			wrappedContext->GetV8Context().Dispose();
		}

		// KrollBindings
		KrollBindings::dispose();
		EventEmitter::dispose();

		V8Runtime::moduleContexts.Dispose();
		V8Runtime::moduleContexts = Persistent<Array>();

		V8Runtime::globalContext->DetachGlobal();

	}

	// Dispose of each class' static cache / resources

	V8Util::dispose();
	ProxyFactory::dispose();

	moduleObject.Dispose();
	moduleObject = Persistent<Object>();

	runModuleFunction.Dispose();
	runModuleFunction = Persistent<Function>();

	V8Runtime::krollGlobalObject.Dispose();

	V8Runtime::globalContext->Exit();
	V8Runtime::globalContext.Dispose();

	// Removes the retained global reference to the V8Runtime 
	env->DeleteGlobalRef(V8Runtime::javaInstance);

	V8Runtime::javaInstance = NULL;
}
Esempio n. 26
0
Handle<Value> WrappedScript::EvalMachine(const Arguments& args)
{
	HandleScope scope;

	if (input_flag == compileCode && args.Length() < 1) {
		return ThrowException(Exception::TypeError(String::New("needs at least 'code' argument.")));
	}

	const int sandbox_index = input_flag == compileCode ? 1 : 0;
	if (context_flag == userContext && args.Length() < (sandbox_index + 1)) {
		return ThrowException(Exception::TypeError(String::New("needs a 'context' argument.")));
	}

	Local<String> code;
	if (input_flag == compileCode) code = args[0]->ToString();

	Local<Object> sandbox;
	if (context_flag == newContext) {
		sandbox = args[sandbox_index]->IsObject() ? args[sandbox_index]->ToObject() : Object::New();
	} else if (context_flag == userContext) {
		sandbox = args[sandbox_index]->ToObject();
	}

	int filename_offset = 1;
	if (context_flag == thisContext) {
		filename_offset = 0;
	}

	const int filename_index = sandbox_index + filename_offset;
	Local<String> filename =
		args.Length() > filename_index ? args[filename_index]->ToString() : String::New("evalmachine.<anonymous>");

	const int display_error_index = args.Length() - 1;
	bool display_error = false;
	if (args.Length() > display_error_index && args[display_error_index]->IsBoolean()
		&& args[display_error_index]->BooleanValue() == true) {
		display_error = true;
	}

	Persistent<Context> context;

	Local<Array> keys;
	unsigned int i;
	WrappedContext *nContext = NULL;
	Local<Object> contextArg;

	if (context_flag == newContext) {
		// Create the new context
		context = Context::New();

	} else if (context_flag == userContext) {
		// Use the passed in context
		contextArg = args[sandbox_index]->ToObject();
		nContext = WrappedContext::Unwrap(contextArg);
		context = nContext->GetV8Context();
	}

	// New and user context share code. DRY it up.
	if (context_flag == userContext || context_flag == newContext) {
		// Enter the context
		context->Enter();
	}

	Handle<Value> result;
	Handle<Script> script;

	if (input_flag == compileCode) {
		// well, here WrappedScript::New would suffice in all cases, but maybe
		// Compile has a little better performance where possible
		script = output_flag == returnResult ? Script::Compile(code, filename) : Script::New(code, filename);
		if (script.IsEmpty()) {
			// Hack because I can't get a proper stacktrace on SyntaxError
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		} else if (n_script->script_.IsEmpty()) {
			return ThrowException(Exception::Error(String::New("'this' must be a result of previous "
				"new Script(code) call.")));
		}

		script = n_script->script_;
	}

	if (output_flag == returnResult) {
		result = script->Run();
		if (result.IsEmpty()) {
			if (context_flag == newContext) {
				context->DetachGlobal();
				context->Exit();
				context.Dispose();
			}
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		}
		n_script->script_ = Persistent<Script>::New(script);
		result = args.This();
	}

	if (context_flag == newContext) {
		// Clean up, clean up, everybody everywhere!
		context->DetachGlobal();
		context->Exit();
		context.Dispose();
	} else if (context_flag == userContext) {
		// Exit the passed in context.
		context->Exit();
	}

	if (result->IsObject()) {
		Local<Context> creation = result->ToObject()->CreationContext();
	}

	return result == args.This() ? result : scope.Close(result);
}
Esempio n. 27
0
Handle<Value> WrappedScript::EvalMachine(const Arguments& args)
{
	HandleScope scope;

	if (input_flag == compileCode && args.Length() < 1) {
		return ThrowException(Exception::TypeError(String::New("needs at least 'code' argument.")));
	}

	const int sandbox_index = input_flag == compileCode ? 1 : 0;
	if (context_flag == userContext && args.Length() < (sandbox_index + 1)) {
		return ThrowException(Exception::TypeError(String::New("needs a 'context' argument.")));
	}

	Local<String> code;
	if (input_flag == compileCode) code = args[0]->ToString();

	Local<Object> sandbox;
	if (context_flag == newContext) {
		sandbox = args[sandbox_index]->IsObject() ? args[sandbox_index]->ToObject() : Object::New();
	} else if (context_flag == userContext) {
		sandbox = args[sandbox_index]->ToObject();
	}

	const int filename_index = sandbox_index + (context_flag == newContext ? 1 : 0);
	Local<String> filename =
			args.Length() > filename_index ? args[filename_index]->ToString() : String::New("evalmachine.<anonymous>");

	const int display_error_index = args.Length() - 1;
	bool display_error = false;
	if (args.Length() > display_error_index && args[display_error_index]->IsBoolean()
		&& args[display_error_index]->BooleanValue() == true) {
		display_error = true;
	}

	Persistent<Context> context;

	Local<Array> keys;
	unsigned int i;
	WrappedContext *nContext = NULL;
	Local<Object> contextArg;

	if (context_flag == newContext) {
		// Create the new context
		context = Context::New();

	} else if (context_flag == userContext) {
		// Use the passed in context
		contextArg = args[sandbox_index]->ToObject();
		nContext = NativeObject::Unwrap<WrappedContext>(contextArg);
		context = nContext->GetV8Context();
	}

	// New and user context share code. DRY it up.
	if (context_flag == userContext || context_flag == newContext) {
		// Enter the context
		context->Enter();

		// Call the initCallback, if it exists
		if (nContext) {
			Persistent<Function> initCallback = nContext->GetInitCallback();

			if (!initCallback.IsEmpty()) {
				Handle<Value> callbackArgs[] = { contextArg, context->Global() };
				initCallback->Call(contextArg, 2, callbackArgs);
			}
		}

		// Copy everything from the passed in sandbox (either the persistent
		// context for runInContext(), or the sandbox arg to runInNewContext()).
		keys = sandbox->GetPropertyNames();

		for (i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = sandbox->Get(key);
			if (value == sandbox) {
				value = context->Global();
			}
			context->Global()->Set(key, value);
		}
	}

	Handle<Value> result;
	Handle<Script> script;

	if (input_flag == compileCode) {
		// well, here WrappedScript::New would suffice in all cases, but maybe
		// Compile has a little better performance where possible
		script = output_flag == returnResult ? Script::Compile(code, filename) : Script::New(code, filename);
		if (script.IsEmpty()) {
			// Hack because I can't get a proper stacktrace on SyntaxError
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		} else if (n_script->script_.IsEmpty()) {
			return ThrowException(Exception::Error(String::New("'this' must be a result of previous "
				"new Script(code) call.")));
		}

		script = n_script->script_;
	}

	if (output_flag == returnResult) {
		result = script->Run();
		if (result.IsEmpty()) {
			if (context_flag == newContext) {
				context->DetachGlobal();
				context->Exit();
				context.Dispose();
			}
			return Undefined();
		}
	} else {
		WrappedScript *n_script = NativeObject::Unwrap<WrappedScript>(args.Holder());
		if (!n_script) {
			return ThrowException(Exception::Error(String::New("Must be called as a method of Script.")));
		}
		n_script->script_ = Persistent<Script>::New(script);
		result = args.This();
	}

	if (context_flag == userContext || context_flag == newContext) {
		// success! copy changes back onto the sandbox object.
		keys = context->Global()->GetPropertyNames();
		for (i = 0; i < keys->Length(); i++) {
			Handle<String> key = keys->Get(Integer::New(i))->ToString();
			Handle<Value> value = context->Global()->Get(key);
			if (value == context->Global()) {
				value = sandbox;
			}
			sandbox->Set(key, value);
		}
	}

	if (context_flag == newContext) {
		// Clean up, clean up, everybody everywhere!
		context->DetachGlobal();
		context->Exit();
		context.Dispose();
	} else if (context_flag == userContext) {
		// Exit the passed in context.
		context->Exit();
	}

	if (result->IsObject()) {
		Local<Context> creation = result->ToObject()->CreationContext();
	}

	return result == args.This() ? result : scope.Close(result);
}
Esempio n. 28
0
int main (int argc, char** argv) {
    signal(SIGSEGV, AnsiSignalHandler);
    //    printf("SILK V0.1\n");
    char *startup;
    const char *progName;
    signal(SIGSEGV, AnsiSignalHandler);
    signal(SIGINT, AnsiSignalHandler);

    if (argc < 2) {
        startup = readFile("/usr/local/silkjs/builtin/interpreter.js");
        if (!startup) {
            startup = readFile("/usr/share/silkjs/builtin/interpreter.js");
        }
        progName = "interpreter";
    }
    else {
        startup = readFile(argv[1]);
        progName = argv[1];
    }
    if (!startup) {
        printf("%s not found\n", argv[1]);
        exit(1);
    }
    if (startup[0] == '#' && startup[1] == '!') {
        startup[0] = startup[1] = '/';
    }
    
    // v8 command line switches
    const char *switches = "--harmony";
    V8::SetFlagsFromString(switches, strlen(switches));
    
    {
        //		Isolate *isolate = Isolate::New();
        //		isolate->Enter();
        //		Locker lock(isolate);
        Locker locker;
        HandleScope scope;

        init_global_object();
        V8::SetCaptureStackTraceForUncaughtExceptions(true, 50); // , StackTrace::kDetailed);
        context = Context::New(NULL, globalObject);
        Context::Scope context_scope(context);
        {
            Locker locker;
            //			Debug::SetDebugMessageDispatchHandler(debugger, true);
            //			Debug::EnableAgent("silkjs", 5858);

            Handle<Script>init = Script::New(String::New("global=this; module = {}; include('builtin/all.js');"), String::New("builtin"));
            init->Run();
            V8::SetCaptureStackTraceForUncaughtExceptions(true, 50, StackTrace::kDetailed);
            TryCatch tryCatch;
            mainScript = Persistent<Script>::New(Script::Compile(String::New(startup), String::New(progName)));
            if (mainScript.IsEmpty()) {
                ReportException(&tryCatch);
                exit(1);
            }
            Handle<Value>v = mainScript->Run();
            if (v.IsEmpty()) {
                ReportException(&tryCatch);
                exit(1);
            }
            Handle<String> process_name = String::New("main");
            Handle<Value> process_val = context->Global()->Get(process_name);
            if (!process_val.IsEmpty() && process_val->IsFunction()) {
                Handle<Function> process_fun = Handle<Function>::Cast(process_val);
                mainFunc = Persistent<Function>::New(process_fun);
                int ac = argc - 2;
                if (ac < 0) {
                    ac = 0;
                }
                Handle<Value>av[ac];
                for (int i = 2; i < argc; i++) {
                    av[i - 2] = String::New(argv[i]);
                }
                v = mainFunc->Call(context->Global(), ac, av);
                if (v.IsEmpty()) {
                    ReportException(&tryCatch);
                    exit(1);
                }
            }
        }
        context.Dispose();
    }
}
Esempio n. 29
0
int main(int argc, char* argv[]) {




	// Create a stack-allocated handle scope.
	HandleScope handle_scope;


	// creating a global template

	Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
	global->Set(v8::String::New("print"), v8::FunctionTemplate::New(Print));

	// Create a new context.
	Persistent<Context> context = Context::New(NULL, global);


	current_context = context;
	// Enter the created context for compiling and
	// running the hello world script.
	Context::Scope context_scope(context);

	//Local<Object> global = Context::GetCurrent()->Global();

	//...
	//associates plus on script to the Plus function

	//create_entity_with_name("bhupesh", context);


	Handle<String> source ;
	Handle<Script> script;

	// Get the JavaScript file as a string
	// arg[0] is the file name

	if( argv[1] == NULL)
	{
		// Create a string containing the JavaScript source code.
		source = String::New("'Hello' + ', World!'");
		script = Script::Compile(source);
	}
	else
	{
		char* s = read_js_file_as_string(argv[1]);
		cout << "Script is " << endl;
		cout << s << endl;

		source = String::New(s);
		script = Script::Compile(source, String::New(argv[1]));
   }

	// Run the script to get the result.
//	script->Run();

//	assert(f_value->IsFunction());
//	Local<Function> f = Local<Function>::Cast(f_value);
//	f->Call(Context::GetCurrent()->Global(), 0, NULL);

	//Local<Value> args[2] = {v8::Number::New(3), v8::Number::New(4)};



	//Local<Number> result = (f->Call(Context::GetCurrent()->Global(), 2, args))->ToNumber();


	//int num = result->Int32Value();
	//printf("%d\n", num);


	// Dispose the persistent context.
	context.Dispose();


	return 0;
}
Esempio n. 30
0
void Player::Dispose(Persistent<Value> handle, void* parameter)
{
    auto instance = static_cast<PlayerPtr*>(parameter);
    delete instance;
    handle.Dispose();
}