Skip to content

Instantly share code, notes, and snippets.

@AndreasMadsen
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreasMadsen/4c02c801400391a4bac8 to your computer and use it in GitHub Desktop.
Save AndreasMadsen/4c02c801400391a4bac8 to your computer and use it in GitHub Desktop.
Working Local Scope in v8
diff --git a/src/runtime.cc b/src/runtime.cc
index 1616434..a72eff3 100644
--- a/src/runtime.cc
+++ b/src/runtime.cc
@@ -14552,6 +14552,59 @@ RUNTIME_FUNCTION(Runtime_GetScript) {
}
+// Get variabels in this function scope
+RUNTIME_FUNCTION(Runtime_LocalVariabels) {
+ HandleScope scope(isolate);
+
+ DCHECK(args.length() == 2);
+
+ CONVERT_ARG_HANDLE_CHECKED(JSObject, locals, 0);
+ CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 1);
+
+ // Unpack the function scope
+ SharedFunctionInfo* shared = function->shared();
+ ScopeInfo* scope_info = shared->scope_info();
+ Object* script_obj = shared->script();
+
+ if (script_obj->IsScript()) {
+ // Search the frames for a function match
+ JavaScriptFrame* frame;
+ bool found = false;
+
+ for (JavaScriptFrameIterator it(isolate); !it.done(); it.Advance()) {
+ frame = it.frame();
+ if (frame->function() == *function.location()) {
+ found = true;
+ break;
+ }
+ }
+
+ // function is not in active scope, stop here
+ if (!found) {
+ return isolate->heap()->undefined_value();
+ }
+
+ // Build an object containing the local variables
+ int stack_local_count = scope_info->StackLocalCount();
+
+ for (int i = 0; i < stack_local_count; i++) {
+ String* name = scope_info->StackLocalName(i);
+ Object* value = frame->GetExpression(i);
+
+ Handle<String> prop_name = Handle<String>(name, isolate);
+ Handle<Object> prop_value = Handle<Object>(value, isolate);
+ JSObject::SetProperty(locals, prop_name, prop_value, SLOPPY).Assert();
+ }
+ return isolate->heap()->undefined_value();
+ }
+
+ return isolate->heap()->undefined_value();
+}
+
+
// Collect the raw data for a stack trace. Returns an array of 4
// element segments each containing a receiver, function, code and
// native code offset.
diff --git a/src/runtime.h b/src/runtime.h
index ef42b52..c22146a 100644
--- a/src/runtime.h
+++ b/src/runtime.h
@@ -207,6 +207,7 @@ namespace internal {
F(FunctionIsAPIFunction, 1, 1) \
F(FunctionIsBuiltin, 1, 1) \
F(GetScript, 1, 1) \
+ F(LocalVariabels, 2, 1) \
F(CollectStackTrace, 2, 1) \
F(GetV8Version, 0, 1) \
\
d8 --allow-natives-syntax test.js
{
"a": true,
"b": {
"prop": "you"
},
"c": "Bad Ass",
"d": [
"my",
"life",
0
]
}
function GetLocals(func) {
var locals = {};
%LocalVariabels(locals, func);
return locals;
}
function foo() {
var a = true;
var b = { "prop": "you" };
var c = "Bad Ass";
var d = ["my", "life", 0];
print(JSON.stringify(GetLocals(foo), null, '\t'));
}
foo();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment