怎么通过beam文件得到所有的record或源代码?
1. 首先必须要在compile里面加上debug_info信息:
1 > c(load,[debug_info]). {ok,load} 2> beam_lib:chunks(code:which(load),[compile_info]). {ok,{load,[{compile_info,[{options,[debug_info]}, {version,"5.0.2"}, {time,{2014,11,10,15,19,43}}, {source,"c:/Users/admin/Documents/GitHub/ErlMixCode/src/load/load.erl"}]}]}}
2. 从beam中通过beam_lib模块取出recod信息或源代码:
-module(beamI). %% API -export([record_attrs/1,beam_to_source/1]).
%%得到record信息[{RecName1,[Filed11,Filed12]},{RecName2,[Filed21,Filed22]}] record_attrs(Beam) -> {ok,{_Mod,[{abstract_code,{_Version,Forms}},{"CInf",_CB}]}} = beam_lib:chunks(code:which(Beam), [abstract_code,"CInf"]), [join_name_field(D) || {attribute,_,record,D} <- Forms].
%%得到源代码Beam.erl内容: beam_to_source(Beam) -> {ok,{_,[{abstract_code,{_,AC}}]}} = beam_lib:chunks(code:which(Beam),[abstract_code]), io:fwrite("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))]). join_name_field({Name, Fs}) -> {Name, [element(3, element(3,F)) || F <- Fs]}.
3. 测试:得到record和源文件:
3> beamI:record_attrs(mnesia). [{tid,[counter,pid]}, {tidstore,[store,up_stores,level]}, {cstruct,[name,type,ram_copies,disc_copies,disc_only_copies, load_order,access_mode,majority,index,snmp,local_content, record_name,attributes,user_properties,frag_properties, storage_properties,cookie,version]}, {log_header,[log_kind,log_version,mnesia_version,node,now]}, {commit,[node,decision,ram_copies,disc_copies, disc_only_copies,snmp,schema_ops]}, {decision,[tid,outcome,disc_nodes,ram_nodes]}, {cyclic,[node,oid,op,lock,lucky]}, {mnesia_select,[tab,tid,node,storage,cont,written,spec,type, orig]}]
4> beamI:beam_to_source(load). -file("load.erl", 1). -module(load). -behaviour(gen_server). -vsn("1.0"). -export([multi_start/0, multi_start/1, start/0, start/1, start_link/0, start_link/1]). -export([stop/0, multi_stop/0]). .......
这一切的前提都是你要在编译时+上debug_info信息:
因为你不想加debug_info让代码泄露,但有一些测试工具又非常依赖debug_info。
这时你可以使用encryption对debug_info进行加密,详见beam_lib的官方文档:)
参照:beam_lib模块的官方文档。
--------------------------------------------------------------------------------------------------------------------------------------
人家手都伸出来了,好歹给一小鱼干啊,这是人干的吗?