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. OldPath = code:get_path(),
  32. code:add_pathsa(rebar_state:code_paths(State, all_deps)),
  33. XrefChecks = prepare(State),
  34. XrefIgnores = rebar_state:get(State, xref_ignores, []),
  35. %% Run xref checks
  36. ?INFO("Running cross reference analysis...", []),
  37. XrefResults = xref_checks(XrefChecks, XrefIgnores),
  38. %% Run custom queries
  39. QueryChecks = rebar_state:get(State, xref_queries, []),
  40. QueryResults = lists:foldl(fun check_query/2, [], QueryChecks),
  41. stopped = xref:stop(xref),
  42. rebar_utils:cleanup_code_path(OldPath),
  43. case XrefResults =:= [] andalso QueryResults =:= [] of
  44. true ->
  45. {ok, State};
  46. false ->
  47. ?PRV_ERROR({xref_issues, XrefResults, QueryResults})
  48. end.
  49. -spec format_error(any()) -> iolist().
  50. format_error({xref_issues, XrefResults, QueryResults}) ->
  51. lists:flatten(display_results(XrefResults, QueryResults));
  52. format_error(Reason) ->
  53. io_lib:format("~p", [Reason]).
  54. %% ===================================================================
  55. %% Internal functions
  56. %% ===================================================================
  57. short_desc() ->
  58. "Run cross reference analysis.".
  59. desc() ->
  60. io_lib:format(
  61. "~ts~n"
  62. "~n"
  63. "Valid rebar.config options:~n"
  64. " ~p~n"
  65. " ~p~n"
  66. " ~p~n"
  67. " ~p~n",
  68. [short_desc(),
  69. {xref_warnings, false},
  70. {xref_extra_paths,[]},
  71. {xref_checks, [undefined_function_calls, undefined_functions,
  72. locals_not_used, exports_not_used,
  73. deprecated_function_calls, deprecated_functions]},
  74. {xref_queries,
  75. [{"(xc - uc) || (xu - x - b"
  76. " - (\"mod\":\".*foo\"/\"4\"))",[]}]}
  77. ]).
  78. -spec prepare(rebar_state:t()) -> [atom()].
  79. prepare(State) ->
  80. {ok, _} = xref:start(xref),
  81. ok = xref:set_library_path(xref, code_path(State)),
  82. xref:set_default(xref, [{warnings,
  83. rebar_state:get(State, xref_warnings, false)},
  84. {verbose, rebar_log:is_verbose(State)}]),
  85. [{ok, _} = xref:add_directory(xref, Dir)
  86. || App <- rebar_state:project_apps(State),
  87. %% the directory may not exist in rare cases of a compile
  88. %% hook of a dep running xref prior to the full job being done
  89. Dir <- [rebar_app_info:ebin_dir(App)], filelib:is_dir(Dir)],
  90. %% Get list of xref checks we want to run
  91. ConfXrefChecks = rebar_state:get(State, xref_checks,
  92. [exports_not_used,
  93. undefined_function_calls]),
  94. XrefChecks = sets:to_list(sets:intersection(
  95. sets:from_list(?SUPPORTED_XREFS),
  96. sets:from_list(ConfXrefChecks))),
  97. XrefChecks.
  98. xref_checks(XrefChecks, XrefIgnores) ->
  99. run_xref_checks(XrefChecks, XrefIgnores, []).
  100. run_xref_checks([], _XrefIgnores, Acc) ->
  101. Acc;
  102. run_xref_checks([XrefCheck | T], XrefIgnores, Acc) ->
  103. {ok, Results} = xref:analyze(xref, XrefCheck),
  104. case filter_xref_results(XrefCheck, XrefIgnores, Results) of
  105. [] ->
  106. run_xref_checks(T, XrefIgnores, Acc);
  107. FilterResult ->
  108. run_xref_checks(T, XrefIgnores, [{XrefCheck, FilterResult} | Acc])
  109. end.
  110. check_query({Query, Value}, Acc) ->
  111. {ok, Answer} = xref:q(xref, Query),
  112. case Answer =:= Value of
  113. false ->
  114. [{Query, Value, Answer} | Acc];
  115. _ ->
  116. Acc
  117. end.
  118. code_path(State) ->
  119. [P || P <- code:get_path() ++
  120. rebar_state:get(State, xref_extra_paths, []),
  121. filelib:is_dir(P)].
  122. %% Ignore behaviour functions, and explicitly marked functions
  123. %%
  124. %% Functions can be ignored by using
  125. %% -ignore_xref([{F, A}, {M, F, A}...]).
  126. get_xref_ignorelist(Mod, XrefCheck) ->
  127. %% Get ignore_xref attribute and combine them in one list
  128. Attributes =
  129. try
  130. Mod:module_info(attributes)
  131. catch
  132. _Class:_Error -> []
  133. end,
  134. IgnoreXref = keyall(ignore_xref, Attributes),
  135. BehaviourCallbacks = get_behaviour_callbacks(XrefCheck, Attributes),
  136. %% And create a flat {M,F,A} list
  137. lists:foldl(
  138. fun({F, A}, Acc) -> [{Mod,F,A} | Acc];
  139. ({M, F, A}, Acc) -> [{M,F,A} | Acc]
  140. end, [], lists:flatten([IgnoreXref, BehaviourCallbacks])).
  141. keyall(Key, List) ->
  142. lists:flatmap(fun({K, L}) when Key =:= K -> L; (_) -> [] end, List).
  143. get_behaviour_callbacks(exports_not_used, Attributes) ->
  144. lists:map(fun(Mod) ->
  145. try
  146. Mod:behaviour_info(callbacks)
  147. catch
  148. error:undef ->
  149. ?WARN("Behaviour ~p is used but cannot be found.", [Mod]),
  150. []
  151. end
  152. end, keyall(behaviour, Attributes) ++ keyall(behavior, Attributes));
  153. get_behaviour_callbacks(_XrefCheck, _Attributes) ->
  154. [].
  155. parse_xref_result({_, MFAt}) -> MFAt;
  156. parse_xref_result(MFAt) -> MFAt.
  157. filter_xref_results(XrefCheck, XrefIgnores, XrefResults) ->
  158. SearchModules = lists:usort(
  159. lists:map(
  160. fun({Mt,_Ft,_At}) -> Mt;
  161. ({{Ms,_Fs,_As},{_Mt,_Ft,_At}}) -> Ms;
  162. (_) -> undefined
  163. end, XrefResults)),
  164. Ignores = XrefIgnores ++ lists:flatmap(fun(Module) ->
  165. get_xref_ignorelist(Module, XrefCheck)
  166. end, SearchModules),
  167. [Result || Result <- XrefResults,
  168. 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.