Disassemble Elixir code

And check if Erlang dead code elimination works

Gaspar Chilingarov
Sep 29, 2017 · 2 min read
Image for post
Image for post
HOW DO YOU DO IT??? MINDBLOWING!

Test source code

defmodule Test do
@flag1 false
def init() do
IO.puts "Execute always"
if @flag1 do
IO.puts "Execute in feature flag"
end
42
end
end

Retrieve Core Erlang / IR / Intermediate Representation

f = './_build/dev/lib/test/ebin/Elixir.Test.beam'
result = :beam_lib.chunks(f,[:abstract_code])
{:ok,{_,[{:abstract_code,{_,ac}}]}} = result
IO.puts :erl_prettypr.format(:erl_syntax.form_list(ac))
-file("lib/test.ex", 1).-module('Elixir.Test').-compile(no_auto_import).-export(['__info__'/1, init/0]).-spec '__info__'(attributes | compile | functions |
macros | md5 | module) -> atom() |
[{atom(), any()} |
{atom(), byte(), integer()}].
'__info__'(module) -> 'Elixir.Test';
'__info__'(functions) -> [{init, 0}];
'__info__'(macros) -> [];
'__info__'(attributes) ->
erlang:get_module_info('Elixir.Test', attributes);
'__info__'(compile) ->
erlang:get_module_info('Elixir.Test', compile);
'__info__'(md5) ->
erlang:get_module_info('Elixir.Test', md5).
init() ->
'Elixir.IO':puts(<<"Execute always">>),
case false of
false -> nil;
true -> 'Elixir.IO':puts(<<"Execute in feature flag">>)
end,
42.

Retrieve BEAM disassembly

f = ‘./_build/dev/lib/test/ebin/Elixir.Test.beam’
{:ok, beam} = File.read(f)
IO.inspect :beam_disasm.file(beam), pretty: true
{
:function,
:init,
0,
7,
[
{:line, 1},
{:label, 6},
{:func_info, {:atom, Test}, {:atom, :init}, 0},
{:label, 7},
{:allocate, 0, 0},
{:move, {:literal, "Execute always"}, {:x, 0}},
{:line, 2},
{:call_ext, 1, {:extfunc, IO, :puts, 1}},
{:move, {:integer, 42}, {:x, 0}},
{:deallocate, 0},
:return
]
}

Need help with your Elixir app or want prototype your next microservice in Elixir? DM me on Twitter or Github.

Learn Elixir

Write fast applications in Elixir!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store