访问 V8 引擎的抽象语法树 [英] Access the Abstract Syntax Tree of V8 Engine

查看:16
本文介绍了访问 V8 引擎的抽象语法树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于给定的 JavaScript 代码,是否可以访问 v8 引擎的 AST?我正在使用 V8 引擎开发 JavaScript 静态分析器.

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.

推荐答案

这已经很老了,但也许这个答案可以帮助那些偶然发现的人.答案是肯定的,假设您愿意修改 V8 并编译您自己的版本.

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.

如果是这样,那么在 compiler.cc 中您会找到一个在整个 MakeFunctionInfo 中调用 MakeCode 的位置,它将存储在传入 CompilationInfo 对象中的 AST 转换为本地代码.您需要编写一个继承自 AstVisitor 的类,然后您可以通过在调用 MakeCode 之前插入以下几行来检查 AST:

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);

由于 V8 会在函数被实际调用时及时编译它们,因此 CompileLazy 中还有另一个地方,您必须在其中执行相同的操作才能在调用脚本的整个执行过程中获取它们的 AST.

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.

由于延迟编译的原因,这可能无法让您进行静态分析,因为在您访问 AST 以获取延迟编译的内容之前,执行已经在进行中.但这就是获取 AST 的方法.

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.

这篇关于访问 V8 引擎的抽象语法树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆