Access the Abstract Syntax Tree of V8 Engine

无人久伴 提交于 2019-12-03 07:42:39

问题


Is it possible to access the AST of the v8 engine, for a given JavaScript code? I'm working on a JavaScript Static Analyzer using V8 engine.


回答1:


This is pretty old but maybe the answer helps someone stumbling upon this. The answer is yes, assuming you are willing to modify V8 and compile your own version of it.

If so, then in compiler.cc you find a spot where MakeCode is called throughout MakeFunctionInfo which transforms the AST that is stored in the passed in CompilationInfo object into native code. You need to write a class that inherits from AstVisitor then you can inspect the AST by inserting the following lines before the call to MakeCode:

MyAstVisitor mAV;
// this will call VisitFunctionLiteral in your AST visitor
info->function()->Accept(mAV);

As V8 compiles functions just-in-time when they are actually called, there is another spot in CompileLazy where you would have to do the same to get their ASTs throughout execution of calling scripts.

Because of the lazy compilation thing this probably won't enable you to do static analysis, because the execution already is in progress before you have access to the ASTs for lazily compiled stuff. But this is how to obtain the ASTs.




回答2:


Use --print-ast via SetFlagsFromString




回答3:


Well, I don't know what you want to achieve, but it sounds like you want to modify the AST from inside your C++ code (or maybe write wrapper classes for the JavaScript context for them as well?).

I suggest to take a look at the headers file which pretty explains what's there to be used on V8's AST:

http://v8.googlecode.com/svn/trunk/src/ast.h

~Cheers



来源:https://stackoverflow.com/questions/9451067/access-the-abstract-syntax-tree-of-v8-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!