v8生成字节码快照和读取快照

原创
2020/02/27 18:11
阅读数 2.7K

必须要吐槽一下,大概是没人搞这个东西,本来是想做个工具,思来想去选择了大火的v8引擎,写着写着我需要一个js加密,但是搜遍了各大引擎也没有,大概是姿势不到位把,于是想起来nodejs也有这个功能,于是下载源码把单独提取出来,分享给大家,省的到处找了。 我用的版本不一定是你的版本,api稍有变化情理之中

加载快照-如下:

{
    /*
    //v8加载字节码
    v8::Handle<v8::String> source_string = v8::String::NewFromUtf8(isolate, "", v8::NewStringType::kNormal).ToLocalChecked();
    uint8_t *data = reinterpret_cast<uint8_t*>("");
    v8::ScriptCompiler::CachedData* cache = new v8::ScriptCompiler::CachedData(data, 10,v8::ScriptCompiler::CachedData::BufferNotOwned);
    v8::ScriptCompiler::Source source1(source_string, cache);
    script = v8::ScriptCompiler::CompileUnboundScript(
        isolate, &source1, v8::ScriptCompiler::kConsumeCodeCache).ToLocalChecked();
    */
}
{
    size_t*  len;
    unsigned char* data = "";
    v8::StartupData data1 = v8::CreateSnapshotDataBlob((const char*)data);//编译字节码
    bool a = paWriteToFile("hmbb.bin", data1.data, data1.raw_size);
    //js编译字节码成功
    //data1.data data1.raw_size
    //delete[] data1.data;
}

当然你会发现缺少CreateSnapshotDataBlob,在这里:

bool RunExtraCode(v8::Isolate* isolate, v8::Local<v8::Context> context,
		const char* utf8_source, const char* name) {
		v8::Context::Scope context_scope(context);
		v8::TryCatch try_catch(isolate);
		v8::Local<v8::String> source_string;
		if (!v8::String::NewFromUtf8(isolate, utf8_source, v8::NewStringType::kNormal)
			.ToLocal(&source_string)) {
			return false;
		}
		v8::Local<v8::String> resource_name =
			v8::String::NewFromUtf8(isolate, name, v8::NewStringType::kNormal)
			.ToLocalChecked();
		v8::ScriptOrigin origin(resource_name);
		v8::ScriptCompiler::Source source(source_string, origin);
		v8::Local<v8::Script> script;
		if (!v8::ScriptCompiler::Compile(context, &source).ToLocal(&script))
			return false;
		if (script->Run(context).IsEmpty()) return false;
		//CHECK(!try_catch.HasCaught());
		return true;
	}
	v8::StartupData CreateSnapshotDataBlob(const char* embedded_source = nullptr) {
		// Create a new isolate and a new context from scratch, optionally run
		// a script to embed, and serialize to create a snapshot blob.
		v8::StartupData result = { nullptr, 0 };
		{
			v8::SnapshotCreator snapshot_creator;
			v8::Isolate* isolate = snapshot_creator.GetIsolate();
			{
				v8::HandleScope scope(isolate);
				v8::Local<v8::Context> context = v8::Context::New(isolate);
				if (embedded_source != nullptr &&
					!RunExtraCode(isolate, context, embedded_source, "<embedded>")) {
					return result;
				}
				snapshot_creator.SetDefaultContext(context);
			}
			result = snapshot_creator.CreateBlob(
				v8::SnapshotCreator::FunctionCodeHandling::kClear);
		}
		return result;
	}

好了。

展开阅读全文
V8
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部