Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the Abstract Syntax Tree of V8 Engine

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.

like image 686
Cookies Avatar asked Feb 26 '12 06:02

Cookies


1 Answers

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.

like image 154
Jonas Avatar answered Oct 09 '22 09:10

Jonas