我设法自己找到了。请参阅下面的示例,了解如何在堆栈上查找值(并替换它 - 这里是字符串变量的示例)。
提前说明两点:
- 除了在我的硕士论文中使用它的非常用例之外,我还没有测试过它的不良行为 - (可能)有龙。
- 我不知道为什么在我的测试中
sfl.FindJavaScriptFrame(0)
会产生所需的堆栈帧 - 但是,由于它独立于调用深度,我怀疑由 0 索引的堆栈帧始终是直接调用者的帧(在我的情况下,我知道我正是想要那个)。
和代码:
// Prepare identification of the variable,assuming varName as in the question
// More convenient conversions would be appreciated, at least by me
Local<String> varName = args[0]->ToString();
std::string varStr = *String::AsciiValue(varName);
// I'm using 'namespace i = internal;' (within v8-namespace)
i::Vector<const char> tmpVar(varStr.data(), varStr.length());
i::Handle<i::String> varIStr = i::Isolate::Current()->factory()->NewStringFromAscii(tmpVar, i::TENURED);
// Now hunt down the stack frame of interest, be sure to consider my remarks above
i::StackFrameLocator sfl;
// Comment from the code: The caller must guarantee that such a frame exists.
i::JavaScriptFrame* jsf = sfl.FindJavaScriptFrame(0);
// create some replacement
i::Vector<const char> tmp("there you go", 12);
i::Handle<i::String> insert = i::Isolate::Current()->factory()->NewStringFromAscii(tmp, i::TENURED);
i::Object* insertObj = insert->ToObjectChecked();
// by the help of JavaScriptFrame::Print I came up with this:
i::Object* fun = jsf->function();
if (fun->IsJSFunction()){
i::Handle<i::ScopeInfo> scope_info(i::ScopeInfo::Empty());
i::Handle<i::SharedFunctionInfo> shared((i::JSFunction::cast(fun))->shared());
scope_info = i::Handle<i::ScopeInfo>(shared->scope_info());
i::Object* script_obj = shared->script();
if (script_obj->IsScript()) {
int stack_locals_count = scope_info->StackLocalCount();
for (int i = 0; i < stack_locals_count; i++) {
if (scope_info->StackLocalName(i)->Equals(*varIStr)){
// replace the value on the stack
jsf->SetExpression(i,insertObj);
}
}
}
}