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.

274 line
10 KiB

  1. %% -------------------------------------------------------------------
  2. %%
  3. %% rebar: Erlang Build Tools
  4. %%
  5. %% Copyright (c) 2009 Dave Smith (dizzyd@dizzyd.com)
  6. %%
  7. %% Permission is hereby granted, free of charge, to any person obtaining a copy
  8. %% of this software and associated documentation files (the "Software"), to deal
  9. %% in the Software without restriction, including without limitation the rights
  10. %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. %% copies of the Software, and to permit persons to whom the Software is
  12. %% furnished to do so, subject to the following conditions:
  13. %%
  14. %% The above copyright notice and this permission notice shall be included in
  15. %% all copies or substantial portions of the Software.
  16. %%
  17. %% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. %% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. %% THE SOFTWARE.
  24. %% -------------------------------------------------------------------
  25. -module(rebar_port_compiler).
  26. -export([compile/2,
  27. clean/2]).
  28. -include("rebar.hrl").
  29. %% ===================================================================
  30. %% Public API
  31. %% ===================================================================
  32. %% Supported configuration variables:
  33. %%
  34. %% * port_sources - Erlang list of files and/or wildcard strings to be compiled
  35. %%
  36. %% * port_envs - Erlang list of key/value pairs which will control the environment when
  37. %% running the compiler and linker. By default, the following variables
  38. %% are defined:
  39. %% CC - C compiler
  40. %% CXX - C++ compiler
  41. %% CFLAGS - C compiler
  42. %% CXXFLAGS - C++ compiler
  43. %% LDFLAGS - Link flags
  44. %% DRIVER_CFLAGS - default -I paths for erts and ei
  45. %% DRIVER_LDFLAGS - default -L and -lerl_interface -lei
  46. %%
  47. %% Note that if you wish to extend (vs. replace) these variables, you MUST
  48. %% include a shell-style reference in your definition. E.g. to extend CFLAGS,
  49. %% do something like:
  50. %%
  51. %% {port_envs, [{"CFLAGS", "$CFLAGS -MyOtherOptions"}]}
  52. %%
  53. %% It is also possible to specify platform specific options by specifying a triplet
  54. %% where the first string is a regex that is checked against erlang's system architecture
  55. %% string. E.g. to specify a CFLAG that only applies to x86_64 on linux do:
  56. %%
  57. %% {port_envs, [{"x86_64.*-linux", "CFLAGS", "$CFLAGS -X86Options"}]}
  58. %%
  59. %% * port_pre_script - Tuple which specifies a pre-compilation script to run, and a filename that
  60. %% exists as a result of the script running.
  61. %%
  62. %% * port_cleanup_script - String that specifies a script to run during cleanup. Use this to remove
  63. %% files/directories created by port_pre_script.
  64. %%
  65. compile(Config, AppFile) ->
  66. %% Compose list of sources from config file -- defaults to c_src/*.c
  67. Sources = expand_sources(rebar_config:get_list(Config, port_sources, ["c_src/*.c"]), []),
  68. case Sources of
  69. [] ->
  70. ok;
  71. _ ->
  72. %% Extract environment values from the config (if specified) and merge with the
  73. %% default for this operating system. This enables max flexibility for users.
  74. DefaultEnvs = filter_envs(default_env(), []),
  75. OverrideEnvs = filter_envs(rebar_config:get_list(Config, port_envs, []), []),
  76. Env = merge_envs(OverrideEnvs, DefaultEnvs),
  77. %% One or more files are available for building. Run the pre-compile hook, if
  78. %% necessary.
  79. run_precompile_hook(Config, Env),
  80. %% Compile each of the sources
  81. {NewBins, ExistingBins} = compile_each(Sources, Config, Env, [], []),
  82. %% Construct the driver name and make sure priv/ exists
  83. SoName = so_name(AppFile),
  84. ok = filelib:ensure_dir(SoName),
  85. %% Only relink if necessary, given the SoName and list of new binaries
  86. case needs_link(SoName, NewBins) of
  87. true ->
  88. AllBins = string:join(NewBins ++ ExistingBins, " "),
  89. rebar_utils:sh_failfast(?FMT("$CC ~s $LDFLAGS $DRIVER_LDFLAGS -o ~s", [AllBins, SoName]), Env);
  90. false ->
  91. ?INFO("Skipping relink of ~s\n", [SoName]),
  92. ok
  93. end
  94. end.
  95. clean(Config, AppFile) ->
  96. %% Build a list of sources so as to derive all the bins we generated
  97. Sources = expand_sources(rebar_config:get_list(Config, port_sources, ["c_src/*.c"]), []),
  98. rebar_file_utils:delete_each([source_to_bin(S) || S <- Sources]),
  99. %% Delete the .so file
  100. rebar_file_utils:delete_each([so_name(AppFile)]),
  101. %% Run the cleanup script, if it exists
  102. run_cleanup_hook(Config).
  103. %% ===================================================================
  104. %% Internal functions
  105. %% ===================================================================
  106. expand_sources([], Acc) ->
  107. Acc;
  108. expand_sources([Spec | Rest], Acc) ->
  109. Acc2 = filelib:wildcard(Spec) ++ Acc,
  110. expand_sources(Rest, Acc2).
  111. run_precompile_hook(Config, Env) ->
  112. case rebar_config:get(Config, port_pre_script, undefined) of
  113. undefined ->
  114. ok;
  115. {Script, BypassFileName} ->
  116. case filelib:is_regular(BypassFileName) of
  117. false ->
  118. ?CONSOLE("Running ~s\n", [Script]),
  119. rebar_utils:sh_failfast(Script, Env);
  120. true ->
  121. ?INFO("~s exists; not running ~s\n", [BypassFileName, Script])
  122. end
  123. end.
  124. run_cleanup_hook(Config) ->
  125. case rebar_config:get(Config, port_cleanup_script, undefined) of
  126. undefined ->
  127. ok;
  128. Script ->
  129. ?CONSOLE("Running ~s\n", [Script]),
  130. rebar_utils:sh_failfast(Script, [])
  131. end.
  132. compile_each([], Config, Env, NewBins, ExistingBins) ->
  133. {lists:reverse(NewBins), lists:reverse(ExistingBins)};
  134. compile_each([Source | Rest], Config, Env, NewBins, ExistingBins) ->
  135. Ext = filename:extension(Source),
  136. Bin = filename:rootname(Source, Ext) ++ ".o",
  137. case needs_compile(Source, Bin) of
  138. true ->
  139. ?CONSOLE("Compiling ~s\n", [Source]),
  140. case compiler(Ext) of
  141. "$CC" ->
  142. rebar_utils:sh_failfast(?FMT("$CC -c $CFLAGS $DRIVER_CFLAGS ~s -o ~s", [Source, Bin]), Env);
  143. "$CXX" ->
  144. rebar_utils:sh_failfast(?FMT("$CXX -c $CXXFLAGS $DRIVER_CFLAGS ~s -o ~s", [Source, Bin]), Env)
  145. end,
  146. compile_each(Rest, Config, Env, [Bin | NewBins], ExistingBins);
  147. false ->
  148. ?INFO("Skipping ~s\n", [Source]),
  149. compile_each(Rest, Config, Env, NewBins, [Bin | ExistingBins])
  150. end.
  151. needs_compile(Source, Bin) ->
  152. %% TODO: Generate depends using gcc -MM so we can also check for include changes
  153. filelib:last_modified(Bin) < filelib:last_modified(Source).
  154. needs_link(SoName, []) ->
  155. filelib:last_modified(SoName) == 0;
  156. needs_link(SoName, NewBins) ->
  157. MaxLastMod = lists:max([filelib:last_modified(B) || B <- NewBins]),
  158. case filelib:last_modified(SoName) of
  159. 0 ->
  160. true;
  161. Other ->
  162. ?DEBUG("Checking ~p < ~p", [MaxLastMod, Other]),
  163. MaxLastMod < Other
  164. end.
  165. merge_envs(OverrideEnvs, DefaultEnvs) ->
  166. orddict:merge(fun(Key, Override, Default) ->
  167. expand_env_variable(Override, Key, Default)
  168. end,
  169. orddict:from_list(OverrideEnvs),
  170. orddict:from_list(DefaultEnvs)).
  171. %%
  172. %% Choose a compiler variable, based on a provided extension
  173. %%
  174. compiler(".cc") -> "$CXX";
  175. compiler(".cp") -> "$CXX";
  176. compiler(".cxx") -> "$CXX";
  177. compiler(".cpp") -> "$CXX";
  178. compiler(".CPP") -> "$CXX";
  179. compiler(".c++") -> "$CXX";
  180. compiler(".C") -> "$CXX";
  181. compiler(_) -> "$CC".
  182. %%
  183. %% Given env. variable FOO we want to expand all references to
  184. %% it in InStr. References can have two forms: $FOO and ${FOO}
  185. %%
  186. expand_env_variable(InStr, VarName, VarValue) ->
  187. R1 = re:replace(InStr, "\\\$" ++ VarName, VarValue),
  188. re:replace(R1, "\\\${" ++ VarName ++ "}", VarValue, [{return, list}]).
  189. %%
  190. %% Filter a list of env vars such that only those which match the provided
  191. %% architecture regex (or do not have a regex) are returned.
  192. %%
  193. filter_envs([], Acc) ->
  194. lists:reverse(Acc);
  195. filter_envs([{ArchRegex, Key, Value} | Rest], Acc) ->
  196. case rebar_utils:is_arch(ArchRegex) of
  197. true ->
  198. filter_envs(Rest, [{Key, Value} | Acc]);
  199. false ->
  200. filter_envs(Rest, Acc)
  201. end;
  202. filter_envs([{Key, Value} | Rest], Acc) ->
  203. filter_envs(Rest, [{Key, Value} | Acc]).
  204. erts_dir() ->
  205. lists:concat([code:root_dir(), "/erts-", erlang:system_info(version)]).
  206. default_env() ->
  207. [{"CC", "gcc"},
  208. {"CXX", "g++"},
  209. {"CFLAGS", "-g -Wall -fPIC"},
  210. {"CXXFLAGS", "-g -Wall -fPIC"},
  211. {"darwin", "LDFLAGS", "-bundle -flat_namespace -undefined suppress"},
  212. {"linux", "LDFLAGS", "-shared"},
  213. {"DRIVER_CFLAGS", lists:concat([" -I", code:lib_dir(erl_interface, include),
  214. " -I", filename:join(erts_dir(), include),
  215. " "])},
  216. {"DRIVER_LDFLAGS", lists:concat([" -L", code:lib_dir(erl_interface, lib),
  217. " -lerl_interface -lei"])}].
  218. source_to_bin(Source) ->
  219. Ext = filename:extension(Source),
  220. filename:rootname(Source, Ext) ++ ".o".
  221. so_name(AppFile) ->
  222. %% Get the app name, which we'll use to generate the linked port driver name
  223. case rebar_app_utils:load_app_file(AppFile) of
  224. {ok, AppName, _} ->
  225. ok;
  226. error ->
  227. AppName = undefined,
  228. ?FAIL
  229. end,
  230. %% Construct the driver name
  231. ?FMT("priv/~s_drv.so", [AppName]).