You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
11 KiB

  1. %% -*- erlang-indent-level: 4;indent-tabs-mode: nil -*-
  2. %% ex: ts=4 sw=4 et
  3. -module(rebar_prv_xref).
  4. -behaviour(provider).
  5. -export([init/1,
  6. do/1,
  7. format_error/1]).
  8. -include("rebar.hrl").
  9. -include_lib("providers/include/providers.hrl").
  10. -define(PROVIDER, xref).
  11. -define(DEPS, [compile]).
  12. -define(SUPPORTED_XREFS, [undefined_function_calls, undefined_functions,
  13. locals_not_used, exports_not_used,
  14. deprecated_function_calls, deprecated_functions]).
  15. %% ===================================================================
  16. %% Public API
  17. %% ===================================================================
  18. -spec init(rebar_state:t()) -> {ok, rebar_state:t()}.
  19. init(State) ->
  20. Provider = providers:create([{name, ?PROVIDER},
  21. {module, ?MODULE},
  22. {deps, ?DEPS},
  23. {bare, true},
  24. {example, "rebar3 xref"},
  25. {short_desc, short_desc()},
  26. {desc, desc()}]),
  27. State1 = rebar_state:add_provider(State, Provider),
  28. {ok, State1}.
  29. -spec do(rebar_state:t()) -> {ok, rebar_state:t()} | {error, string()}.
  30. do(State) ->
  31. rebar_paths:set_paths([deps], State),
  32. XrefChecks = prepare(State),
  33. XrefIgnores = rebar_state:get(State, xref_ignores, []),
  34. %% Run xref checks
  35. ?INFO("Running cross reference analysis...", []),
  36. XrefResults = xref_checks(XrefChecks, XrefIgnores),
  37. %% Run custom queries
  38. QueryChecks = rebar_state:get(State, xref_queries, []),
  39. QueryResults = lists:foldl(fun check_query/2, [], QueryChecks),
  40. stopped = xref:stop(xref),
  41. case XrefResults =:= [] andalso QueryResults =:= [] of
  42. true ->
  43. {ok, State};
  44. false ->
  45. ?PRV_ERROR({xref_issues, XrefResults, QueryResults})
  46. end.
  47. -spec format_error(any()) -> iolist().
  48. format_error({xref_issues, XrefResults, QueryResults}) ->
  49. lists:flatten(display_results(XrefResults, QueryResults));
  50. format_error(Reason) ->
  51. io_lib:format("~p", [Reason]).
  52. %% ===================================================================
  53. %% Internal functions
  54. %% ===================================================================
  55. short_desc() ->
  56. "Run cross reference analysis.".
  57. desc() ->
  58. io_lib:format(
  59. "~ts~n"
  60. "~n"
  61. "Valid rebar.config options:~n"
  62. " ~p~n"
  63. " ~p~n"
  64. " ~p~n"
  65. " ~p~n",
  66. [short_desc(),
  67. {xref_warnings, false},
  68. {xref_extra_paths,[]},
  69. {xref_checks, [undefined_function_calls, undefined_functions,
  70. locals_not_used, exports_not_used,
  71. deprecated_function_calls, deprecated_functions]},
  72. {xref_queries,
  73. [{"(xc - uc) || (xu - x - b"
  74. " - (\"mod\":\".*foo\"/\"4\"))",[]}]}
  75. ]).
  76. -spec prepare(rebar_state:t()) -> [atom()].
  77. prepare(State) ->
  78. {ok, _} = xref:start(xref),
  79. ok = xref:set_library_path(xref, code_path(State)),
  80. xref:set_default(xref, [{warnings,
  81. rebar_state:get(State, xref_warnings, false)},
  82. {verbose, rebar_log:is_verbose(State)}]),
  83. [{ok, _} = xref:add_directory(xref, Dir)
  84. || App <- rebar_state:project_apps(State),
  85. %% the directory may not exist in rare cases of a compile
  86. %% hook of a dep running xref prior to the full job being done
  87. Dir <- [rebar_app_info:ebin_dir(App)], filelib:is_dir(Dir)],
  88. %% Get list of xref checks we want to run
  89. ConfXrefChecks = rebar_state:get(State, xref_checks,
  90. [exports_not_used,
  91. undefined_function_calls]),
  92. XrefChecks = sets:to_list(sets:intersection(
  93. sets:from_list(?SUPPORTED_XREFS),
  94. sets:from_list(ConfXrefChecks))),
  95. XrefChecks.
  96. xref_checks(XrefChecks, XrefIgnores) ->
  97. run_xref_checks(XrefChecks, XrefIgnores, []).
  98. run_xref_checks([], _XrefIgnores, Acc) ->
  99. Acc;
  100. run_xref_checks([XrefCheck | T], XrefIgnores, Acc) ->
  101. {ok, Results} = xref:analyze(xref, XrefCheck),
  102. case filter_xref_results(XrefCheck, XrefIgnores, Results) of
  103. [] ->
  104. run_xref_checks(T, XrefIgnores, Acc);
  105. FilterResult ->
  106. run_xref_checks(T, XrefIgnores, [{XrefCheck, FilterResult} | Acc])
  107. end.
  108. check_query({Query, Value}, Acc) ->
  109. {ok, Answer} = xref:q(xref, Query),
  110. case Answer =:= Value of
  111. false ->
  112. [{Query, Value, Answer} | Acc];
  113. _ ->
  114. Acc
  115. end.
  116. code_path(State) ->
  117. [P || P <- code:get_path() ++
  118. rebar_state:get(State, xref_extra_paths, []),
  119. filelib:is_dir(P)].
  120. %% Ignore behaviour functions, and explicitly marked functions
  121. %%
  122. %% Functions can be ignored by using
  123. %% -ignore_xref([{F, A}, {M, F, A}...]).
  124. get_xref_ignorelist(Mod, XrefCheck) ->
  125. %% Get ignore_xref attribute and combine them in one list
  126. Attributes =
  127. try
  128. Mod:module_info(attributes)
  129. catch
  130. _Class:_Error -> []
  131. end,
  132. IgnoreXref = keyall(ignore_xref, Attributes),
  133. BehaviourCallbacks = get_behaviour_callbacks(XrefCheck, Attributes),
  134. %% And create a flat {M,F,A} list
  135. lists:foldl(
  136. fun({F, A}, Acc) -> [{Mod,F,A} | Acc];
  137. ({M, F, A}, Acc) -> [{M,F,A} | Acc];
  138. (M, Acc) when is_atom(M) -> [M | Acc]
  139. end, [], lists:flatten([IgnoreXref, BehaviourCallbacks])).
  140. keyall(Key, List) ->
  141. lists:flatmap(fun({K, L}) when Key =:= K -> L; (_) -> [] end, List).
  142. get_behaviour_callbacks(exports_not_used, Attributes) ->
  143. lists:map(fun(Mod) ->
  144. try
  145. Mod:behaviour_info(callbacks)
  146. catch
  147. error:undef ->
  148. ?WARN("Behaviour ~p is used but cannot be found.", [Mod]),
  149. []
  150. end
  151. end, keyall(behaviour, Attributes) ++ keyall(behavior, Attributes));
  152. get_behaviour_callbacks(_XrefCheck, _Attributes) ->
  153. [].
  154. parse_xref_result({_, MFAt}) -> MFAt;
  155. parse_xref_result(MFAt) -> MFAt.
  156. filter_xref_results(XrefCheck, XrefIgnores, XrefResults) ->
  157. SearchModules = lists:usort(
  158. lists:map(
  159. fun({Mt,_Ft,_At}) -> Mt;
  160. ({{Ms,_Fs,_As},{_Mt,_Ft,_At}}) -> Ms;
  161. (_) -> undefined
  162. end, XrefResults)),
  163. Ignores = XrefIgnores ++ lists:flatmap(fun(Module) ->
  164. get_xref_ignorelist(Module, XrefCheck)
  165. end, SearchModules),
  166. [Result || Result <- XrefResults,
  167. not lists:member(element(1, Result), Ignores)
  168. andalso not lists:member(parse_xref_result(Result), Ignores)].
  169. display_results(XrefResults, QueryResults) ->
  170. [lists:map(fun display_xref_results_for_type/1, XrefResults),
  171. lists:map(fun display_query_result/1, QueryResults)].
  172. display_query_result({Query, Answer, Value}) ->
  173. io_lib:format("Query ~ts~n answer ~p~n did not match ~p~n",
  174. [Query, Answer, Value]).
  175. display_xref_results_for_type({Type, XrefResults}) ->
  176. lists:map(display_xref_result_fun(Type), XrefResults).
  177. display_xref_result_fun(Type) ->
  178. fun(XrefResult) ->
  179. {Source, SMFA, TMFA} =
  180. case XrefResult of
  181. {MFASource, MFATarget} ->
  182. {format_mfa_source(MFASource),
  183. format_mfa(MFASource),
  184. format_mfa(MFATarget)};
  185. MFATarget ->
  186. {format_mfa_source(MFATarget),
  187. format_mfa(MFATarget),
  188. undefined}
  189. end,
  190. case Type of
  191. undefined_function_calls ->
  192. io_lib:format("~tsWarning: ~ts calls undefined function ~ts (Xref)\n",
  193. [Source, SMFA, TMFA]);
  194. undefined_functions ->
  195. io_lib:format("~tsWarning: ~ts is undefined function (Xref)\n",
  196. [Source, SMFA]);
  197. locals_not_used ->
  198. io_lib:format("~tsWarning: ~ts is unused local function (Xref)\n",
  199. [Source, SMFA]);
  200. exports_not_used ->
  201. io_lib:format("~tsWarning: ~ts is unused export (Xref)\n",
  202. [Source, SMFA]);
  203. deprecated_function_calls ->
  204. io_lib:format("~tsWarning: ~ts calls deprecated function ~ts (Xref)\n",
  205. [Source, SMFA, TMFA]);
  206. deprecated_functions ->
  207. io_lib:format("~tsWarning: ~ts is deprecated function (Xref)\n",
  208. [Source, SMFA]);
  209. Other ->
  210. io_lib:format("~tsWarning: ~ts - ~ts xref check: ~ts (Xref)\n",
  211. [Source, SMFA, TMFA, Other])
  212. end
  213. end.
  214. format_mfa({M, F, A}) ->
  215. ?FMT("~ts:~ts/~w", [M, F, A]).
  216. format_mfa_source(MFA) ->
  217. case find_mfa_source(MFA) of
  218. {module_not_found, function_not_found} -> "";
  219. {Source, function_not_found} -> ?FMT("~ts: ", [Source]);
  220. {Source, Line} -> ?FMT("~ts:~w: ", [Source, Line])
  221. end.
  222. %%
  223. %% Extract an element from a tuple, or undefined if N > tuple size
  224. %%
  225. safe_element(N, Tuple) ->
  226. try
  227. element(N, Tuple)
  228. catch
  229. error:badarg ->
  230. undefined
  231. end.
  232. %%
  233. %% Given a MFA, find the file and LOC where it's defined. Note that
  234. %% xref doesn't work if there is no abstract_code, so we can avoid
  235. %% being too paranoid here.
  236. %%
  237. find_mfa_source({M, F, A}) ->
  238. case code:get_object_code(M) of
  239. error -> {module_not_found, function_not_found};
  240. {M, Bin, _} -> find_function_source(M,F,A,Bin)
  241. end.
  242. find_function_source(M, F, A, Bin) ->
  243. ChunksLookup = beam_lib:chunks(Bin, [abstract_code]),
  244. {ok, {M, [{abstract_code, AbstractCodeLookup}]}} = ChunksLookup,
  245. case AbstractCodeLookup of
  246. no_abstract_code ->
  247. % There isn't much else we can do at this point
  248. {module_not_found, function_not_found};
  249. {raw_abstract_v1, AbstractCode} ->
  250. find_function_source_in_abstract_code(F, A, AbstractCode)
  251. end.
  252. find_function_source_in_abstract_code(F, A, AbstractCode) ->
  253. %% Extract the original source filename from the abstract code
  254. [{attribute, _, file, {Source, _}} | _] = AbstractCode,
  255. %% Extract the line number for a given function def
  256. Fn = [E || E <- AbstractCode,
  257. safe_element(1, E) == function,
  258. safe_element(3, E) == F,
  259. safe_element(4, E) == A],
  260. case Fn of
  261. [{function, Line, F, _, _}] -> {Source, Line};
  262. %% do not crash if functions are exported, even though they
  263. %% are not in the source.
  264. %% parameterized modules add new/1 and instance/1 for example.
  265. [] -> {Source, function_not_found}
  266. end.