PageRenderTime 338ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/stdlib/src/beam_lib.erl

https://github.com/cobusc/otp
Erlang | 1176 lines | 952 code | 151 blank | 73 comment | 9 complexity | 03822b71c16cbd34c752916621d5518c MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, Apache-2.0
  1. %%
  2. %% %CopyrightBegin%
  3. %%
  4. %% Copyright Ericsson AB 2000-2018. All Rights Reserved.
  5. %%
  6. %% Licensed under the Apache License, Version 2.0 (the "License");
  7. %% you may not use this file except in compliance with the License.
  8. %% You may obtain a copy of the License at
  9. %%
  10. %% http://www.apache.org/licenses/LICENSE-2.0
  11. %%
  12. %% Unless required by applicable law or agreed to in writing, software
  13. %% distributed under the License is distributed on an "AS IS" BASIS,
  14. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. %% See the License for the specific language governing permissions and
  16. %% limitations under the License.
  17. %%
  18. %% %CopyrightEnd%
  19. %%
  20. -module(beam_lib).
  21. -behaviour(gen_server).
  22. %% Avoid warning for local function error/1 clashing with autoimported BIF.
  23. -compile({no_auto_import,[error/1]}).
  24. %% Avoid warning for local function error/2 clashing with autoimported BIF.
  25. -compile({no_auto_import,[error/2]}).
  26. -export([info/1,
  27. cmp/2,
  28. cmp_dirs/2,
  29. chunks/2,
  30. chunks/3,
  31. all_chunks/1,
  32. diff_dirs/2,
  33. strip/1,
  34. strip_files/1,
  35. strip_release/1,
  36. build_module/1,
  37. version/1,
  38. md5/1,
  39. format_error/1]).
  40. %% The following functions implement encrypted debug info.
  41. -export([crypto_key_fun/1, clear_crypto_key_fun/0]).
  42. -export([init/1,handle_call/3,handle_cast/2,handle_info/2,
  43. terminate/2,code_change/3]).
  44. -export([make_crypto_key/2, get_crypto_key/1]). %Utilities used by compiler
  45. -export_type([attrib_entry/0, compinfo_entry/0, labeled_entry/0, label/0]).
  46. -import(lists, [append/1, delete/2, foreach/2, keysort/2,
  47. member/2, reverse/1, sort/1, splitwith/2]).
  48. %%-------------------------------------------------------------------------
  49. -type beam() :: module() | file:filename() | binary().
  50. -type debug_info() :: {DbgiVersion :: atom(), Backend :: module(), Data :: term()} | 'no_debug_info'.
  51. -type forms() :: [erl_parse:abstract_form() | erl_parse:form_info()].
  52. -type abst_code() :: {AbstVersion :: atom(), forms()} | 'no_abstract_code'.
  53. -type dataB() :: binary().
  54. -type index() :: non_neg_integer().
  55. -type label() :: integer().
  56. -type chunkid() :: nonempty_string(). % approximation of the strings below
  57. %% "Abst" | "Dbgi" | "Attr" | "CInf" | "ExpT" | "ImpT" | "LocT" | "Atom" | "AtU8".
  58. -type chunkname() :: 'abstract_code' | 'debug_info'
  59. | 'attributes' | 'compile_info'
  60. | 'exports' | 'labeled_exports'
  61. | 'imports' | 'indexed_imports'
  62. | 'locals' | 'labeled_locals'
  63. | 'atoms'.
  64. -type chunkref() :: chunkname() | chunkid().
  65. -type attrib_entry() :: {Attribute :: atom(), [AttributeValue :: term()]}.
  66. -type compinfo_entry() :: {InfoKey :: atom(), term()}.
  67. -type labeled_entry() :: {Function :: atom(), arity(), label()}.
  68. -type chunkdata() :: {chunkid(), dataB()}
  69. | {'abstract_code', abst_code()}
  70. | {'debug_info', debug_info()}
  71. | {'attributes', [attrib_entry()]}
  72. | {'compile_info', [compinfo_entry()]}
  73. | {'exports', [{atom(), arity()}]}
  74. | {'labeled_exports', [labeled_entry()]}
  75. | {'imports', [mfa()]}
  76. | {'indexed_imports', [{index(), module(), Function :: atom(), arity()}]}
  77. | {'locals', [{atom(), arity()}]}
  78. | {'labeled_locals', [labeled_entry()]}
  79. | {'atoms', [{integer(), atom()}]}.
  80. %% Error reasons
  81. -type info_rsn() :: {'chunk_too_big', file:filename(),
  82. chunkid(), ChunkSize :: non_neg_integer(),
  83. FileSize :: non_neg_integer()}
  84. | {'invalid_beam_file', file:filename(),
  85. Position :: non_neg_integer()}
  86. | {'invalid_chunk', file:filename(), chunkid()}
  87. | {'missing_chunk', file:filename(), chunkid()}
  88. | {'not_a_beam_file', file:filename()}
  89. | {'file_error', file:filename(), file:posix()}.
  90. -type chnk_rsn() :: {'unknown_chunk', file:filename(), atom()}
  91. | {'key_missing_or_invalid', file:filename(),
  92. 'abstract_code' | 'debug_info'}
  93. | info_rsn().
  94. -type cmp_rsn() :: {'modules_different', module(), module()}
  95. | {'chunks_different', chunkid()}
  96. | 'different_chunks'
  97. | info_rsn().
  98. %%-------------------------------------------------------------------------
  99. %%
  100. %% Exported functions
  101. %%
  102. -spec info(Beam) -> [InfoPair] | {'error', 'beam_lib', info_rsn()} when
  103. Beam :: beam(),
  104. InfoPair :: {'file', Filename :: file:filename()}
  105. | {'binary', Binary :: binary()}
  106. | {'module', Module :: module()}
  107. | {'chunks', [{ChunkId :: chunkid(),
  108. Pos :: non_neg_integer(),
  109. Size :: non_neg_integer()}]}.
  110. info(File) ->
  111. read_info(beam_filename(File)).
  112. -spec chunks(Beam, ChunkRefs) ->
  113. {'ok', {module(), [chunkdata()]}} |
  114. {'error', 'beam_lib', chnk_rsn()} when
  115. Beam :: beam(),
  116. ChunkRefs :: [chunkref()].
  117. chunks(File, Chunks) ->
  118. read_chunk_data(File, Chunks).
  119. -spec chunks(Beam, ChunkRefs, Options) ->
  120. {'ok', {module(), [ChunkResult]}} |
  121. {'error', 'beam_lib', chnk_rsn()} when
  122. Beam :: beam(),
  123. ChunkRefs :: [chunkref()],
  124. Options :: ['allow_missing_chunks'],
  125. ChunkResult :: chunkdata() | {ChunkRef :: chunkref(), 'missing_chunk'}.
  126. chunks(File, Chunks, Options) ->
  127. try read_chunk_data(File, Chunks, Options)
  128. catch Error -> Error end.
  129. -spec all_chunks(beam()) ->
  130. {'ok', 'beam_lib', [{chunkid(), dataB()}]} | {'error', 'beam_lib', info_rsn()}.
  131. all_chunks(File) ->
  132. read_all_chunks(File).
  133. -spec cmp(Beam1, Beam2) -> 'ok' | {'error', 'beam_lib', cmp_rsn()} when
  134. Beam1 :: beam(),
  135. Beam2 :: beam().
  136. cmp(File1, File2) ->
  137. try cmp_files(File1, File2)
  138. catch Error -> Error end.
  139. -spec cmp_dirs(Dir1, Dir2) ->
  140. {Only1, Only2, Different} | {'error', 'beam_lib', Reason} when
  141. Dir1 :: atom() | file:filename(),
  142. Dir2 :: atom() | file:filename(),
  143. Only1 :: [file:filename()],
  144. Only2 :: [file:filename()],
  145. Different :: [{Filename1 :: file:filename(), Filename2 :: file:filename()}],
  146. Reason :: {'not_a_directory', term()} | info_rsn().
  147. cmp_dirs(Dir1, Dir2) ->
  148. catch compare_dirs(Dir1, Dir2).
  149. -spec diff_dirs(Dir1, Dir2) -> 'ok' | {'error', 'beam_lib', Reason} when
  150. Dir1 :: atom() | file:filename(),
  151. Dir2 :: atom() | file:filename(),
  152. Reason :: {'not_a_directory', term()} | info_rsn().
  153. diff_dirs(Dir1, Dir2) ->
  154. catch diff_directories(Dir1, Dir2).
  155. -spec strip(Beam1) ->
  156. {'ok', {module(), Beam2}} | {'error', 'beam_lib', info_rsn()} when
  157. Beam1 :: beam(),
  158. Beam2 :: beam().
  159. strip(FileName) ->
  160. try strip_file(FileName)
  161. catch Error -> Error end.
  162. -spec strip_files(Files) ->
  163. {'ok', [{module(), Beam}]} | {'error', 'beam_lib', info_rsn()} when
  164. Files :: [beam()],
  165. Beam :: beam().
  166. strip_files(Files) when is_list(Files) ->
  167. try strip_fils(Files)
  168. catch Error -> Error end.
  169. -spec strip_release(Dir) ->
  170. {'ok', [{module(), file:filename()}]}
  171. | {'error', 'beam_lib', Reason} when
  172. Dir :: atom() | file:filename(),
  173. Reason :: {'not_a_directory', term()} | info_rsn().
  174. strip_release(Root) ->
  175. catch strip_rel(Root).
  176. -spec version(Beam) ->
  177. {'ok', {module(), [Version :: term()]}} |
  178. {'error', 'beam_lib', chnk_rsn()} when
  179. Beam :: beam().
  180. version(File) ->
  181. case catch read_chunk_data(File, [attributes]) of
  182. {ok, {Module, [{attributes, Attrs}]}} ->
  183. {vsn, Version} = lists:keyfind(vsn, 1, Attrs),
  184. {ok, {Module, Version}};
  185. Error ->
  186. Error
  187. end.
  188. -spec md5(Beam) ->
  189. {'ok', {module(), MD5}} | {'error', 'beam_lib', chnk_rsn()} when
  190. Beam :: beam(),
  191. MD5 :: binary().
  192. md5(File) ->
  193. case catch read_significant_chunks(File, md5_chunks()) of
  194. {ok, {Module, Chunks0}} ->
  195. Chunks = filter_funtab(Chunks0),
  196. {ok, {Module, erlang:md5([C || {_Id, C} <- Chunks])}};
  197. Error ->
  198. Error
  199. end.
  200. -spec format_error(Reason) -> io_lib:chars() when
  201. Reason :: term().
  202. format_error({error, Error}) ->
  203. format_error(Error);
  204. format_error({error, Module, Error}) ->
  205. Module:format_error(Error);
  206. format_error({unknown_chunk, File, ChunkName}) ->
  207. io_lib:format("~tp: Cannot find chunk ~p~n", [File, ChunkName]);
  208. format_error({invalid_chunk, File, ChunkId}) ->
  209. io_lib:format("~tp: Invalid contents of chunk ~p~n", [File, ChunkId]);
  210. format_error({not_a_beam_file, File}) ->
  211. io_lib:format("~tp: Not a BEAM file~n", [File]);
  212. format_error({file_error, File, Reason}) ->
  213. io_lib:format("~tp: ~tp~n", [File, file:format_error(Reason)]);
  214. format_error({missing_chunk, File, ChunkId}) ->
  215. io_lib:format("~tp: Not a BEAM file: no IFF \"~s\" chunk~n",
  216. [File, ChunkId]);
  217. format_error({invalid_beam_file, File, Pos}) ->
  218. io_lib:format("~tp: Invalid format of BEAM file near byte number ~p~n",
  219. [File, Pos]);
  220. format_error({chunk_too_big, File, ChunkId, Size, Len}) ->
  221. io_lib:format("~tp: Size of chunk \"~s\" is ~p bytes, "
  222. "but only ~p bytes could be read~n",
  223. [File, ChunkId, Size, Len]);
  224. format_error({chunks_different, Id}) ->
  225. io_lib:format("Chunk \"~s\" differs in the two files~n", [Id]);
  226. format_error(different_chunks) ->
  227. "The two files have different chunks\n";
  228. format_error({modules_different, Module1, Module2}) ->
  229. io_lib:format("Module names ~p and ~p differ in the two files~n",
  230. [Module1, Module2]);
  231. format_error({not_a_directory, Name}) ->
  232. io_lib:format("~tp: Not a directory~n", [Name]);
  233. format_error({key_missing_or_invalid, File, ChunkId}) ->
  234. io_lib:format("~tp: Cannot decrypt ~ts because key is missing or invalid",
  235. [File, ChunkId]);
  236. format_error(badfun) ->
  237. "not a fun or the fun has the wrong arity";
  238. format_error(exists) ->
  239. "a fun has already been installed";
  240. format_error(E) ->
  241. io_lib:format("~tp~n", [E]).
  242. %%
  243. %% Exported functions for encrypted debug info.
  244. %%
  245. -type mode() :: 'des3_cbc'.
  246. -type crypto_fun_arg() :: 'init'
  247. | 'clear'
  248. | {'debug_info', mode(), module(), file:filename()}.
  249. -type crypto_fun() :: fun((crypto_fun_arg()) -> term()).
  250. -spec crypto_key_fun(CryptoKeyFun) -> 'ok' | {'error', Reason} when
  251. CryptoKeyFun :: crypto_fun(),
  252. Reason :: badfun | exists | term().
  253. crypto_key_fun(F) ->
  254. call_crypto_server({crypto_key_fun, F}).
  255. -spec clear_crypto_key_fun() -> 'undefined' | {'ok', Result} when
  256. Result :: 'undefined' | term().
  257. clear_crypto_key_fun() ->
  258. call_crypto_server(clear_crypto_key_fun).
  259. -spec make_crypto_key(mode(), string()) ->
  260. {mode(), [binary()], binary(), integer()}.
  261. make_crypto_key(des3_cbc=Type, String) ->
  262. <<K1:8/binary,K2:8/binary>> = First = erlang:md5(String),
  263. <<K3:8/binary,IVec:8/binary>> = erlang:md5([First|reverse(String)]),
  264. {Type,[K1,K2,K3],IVec,8}.
  265. -spec build_module(Chunks) -> {'ok', Binary} when
  266. Chunks :: [{chunkid(), dataB()}],
  267. Binary :: binary().
  268. build_module(Chunks0) ->
  269. Chunks = list_to_binary(build_chunks(Chunks0)),
  270. Size = byte_size(Chunks),
  271. 0 = Size rem 4, % Assertion: correct padding?
  272. {ok, <<"FOR1", (Size+4):32, "BEAM", Chunks/binary>>}.
  273. %%
  274. %% Local functions
  275. %%
  276. read_info(File) ->
  277. try
  278. {ok, Module, Data} = scan_beam(File, info),
  279. [if
  280. is_binary(File) -> {binary, File};
  281. true -> {file, File}
  282. end, {module, Module}, {chunks, Data}]
  283. catch Error -> Error end.
  284. diff_directories(Dir1, Dir2) ->
  285. {OnlyDir1, OnlyDir2, Diff} = compare_dirs(Dir1, Dir2),
  286. diff_only(Dir1, OnlyDir1),
  287. diff_only(Dir2, OnlyDir2),
  288. foreach(fun(D) -> io:format("** different: ~tp~n", [D]) end, Diff),
  289. ok.
  290. diff_only(_Dir, []) ->
  291. ok;
  292. diff_only(Dir, Only) ->
  293. io:format("Only in ~tp: ~tp~n", [Dir, Only]).
  294. %% -> {OnlyInDir1, OnlyInDir2, Different} | throw(Error)
  295. compare_dirs(Dir1, Dir2) ->
  296. R1 = sofs:relation(beam_files(Dir1)),
  297. R2 = sofs:relation(beam_files(Dir2)),
  298. F1 = sofs:domain(R1),
  299. F2 = sofs:domain(R2),
  300. {O1, Both, O2} = sofs:symmetric_partition(F1, F2),
  301. OnlyL1 = sofs:image(R1, O1),
  302. OnlyL2 = sofs:image(R2, O2),
  303. B1 = sofs:to_external(sofs:restriction(R1, Both)),
  304. B2 = sofs:to_external(sofs:restriction(R2, Both)),
  305. Diff = compare_files(B1, B2, []),
  306. {sofs:to_external(OnlyL1), sofs:to_external(OnlyL2), Diff}.
  307. compare_files([], [], Acc) ->
  308. lists:reverse(Acc);
  309. compare_files([{_,F1} | R1], [{_,F2} | R2], Acc) ->
  310. NAcc = case catch cmp_files(F1, F2) of
  311. {error, _Mod, _Reason} ->
  312. [{F1, F2} | Acc];
  313. ok ->
  314. Acc
  315. end,
  316. compare_files(R1, R2, NAcc).
  317. beam_files(Dir) ->
  318. ok = assert_directory(Dir),
  319. L = filelib:wildcard(filename:join(Dir, "*.beam")),
  320. [{filename:basename(Path), Path} || Path <- L].
  321. %% -> ok | throw(Error)
  322. cmp_files(File1, File2) ->
  323. {ok, {M1, L1}} = read_all_but_useless_chunks(File1),
  324. {ok, {M2, L2}} = read_all_but_useless_chunks(File2),
  325. if
  326. M1 =:= M2 ->
  327. cmp_lists(L1, L2);
  328. true ->
  329. error({modules_different, M1, M2})
  330. end.
  331. cmp_lists([], []) ->
  332. ok;
  333. cmp_lists([{Id, C1} | R1], [{Id, C2} | R2]) ->
  334. if
  335. C1 =:= C2 ->
  336. cmp_lists(R1, R2);
  337. true ->
  338. error({chunks_different, Id})
  339. end;
  340. cmp_lists(_, _) ->
  341. error(different_chunks).
  342. strip_rel(Root) ->
  343. ok = assert_directory(Root),
  344. strip_fils(filelib:wildcard(filename:join(Root, "lib/*/ebin/*.beam"))).
  345. %% -> {ok, [{Mod, BinaryOrFileName}]} | throw(Error)
  346. strip_fils(Files) ->
  347. {ok, [begin {ok, Reply} = strip_file(F), Reply end || F <- Files]}.
  348. %% -> {ok, {Mod, FileName}} | {ok, {Mod, binary()}} | throw(Error)
  349. strip_file(File) ->
  350. {ok, {Mod, Chunks}} = read_significant_chunks(File, significant_chunks()),
  351. {ok, Stripped0} = build_module(Chunks),
  352. Stripped = compress(Stripped0),
  353. case File of
  354. _ when is_binary(File) ->
  355. {ok, {Mod, Stripped}};
  356. _ ->
  357. FileName = beam_filename(File),
  358. case file:open(FileName, [raw, binary, write]) of
  359. {ok, Fd} ->
  360. case file:write(Fd, Stripped) of
  361. ok ->
  362. ok = file:close(Fd),
  363. {ok, {Mod, FileName}};
  364. Error ->
  365. ok = file:close(Fd),
  366. file_error(FileName, Error)
  367. end;
  368. Error ->
  369. file_error(FileName, Error)
  370. end
  371. end.
  372. build_chunks([{Id, Data} | Chunks]) ->
  373. BId = list_to_binary(Id),
  374. Size = byte_size(Data),
  375. Chunk = [<<BId/binary, Size:32>>, Data | pad(Size)],
  376. [Chunk | build_chunks(Chunks)];
  377. build_chunks([]) ->
  378. [].
  379. pad(Size) ->
  380. case Size rem 4 of
  381. 0 -> [];
  382. Rem -> lists:duplicate(4 - Rem, 0)
  383. end.
  384. %% -> {ok, {Module, Chunks}} | throw(Error)
  385. read_all_but_useless_chunks(File0) when is_atom(File0);
  386. is_list(File0);
  387. is_binary(File0) ->
  388. File = beam_filename(File0),
  389. {ok, Module, ChunkIds0} = scan_beam(File, info),
  390. ChunkIds = [Name || {Name,_,_} <- ChunkIds0,
  391. not is_useless_chunk(Name)],
  392. {ok, Module, Chunks} = scan_beam(File, ChunkIds),
  393. {ok, {Module, lists:reverse(Chunks)}}.
  394. is_useless_chunk("CInf") -> true;
  395. is_useless_chunk(_) -> false.
  396. %% -> {ok, {Module, Chunks}} | throw(Error)
  397. read_significant_chunks(File, ChunkList) ->
  398. case read_chunk_data(File, ChunkList, [allow_missing_chunks]) of
  399. {ok, {Module, Chunks0}} ->
  400. Mandatory = mandatory_chunks(),
  401. Chunks = filter_significant_chunks(Chunks0, Mandatory, File, Module),
  402. {ok, {Module, Chunks}}
  403. end.
  404. filter_significant_chunks([{_, Data}=Pair|Cs], Mandatory, File, Mod)
  405. when is_binary(Data) ->
  406. [Pair|filter_significant_chunks(Cs, Mandatory, File, Mod)];
  407. filter_significant_chunks([{Id, missing_chunk}|Cs], Mandatory, File, Mod) ->
  408. case member(Id, Mandatory) of
  409. false ->
  410. filter_significant_chunks(Cs, Mandatory, File, Mod);
  411. true ->
  412. error({missing_chunk, File, Id})
  413. end;
  414. filter_significant_chunks([], _, _, _) -> [].
  415. filter_funtab([{"FunT"=Tag, <<L:4/binary, Data0/binary>>}|Cs]) ->
  416. Data = filter_funtab_1(Data0, <<0:32>>),
  417. Funtab = <<L/binary, (iolist_to_binary(Data))/binary>>,
  418. [{Tag, Funtab}|filter_funtab(Cs)];
  419. filter_funtab([H|T]) ->
  420. [H|filter_funtab(T)];
  421. filter_funtab([]) -> [].
  422. filter_funtab_1(<<Important:20/binary,_OldUniq:4/binary,T/binary>>, Zero) ->
  423. [Important,Zero|filter_funtab_1(T, Zero)];
  424. filter_funtab_1(Tail, _) when is_binary(Tail) -> [Tail].
  425. read_all_chunks(File0) when is_atom(File0);
  426. is_list(File0);
  427. is_binary(File0) ->
  428. try
  429. File = beam_filename(File0),
  430. {ok, Module, ChunkIds0} = scan_beam(File, info),
  431. ChunkIds = [Name || {Name,_,_} <- ChunkIds0],
  432. {ok, Module, Chunks} = scan_beam(File, ChunkIds),
  433. {ok, Module, lists:reverse(Chunks)}
  434. catch Error -> Error end.
  435. read_chunk_data(File0, ChunkNames) ->
  436. try read_chunk_data(File0, ChunkNames, [])
  437. catch Error -> Error end.
  438. %% -> {ok, {Module, Symbols}} | throw(Error)
  439. read_chunk_data(File0, ChunkNames0, Options)
  440. when is_atom(File0); is_list(File0); is_binary(File0) ->
  441. File = beam_filename(File0),
  442. {ChunkIds, Names, Optional} = check_chunks(ChunkNames0, File, [], [], []),
  443. AllowMissingChunks = member(allow_missing_chunks, Options),
  444. {ok, Module, Chunks} = scan_beam(File, ChunkIds, AllowMissingChunks, Optional),
  445. AT = ets:new(beam_symbols, []),
  446. T = {empty, AT},
  447. try chunks_to_data(Names, Chunks, File, Chunks, Module, T, [])
  448. after ets:delete(AT)
  449. end.
  450. %% -> {ok, list()} | throw(Error)
  451. check_chunks([atoms | Ids], File, IL, L, O) ->
  452. check_chunks(Ids, File, ["Atom", "AtU8" | IL],
  453. [{atom_chunk, atoms} | L], ["Atom", "AtU8" | O]);
  454. check_chunks([abstract_code | Ids], File, IL, L, O) ->
  455. check_chunks(Ids, File, ["Abst", "Dbgi" | IL],
  456. [{abst_chunk, abstract_code} | L], ["Abst", "Dbgi" | O]);
  457. check_chunks([ChunkName | Ids], File, IL, L, O) when is_atom(ChunkName) ->
  458. ChunkId = chunk_name_to_id(ChunkName, File),
  459. check_chunks(Ids, File, [ChunkId | IL], [{ChunkId, ChunkName} | L], O);
  460. check_chunks([ChunkId | Ids], File, IL, L, O) -> % when is_list(ChunkId)
  461. check_chunks(Ids, File, [ChunkId | IL], [{ChunkId, ChunkId} | L], O);
  462. check_chunks([], _File, IL, L, O) ->
  463. {lists:usort(IL), reverse(L), O}.
  464. %% -> {ok, Module, Data} | throw(Error)
  465. scan_beam(File, What) ->
  466. scan_beam(File, What, false, []).
  467. %% -> {ok, Module, Data} | throw(Error)
  468. scan_beam(File, What0, AllowMissingChunks, OptionalChunks) ->
  469. case scan_beam1(File, What0) of
  470. {missing, _FD, Mod, Data, What} when AllowMissingChunks ->
  471. {ok, Mod, [{Id, missing_chunk} || Id <- What] ++ Data};
  472. {missing, FD, Mod, Data, What} ->
  473. case What -- OptionalChunks of
  474. [] -> {ok, Mod, Data};
  475. [Missing | _] -> error({missing_chunk, filename(FD), Missing})
  476. end;
  477. R ->
  478. R
  479. end.
  480. %% -> {ok, Module, Data} | throw(Error)
  481. scan_beam1(File, What) ->
  482. FD = open_file(File),
  483. case catch scan_beam2(FD, What) of
  484. Error when error =:= element(1, Error) ->
  485. throw(Error);
  486. R ->
  487. R
  488. end.
  489. scan_beam2(FD, What) ->
  490. case pread(FD, 0, 12) of
  491. {NFD, {ok, <<"FOR1", _Size:32, "BEAM">>}} ->
  492. Start = 12,
  493. scan_beam(NFD, Start, What, 17, []);
  494. _Error ->
  495. error({not_a_beam_file, filename(FD)})
  496. end.
  497. scan_beam(_FD, _Pos, [], Mod, Data) when Mod =/= 17 ->
  498. {ok, Mod, Data};
  499. scan_beam(FD, Pos, What, Mod, Data) ->
  500. case pread(FD, Pos, 8) of
  501. {_NFD, eof} when Mod =:= 17 ->
  502. error({missing_chunk, filename(FD), "Atom"});
  503. {_NFD, eof} when What =:= info ->
  504. {ok, Mod, reverse(Data)};
  505. {NFD, eof} ->
  506. {missing, NFD, Mod, Data, What};
  507. {NFD, {ok, <<IdL:4/binary, Sz:32>>}} ->
  508. Id = binary_to_list(IdL),
  509. Pos1 = Pos + 8,
  510. Pos2 = (4 * trunc((Sz+3) / 4)) + Pos1,
  511. get_data(What, Id, NFD, Sz, Pos1, Pos2, Mod, Data);
  512. {_NFD, {ok, _ChunkHead}} ->
  513. error({invalid_beam_file, filename(FD), Pos})
  514. end.
  515. get_atom_data(Cs, Id, FD, Size, Pos, Pos2, Data, Encoding) ->
  516. NewCs = del_chunk(Id, Cs),
  517. {NFD, Chunk} = get_chunk(Id, Pos, Size, FD),
  518. <<_Num:32, Chunk2/binary>> = Chunk,
  519. {Module, _} = extract_atom(Chunk2, Encoding),
  520. C = case Cs of
  521. info ->
  522. {Id, Pos, Size};
  523. _ ->
  524. {Id, Chunk}
  525. end,
  526. scan_beam(NFD, Pos2, NewCs, Module, [C | Data]).
  527. get_data(Cs, "Atom" = Id, FD, Size, Pos, Pos2, _Mod, Data) ->
  528. get_atom_data(Cs, Id, FD, Size, Pos, Pos2, Data, latin1);
  529. get_data(Cs, "AtU8" = Id, FD, Size, Pos, Pos2, _Mod, Data) ->
  530. get_atom_data(Cs, Id, FD, Size, Pos, Pos2, Data, utf8);
  531. get_data(info, Id, FD, Size, Pos, Pos2, Mod, Data) ->
  532. scan_beam(FD, Pos2, info, Mod, [{Id, Pos, Size} | Data]);
  533. get_data(Chunks, Id, FD, Size, Pos, Pos2, Mod, Data) ->
  534. {NFD, NewData} = case member(Id, Chunks) of
  535. true ->
  536. {FD1, Chunk} = get_chunk(Id, Pos, Size, FD),
  537. {FD1, [{Id, Chunk} | Data]};
  538. false ->
  539. {FD, Data}
  540. end,
  541. NewChunks = del_chunk(Id, Chunks),
  542. scan_beam(NFD, Pos2, NewChunks, Mod, NewData).
  543. del_chunk(_Id, info) ->
  544. info;
  545. del_chunk(Id, Chunks) ->
  546. delete(Id, Chunks).
  547. %% -> {NFD, binary()} | throw(Error)
  548. get_chunk(Id, Pos, Size, FD) ->
  549. case pread(FD, Pos, Size) of
  550. {NFD, eof} when Size =:= 0 -> % cannot happen
  551. {NFD, <<>>};
  552. {_NFD, eof} when Size > 0 ->
  553. error({chunk_too_big, filename(FD), Id, Size, 0});
  554. {_NFD, {ok, Chunk}} when Size > byte_size(Chunk) ->
  555. error({chunk_too_big, filename(FD), Id, Size, byte_size(Chunk)});
  556. {NFD, {ok, Chunk}} -> % when Size =:= size(Chunk)
  557. {NFD, Chunk}
  558. end.
  559. chunks_to_data([{atom_chunk, Name} | CNs], Chunks, File, Cs, Module, Atoms, L) ->
  560. {NewAtoms, Ret} = chunk_to_data(Name, <<"">>, File, Cs, Atoms, Module),
  561. chunks_to_data(CNs, Chunks, File, Cs, Module, NewAtoms, [Ret | L]);
  562. chunks_to_data([{abst_chunk, Name} | CNs], Chunks, File, Cs, Module, Atoms, L) ->
  563. DbgiChunk = proplists:get_value("Dbgi", Chunks, <<"">>),
  564. {NewAtoms, Ret} =
  565. case catch chunk_to_data(debug_info, DbgiChunk, File, Cs, Atoms, Module) of
  566. {DbgiAtoms, {debug_info, {debug_info_v1, Backend, Metadata}}} ->
  567. case Backend:debug_info(erlang_v1, Module, Metadata, []) of
  568. {ok, Code} -> {DbgiAtoms, {abstract_code, {raw_abstract_v1, Code}}};
  569. {error, _} -> {DbgiAtoms, {abstract_code, no_abstract_code}}
  570. end;
  571. {error,beam_lib,{key_missing_or_invalid,Path,debug_info}} ->
  572. error({key_missing_or_invalid,Path,abstract_code});
  573. _ ->
  574. AbstChunk = proplists:get_value("Abst", Chunks, <<"">>),
  575. chunk_to_data(Name, AbstChunk, File, Cs, Atoms, Module)
  576. end,
  577. chunks_to_data(CNs, Chunks, File, Cs, Module, NewAtoms, [Ret | L]);
  578. chunks_to_data([{Id, Name} | CNs], Chunks, File, Cs, Module, Atoms, L) ->
  579. {_Id, Chunk} = lists:keyfind(Id, 1, Chunks),
  580. {NewAtoms, Ret} = chunk_to_data(Name, Chunk, File, Cs, Atoms, Module),
  581. chunks_to_data(CNs, Chunks, File, Cs, Module, NewAtoms, [Ret | L]);
  582. chunks_to_data([], _Chunks, _File, _Cs, Module, _Atoms, L) ->
  583. {ok, {Module, reverse(L)}}.
  584. chunk_to_data(attributes=Id, Chunk, File, _Cs, AtomTable, _Mod) ->
  585. try
  586. Term = binary_to_term(Chunk),
  587. {AtomTable, {Id, attributes(Term)}}
  588. catch
  589. error:badarg ->
  590. error({invalid_chunk, File, chunk_name_to_id(Id, File)})
  591. end;
  592. chunk_to_data(compile_info=Id, Chunk, File, _Cs, AtomTable, _Mod) ->
  593. try
  594. {AtomTable, {Id, binary_to_term(Chunk)}}
  595. catch
  596. error:badarg ->
  597. error({invalid_chunk, File, chunk_name_to_id(Id, File)})
  598. end;
  599. chunk_to_data(debug_info=Id, Chunk, File, _Cs, AtomTable, Mod) ->
  600. case Chunk of
  601. <<>> ->
  602. {AtomTable, {Id, no_debug_info}};
  603. <<0:8,N:8,Mode0:N/binary,Rest/binary>> ->
  604. Mode = binary_to_atom(Mode0, utf8),
  605. Term = decrypt_chunk(Mode, Mod, File, Id, Rest),
  606. {AtomTable, {Id, anno_from_term(Term)}};
  607. _ ->
  608. case catch binary_to_term(Chunk) of
  609. {'EXIT', _} ->
  610. error({invalid_chunk, File, chunk_name_to_id(Id, File)});
  611. Term ->
  612. {AtomTable, {Id, anno_from_term(Term)}}
  613. end
  614. end;
  615. chunk_to_data(abstract_code=Id, Chunk, File, _Cs, AtomTable, Mod) ->
  616. %% Before Erlang/OTP 20.0.
  617. case Chunk of
  618. <<>> ->
  619. {AtomTable, {Id, no_abstract_code}};
  620. <<0:8,N:8,Mode0:N/binary,Rest/binary>> ->
  621. Mode = binary_to_atom(Mode0, utf8),
  622. Term = decrypt_chunk(Mode, Mod, File, Id, Rest),
  623. {AtomTable, {Id, old_anno_from_term(Term)}};
  624. _ ->
  625. case catch binary_to_term(Chunk) of
  626. {'EXIT', _} ->
  627. error({invalid_chunk, File, chunk_name_to_id(Id, File)});
  628. Term ->
  629. try
  630. {AtomTable, {Id, old_anno_from_term(Term)}}
  631. catch
  632. _:_ ->
  633. error({invalid_chunk, File,
  634. chunk_name_to_id(Id, File)})
  635. end
  636. end
  637. end;
  638. chunk_to_data(atoms=Id, _Chunk, _File, Cs, AtomTable0, _Mod) ->
  639. AtomTable = ensure_atoms(AtomTable0, Cs),
  640. Atoms = ets:tab2list(AtomTable),
  641. {AtomTable, {Id, lists:sort(Atoms)}};
  642. chunk_to_data(ChunkName, Chunk, File,
  643. Cs, AtomTable, _Mod) when is_atom(ChunkName) ->
  644. case catch symbols(Chunk, AtomTable, Cs, ChunkName) of
  645. {ok, NewAtomTable, S} ->
  646. {NewAtomTable, {ChunkName, S}};
  647. {'EXIT', _} ->
  648. error({invalid_chunk, File, chunk_name_to_id(ChunkName, File)})
  649. end;
  650. chunk_to_data(ChunkId, Chunk, _File,
  651. _Cs, AtomTable, _Module) when is_list(ChunkId) ->
  652. {AtomTable, {ChunkId, Chunk}}. % Chunk is a binary
  653. chunk_name_to_id(indexed_imports, _) -> "ImpT";
  654. chunk_name_to_id(imports, _) -> "ImpT";
  655. chunk_name_to_id(exports, _) -> "ExpT";
  656. chunk_name_to_id(labeled_exports, _) -> "ExpT";
  657. chunk_name_to_id(locals, _) -> "LocT";
  658. chunk_name_to_id(labeled_locals, _) -> "LocT";
  659. chunk_name_to_id(attributes, _) -> "Attr";
  660. chunk_name_to_id(abstract_code, _) -> "Abst";
  661. chunk_name_to_id(debug_info, _) -> "Dbgi";
  662. chunk_name_to_id(compile_info, _) -> "CInf";
  663. chunk_name_to_id(Other, File) ->
  664. error({unknown_chunk, File, Other}).
  665. %% Extract attributes
  666. attributes(Attrs) ->
  667. attributes(keysort(1, Attrs), []).
  668. attributes([], R) ->
  669. reverse(R);
  670. attributes(L, R) ->
  671. K = element(1, hd(L)),
  672. {L1, L2} = splitwith(fun(T) -> element(1, T) =:= K end, L),
  673. V = append([A || {_, A} <- L1]),
  674. attributes(L2, [{K, V} | R]).
  675. %% Extract symbols
  676. symbols(<<_Num:32, B/binary>>, AT0, Cs, Name) ->
  677. AT = ensure_atoms(AT0, Cs),
  678. symbols1(B, AT, Name, [], 1).
  679. symbols1(<<I1:32, I2:32, I3:32, B/binary>>, AT, Name, S, Cnt) ->
  680. Symbol = symbol(Name, AT, I1, I2, I3, Cnt),
  681. symbols1(B, AT, Name, [Symbol|S], Cnt+1);
  682. symbols1(<<>>, AT, _Name, S, _Cnt) ->
  683. {ok, AT, sort(S)}.
  684. symbol(indexed_imports, AT, I1, I2, I3, Cnt) ->
  685. {Cnt, atm(AT, I1), atm(AT, I2), I3};
  686. symbol(imports, AT, I1, I2, I3, _Cnt) ->
  687. {atm(AT, I1), atm(AT, I2), I3};
  688. symbol(labeled_exports, AT, I1, I2, I3, _Cnt) ->
  689. {atm(AT, I1), I2, I3};
  690. symbol(labeled_locals, AT, I1, I2, I3, _Cnt) ->
  691. {atm(AT, I1), I2, I3};
  692. symbol(_, AT, I1, I2, _I3, _Cnt) ->
  693. {atm(AT, I1), I2}.
  694. atm(AT, N) ->
  695. [{_N, S}] = ets:lookup(AT, N),
  696. S.
  697. %% AT is updated.
  698. ensure_atoms({empty, AT}, Cs) ->
  699. case lists:keyfind("AtU8", 1, Cs) of
  700. {_Id, AtomChunk} when is_binary(AtomChunk) ->
  701. extract_atoms(AtomChunk, AT, utf8);
  702. _ ->
  703. {_Id, AtomChunk} = lists:keyfind("Atom", 1, Cs),
  704. extract_atoms(AtomChunk, AT, latin1)
  705. end,
  706. AT;
  707. ensure_atoms(AT, _Cs) ->
  708. AT.
  709. extract_atoms(<<_Num:32, B/binary>>, AT, Encoding) ->
  710. extract_atoms(B, 1, AT, Encoding).
  711. extract_atoms(<<>>, _I, _AT, _Encoding) ->
  712. true;
  713. extract_atoms(B, I, AT, Encoding) ->
  714. {Atom, B1} = extract_atom(B, Encoding),
  715. true = ets:insert(AT, {I, Atom}),
  716. extract_atoms(B1, I+1, AT, Encoding).
  717. extract_atom(<<Len, B/binary>>, Encoding) ->
  718. <<SB:Len/binary, Tail/binary>> = B,
  719. {binary_to_atom(SB, Encoding), Tail}.
  720. %%% Utils.
  721. -record(bb, {pos = 0 :: integer(),
  722. bin :: binary(),
  723. source :: binary() | string()}).
  724. open_file(<<"FOR1",_/binary>>=Binary) ->
  725. #bb{bin = Binary, source = Binary};
  726. open_file(Binary0) when is_binary(Binary0) ->
  727. Binary = uncompress(Binary0),
  728. #bb{bin = Binary, source = Binary};
  729. open_file(FileName) ->
  730. case file:open(FileName, [read, raw, binary]) of
  731. {ok, Fd} ->
  732. read_all(Fd, FileName, []);
  733. Error ->
  734. file_error(FileName, Error)
  735. end.
  736. read_all(Fd, FileName, Bins) ->
  737. case file:read(Fd, 1 bsl 18) of
  738. {ok, Bin} ->
  739. read_all(Fd, FileName, [Bin | Bins]);
  740. eof ->
  741. ok = file:close(Fd),
  742. #bb{bin = uncompress(reverse(Bins)), source = FileName};
  743. Error ->
  744. ok = file:close(Fd),
  745. file_error(FileName, Error)
  746. end.
  747. pread(FD, AtPos, Size) ->
  748. #bb{pos = Pos, bin = Binary} = FD,
  749. Skip = AtPos-Pos,
  750. case Binary of
  751. <<_:Skip/binary, B:Size/binary, Bin/binary>> ->
  752. NFD = FD#bb{pos = AtPos+Size, bin = Bin},
  753. {NFD, {ok, B}};
  754. <<_:Skip/binary, Bin/binary>> when byte_size(Bin) > 0 ->
  755. NFD = FD#bb{pos = AtPos+byte_size(Bin), bin = <<>>},
  756. {NFD, {ok, Bin}};
  757. _ ->
  758. {FD, eof}
  759. end.
  760. filename(BB) when is_binary(BB#bb.source) ->
  761. BB#bb.source;
  762. filename(BB) ->
  763. list_to_atom(BB#bb.source).
  764. beam_filename(Bin) when is_binary(Bin) ->
  765. Bin;
  766. beam_filename(File) ->
  767. filename:rootname(File, ".beam") ++ ".beam".
  768. uncompress(Binary0) ->
  769. {ok, Fd} = ram_file:open(Binary0, [write, binary]),
  770. {ok, _} = ram_file:uncompress(Fd),
  771. {ok, Binary} = ram_file:get_file(Fd),
  772. ok = ram_file:close(Fd),
  773. Binary.
  774. compress(Binary0) ->
  775. {ok, Fd} = ram_file:open(Binary0, [write, binary]),
  776. {ok, _} = ram_file:compress(Fd),
  777. {ok, Binary} = ram_file:get_file(Fd),
  778. ok = ram_file:close(Fd),
  779. Binary.
  780. %% -> ok | throw(Error)
  781. assert_directory(FileName) ->
  782. case filelib:is_dir(FileName) of
  783. true ->
  784. ok;
  785. false ->
  786. error({not_a_directory, FileName})
  787. end.
  788. -spec file_error(file:filename(), {'error',atom()}) -> no_return().
  789. file_error(FileName, {error, Reason}) ->
  790. error({file_error, FileName, Reason}).
  791. -spec error(term()) -> no_return().
  792. error(Reason) ->
  793. throw({error, ?MODULE, Reason}).
  794. %% The following chunks must be kept when stripping a BEAM file.
  795. significant_chunks() ->
  796. ["Line" | md5_chunks()].
  797. %% The following chunks are significant when calculating the MD5
  798. %% for a module. They are listed in the order that they should be MD5:ed.
  799. md5_chunks() ->
  800. ["Atom", "AtU8", "Code", "StrT", "ImpT", "ExpT", "FunT", "LitT"].
  801. %% The following chunks are mandatory in every Beam file.
  802. mandatory_chunks() ->
  803. ["Code", "ExpT", "ImpT", "StrT"].
  804. %%% ====================================================================
  805. %%% The rest of the file handles encrypted debug info.
  806. %%%
  807. %%% Encrypting the debug info is only useful if you want to
  808. %%% have the debug info available all the time (maybe even in a live
  809. %%% system), but don't want to risk that anyone else but yourself
  810. %%% can use it.
  811. %%% ====================================================================
  812. -record(state, {crypto_key_f :: crypto_fun() | 'undefined'}).
  813. -define(CRYPTO_KEY_SERVER, beam_lib__crypto_key_server).
  814. decrypt_chunk(Type, Module, File, Id, Bin) ->
  815. try
  816. KeyString = get_crypto_key({debug_info, Type, Module, File}),
  817. {Type,Key,IVec,_BlockSize} = make_crypto_key(Type, KeyString),
  818. ok = start_crypto(),
  819. NewBin = crypto:block_decrypt(Type, Key, IVec, Bin),
  820. binary_to_term(NewBin)
  821. catch
  822. _:_ ->
  823. error({key_missing_or_invalid, File, Id})
  824. end.
  825. old_anno_from_term({raw_abstract_v1, Forms}) ->
  826. {raw_abstract_v1, anno_from_forms(Forms)};
  827. old_anno_from_term({Tag, Forms}) when Tag =:= abstract_v1;
  828. Tag =:= abstract_v2 ->
  829. try {Tag, anno_from_forms(Forms)}
  830. catch
  831. _:_ ->
  832. {Tag, Forms}
  833. end;
  834. old_anno_from_term(T) ->
  835. T.
  836. anno_from_term({debug_info_v1=Tag1, erl_abstract_code=Tag2, {Forms, Opts}}) ->
  837. try {Tag1, Tag2, {anno_from_forms(Forms), Opts}}
  838. catch
  839. _:_ ->
  840. {Tag1, Tag2, {Forms, Opts}}
  841. end;
  842. anno_from_term(T) ->
  843. T.
  844. anno_from_forms(Forms0) ->
  845. %% Forms with record field types created before OTP 19.0 are
  846. %% replaced by well-formed record forms holding the type
  847. %% information.
  848. Forms = epp:restore_typed_record_fields(Forms0),
  849. [erl_parse:anno_from_term(Form) || Form <- Forms].
  850. start_crypto() ->
  851. case crypto:start() of
  852. {error, {already_started, _}} ->
  853. ok;
  854. ok ->
  855. ok
  856. end.
  857. get_crypto_key(What) ->
  858. call_crypto_server({get_crypto_key, What}).
  859. call_crypto_server(Req) ->
  860. try
  861. gen_server:call(?CRYPTO_KEY_SERVER, Req, infinity)
  862. catch
  863. exit:{noproc,_} ->
  864. %% Not started.
  865. call_crypto_server_1(Req);
  866. exit:{normal,_} ->
  867. %% The process finished just as we called it.
  868. call_crypto_server_1(Req)
  869. end.
  870. call_crypto_server_1(Req) ->
  871. case gen_server:start({local,?CRYPTO_KEY_SERVER}, ?MODULE, [], []) of
  872. {ok, _} -> ok;
  873. {error, {already_started, _}} -> ok
  874. end,
  875. erlang:yield(),
  876. call_crypto_server(Req).
  877. -spec init([]) -> {'ok', #state{}}.
  878. init([]) ->
  879. {ok, #state{}}.
  880. -type calls() :: 'clear_crypto_key_fun'
  881. | {'crypto_key_fun', _}
  882. | {'get_crypto_key', _}.
  883. -spec handle_call(calls(), {pid(), term()}, #state{}) ->
  884. {'noreply', #state{}} |
  885. {'reply', 'error' | {'error','badfun' | 'exists'}, #state{}} |
  886. {'stop', 'normal', 'undefined' | {'ok', term()}, #state{}}.
  887. handle_call({get_crypto_key, _}=R, From, #state{crypto_key_f=undefined}=S) ->
  888. case crypto_key_fun_from_file() of
  889. error ->
  890. {reply, error, S};
  891. F when is_function(F) ->
  892. %% The init function for the fun has already been called.
  893. handle_call(R, From, S#state{crypto_key_f=F})
  894. end;
  895. handle_call({get_crypto_key, What}, From, #state{crypto_key_f=F}=S) ->
  896. try
  897. Result = F(What),
  898. %% The result may hold information that we don't want
  899. %% lying around. Reply first, then GC, then noreply.
  900. gen_server:reply(From, Result),
  901. erlang:garbage_collect(),
  902. {noreply, S}
  903. catch
  904. _:_ ->
  905. {reply, error, S}
  906. end;
  907. handle_call({crypto_key_fun, F}, {_,_} = From, S) ->
  908. case S#state.crypto_key_f of
  909. undefined ->
  910. if is_function(F, 1) ->
  911. {Result, Fun, Reply} =
  912. case catch F(init) of
  913. ok ->
  914. {true, F, ok};
  915. {ok, F1} when is_function(F1) ->
  916. if
  917. is_function(F1, 1) ->
  918. {true, F1, ok};
  919. true ->
  920. {false, undefined,
  921. {error, badfun}}
  922. end;
  923. {error, Reason} ->
  924. {false, undefined, {error, Reason}};
  925. {'EXIT', Reason} ->
  926. {false, undefined, {error, Reason}}
  927. end,
  928. gen_server:reply(From, Reply),
  929. erlang:garbage_collect(),
  930. NewS = case Result of
  931. true ->
  932. S#state{crypto_key_f = Fun};
  933. false ->
  934. S
  935. end,
  936. {noreply, NewS};
  937. true ->
  938. {reply, {error, badfun}, S}
  939. end;
  940. OtherF when is_function(OtherF) ->
  941. {reply, {error, exists}, S}
  942. end;
  943. handle_call(clear_crypto_key_fun, _From, S) ->
  944. case S#state.crypto_key_f of
  945. undefined ->
  946. {stop,normal,undefined,S};
  947. F ->
  948. Result = (catch F(clear)),
  949. {stop,normal,{ok,Result},S}
  950. end.
  951. -spec handle_cast(term(), #state{}) -> {'noreply', #state{}}.
  952. handle_cast(_, State) ->
  953. {noreply, State}.
  954. -spec handle_info(term(), #state{}) -> {'noreply', #state{}}.
  955. handle_info(_, State) ->
  956. {noreply, State}.
  957. -spec code_change(term(), #state{}, term()) -> {'ok', #state{}}.
  958. code_change(_OldVsn, State, _Extra) ->
  959. {ok, State}.
  960. -spec terminate(term(), #state{}) -> 'ok'.
  961. terminate(_Reason, _State) ->
  962. ok.
  963. crypto_key_fun_from_file() ->
  964. case init:get_argument(home) of
  965. {ok,[[Home]]} ->
  966. crypto_key_fun_from_file_1([".",Home]);
  967. _ ->
  968. crypto_key_fun_from_file_1(["."])
  969. end.
  970. crypto_key_fun_from_file_1(Path) ->
  971. case f_p_s(Path, ".erlang.crypt") of
  972. {ok, KeyInfo, _} ->
  973. try_load_crypto_fun(KeyInfo);
  974. _ ->
  975. error
  976. end.
  977. f_p_s(P, F) ->
  978. case file:path_script(P, F) of
  979. {error, enoent} ->
  980. {error, enoent};
  981. {error, {Line, _Mod, _Term}=E} ->
  982. error("file:path_script(~tp,~tp): error on line ~p: ~ts~n",
  983. [P, F, Line, file:format_error(E)]),
  984. ok;
  985. {error, E} when is_atom(E) ->
  986. error("file:path_script(~tp,~tp): ~ts~n",
  987. [P, F, file:format_error(E)]),
  988. ok;
  989. Other ->
  990. Other
  991. end.
  992. try_load_crypto_fun(KeyInfo) when is_list(KeyInfo) ->
  993. T = ets:new(keys, [private, set]),
  994. foreach(
  995. fun({debug_info, Mode, M, Key}) when is_atom(M) ->
  996. ets:insert(T, {{debug_info,Mode,M,[]}, Key});
  997. ({debug_info, Mode, [], Key}) ->
  998. ets:insert(T, {{debug_info, Mode, [], []}, Key});
  999. (Other) ->
  1000. error("unknown key: ~p~n", [Other])
  1001. end, KeyInfo),
  1002. fun({debug_info, Mode, M, F}) ->
  1003. alt_lookup_key(
  1004. [{debug_info,Mode,M,F},
  1005. {debug_info,Mode,M,[]},
  1006. {debug_info,Mode,[],[]}], T);
  1007. (clear) ->
  1008. ets:delete(T);
  1009. (_) ->
  1010. error
  1011. end;
  1012. try_load_crypto_fun(KeyInfo) ->
  1013. error("unrecognized crypto key info: ~p\n", [KeyInfo]).
  1014. alt_lookup_key([H|T], Tab) ->
  1015. case ets:lookup(Tab, H) of
  1016. [] ->
  1017. alt_lookup_key(T, Tab);
  1018. [{_, Val}] ->
  1019. Val
  1020. end;
  1021. alt_lookup_key([], _) ->
  1022. error.
  1023. error(Fmt, Args) ->
  1024. error_logger:error_msg(Fmt, Args),
  1025. error.