【erlang】反编译

反编译函数

beam_lib:chunks(BeamPath, [abstract_code]).

test_decompile.erl

-module(test_decompile).
-export([decompile/1]).

decompile(Beam) ->
	case beam_lib:chunks(code:which(Beam),  [abstract_code]) of
	    {ok, {_, [{abstract_code, {_, AC}}]}} ->
		    io:format("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))]);
		Other ->
			Other
	end.

test.erl

-module(test).
-compile(export_all).

-record(kv, {key, val}).

list() ->
	[1, 2, 3].
tuple() ->
	{a, b, c}.
string() ->
	"test".
atom() ->
	hello.
record() ->
	#kv{key = 1}.
binary() ->
	<<"aabbcc">>.

示例:

1> c(test).
{ok,test}
2> c(test_decompile).
{ok,test_decompile}
3> test_decompile:decompile(test).
{ok,{test,[{abstract_code,no_abstract_code}]}}

注意:要想反编译就必须在编译的时候加上+debug_info标记

[root@localhost]# erlc +debug_info test.erl
[root@localhost]# erl
Eshell V8.3  (abort with ^G)
1> test_decompile:decompile(test).
-file("test.erl", 1).
-module(test).
-compile(export_all).
-record(kv, {key, val}).
list() -> [1, 2, 3].
tuple() -> {a, b, c}.
string() -> "test".
atom() -> hello.
record() -> #kv{key = 1}.
binary() -> <<"aabbcc">>.
ok
### BEAM 反编译工具推荐及使用 Erlang 的 BEAM 文件是 Erlang 虚拟机(BEAM 虚拟机)执行的字节码文件,类似于 Java 的 `.class` 文件。要对 BEAM 文件进行反编译,通常需要在编译时添加 `-debug_info` 选项,以便在编译后的 BEAM 文件中保留调试信息,从而支持后续的反编译操作。 #### 推荐的 BEAM 反编译工具 1. **test_decompile** - 这是一个基于 Erlang 自带功能的反编译模块,可以在 Erlang shell 中直接调用。 - 使用方法: - 编译时添加 `+debug_info` 选项: ```bash erlc +debug_info test.erl ``` - 启动 Erlang shell 并调用反编译函数: ```erlang 1> test_decompile:decompile(test). ``` - 此方法适用于简单的 BEAM 文件反编译,并且能够输出原始的 Erlang 代码结构 [^1]。 2. **decompiler** - 这是一个基于 Python 开发的多后端反编译器,支持 IDA 和 Capstone 等知名逆向工程框架。 - 该工具的设计理念是轻量级和灵活性,能够解析复杂的应用程序代码,并将其还原为可读性强的高级语言表示。 - 使用方法: - 安装 Python 环境并安装 `decompiler` 工具。 - 调用工具并指定需要反编译的 BEAM 文件路径。 - 该工具的优势在于其跨平台支持和对多种后端框架的兼容性 [^2]。 3. **beam_lib** - Erlang 标准库中的 `beam_lib` 模块可以用于读取和处理 BEAM 文件。 - 如果 BEAM 文件使用了加密的调试信息,可以通过 `beam_lib` 提供的 `crypto_key_fun/1` 函数注册一个返回解密密钥的函数。 - 示例代码: ```erlang crypto_key_fun() -> "667788". beam_lib:chunks("test.beam", [debug_info], crypto_key_fun/1). ``` - 该方法适用于需要处理加密调试信息的 BEAM 文件 [^4]。 #### BEAM 反编译的使用场景 - **调试和分析** - 在开发过程中,保留 `debug_info` 信息有助于调试和分析程序行为。 - 如果需要发布生产环境,建议移除 `debug_info` 选项以防止代码被轻易反编译。 - **防止反编译** - 可以通过修改 Emakefile 文件,移除 `debug_info` 选项或使用加密的调试信息。 - 示例 Emakefile 配置: ```erlang {'src/*',[{debug_info_key,{des3_cbc,"mysecretkey"}},{i,"include"},{outdir,"ebin"}]}. ``` - 通过这种方式,可以增加反编译的难度 [^5]。 #### 反编译 BEAM 文件的注意事项 - **调试信息的重要性** - 如果没有在编译时添加 `debug_info` 选项,反编译将无法获取完整的源代码信息。 - 即使使用了加密的调试信息,也需要确保密钥正确,否则无法解密 [^3]。 - **工具选择** - 对于简单的反编译需求,推荐使用 `test_decompile` 模块。 - 对于复杂的逆向工程需求,推荐使用 `decompiler` 工具。 - 如果需要处理加密调试信息,建议使用 `beam_lib` 模块。 ####
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值