binary_to_term(Str, [safe])小问题

现有二进制如下, 需要将其转换为mod_gvg
出于安全的考虑,需要使用`erlang:binary_to_term(Bin, [safe]).

1
2
3
4
Eshell V6.2  (abort with ^G)
1> erlang:term_to_binary({mod_gvg}).
<<131,104,1,100,0,7,109,111,100,95,103,118,103>>
2>

现存在模块safe

1
2
3
4
5
6
-module(safe).

-export([get/1]).

get(mod_gvg) -> 0;
get(_) -> 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Eshell V6.2  (abort with ^G)
1> safe:module_info().
[{exports,[{get,1},{module_info,0},{module_info,1}]},
{imports,[]},
{attributes,[{vsn,[260324741032660828457261428974125625377]}]},
{compile,[{options,[]},
{version,"5.0.2"},
{time,{2018,3,13,9,9,43}},
{source,"e:/ff/safe.erl"}]}]
2> erlang:binary_to_term(<<131,104,1,100,0,7,109,111,100,95,103,118,103>>, [safe]).
** exception error: bad argument
in function binary_to_term/2
called as binary_to_term(<<131,104,1,100,0,7,109,111,100,95,103,118,103>>,
[safe])
3>

明明mod_gvg已经在safe代码中,为什么还是提示失败?
将代码修改如下:

1
2
3
4
5
6
-module(safe).

-export([get/1]).

get(mod_gvg) -> 1;
get(_) -> 0.

再次执行,一切ok

1
2
3
4
5
6
7
8
9
10
11
12
Eshell V6.2  (abort with ^G)
1> safe:module_info().
[{exports,[{get,1},{module_info,0},{module_info,1}]},
{imports,[]},
{attributes,[{vsn,[50307215724812432190773629780968579091]}]},
{compile,[{options,[]},
{version,"5.0.2"},
{time,{2018,3,13,9,12,45}},
{source,"e:/ff/safe.erl"}]}]
2> erlang:binary_to_term(<<131,104,1,100,0,7,109,111,100,95,103,118,103>>, [safe]).
{mod_gvg}
3>

说明在编译代码时,编译器有做优化,将

get(mod_gvg) -> 0;
get(_) -> 0.

简化为get(_) -> 0.
因此, 如果要标明原子存在, 需要是有用的代码.

参考文档

  1. [http://erlang.org/doc/man/erlang.html#binary_to_term-2]