Decompiling .beam to core Erlang and compiling it back to .beam

Hi there, I’m trying to wrap my head around the Erlang compilation and tried to decompile a .beam file to core erlang:

{ok, {_module, [{abstract_code, {_Backend, AbstractCode}}]}} =
  beam_lib:chunks(Path, [abstract_code]),

{ok, _Module, Ast} = compile:noenv_forms(AbstractCode, [to_core]),
Ast.

and compile it back:

{ok, _Module, Beam} = compile:noenv_forms(Ast, [from_core]),
Beam.

And it looks like it works - I can load and use the compiled beam. However, when I try to decompile it again the same way, I get

exception error: no match of right hand side value 
                 {ok,{foo,[{abstract_code,no_abstract_code}]}}
  in function  erl_eval:expr/6 (erl_eval.erl, line 652)
  in call from erl_eval:exprs/6 (erl_eval.erl, line 271)

Is my approach right? Is it possible to decompile to core and back multiple times? What’s necessary for the decompilation to work?

Thanks :wink:

Hello!

What you are doing is not really decompilation, as much as it is extracting the original code from the debug information and then compiling it again. So the debug_info needs to be part of the beam file, not sure that that is possible to do when compiling from_core.

Thanks! How can I do the actual decompilation? Can I somehow ‘append’ debug_info to a .beam?

I don’t know if it is possible. You can have a look here for some discussion: https://erlangforums.com/t/need-help-decompiling-beam-file

Using beam_lib:build_module/1 it should be possible to add more chunks to an existing beam file.

2 Likes