cmCoreTryCompile.cxx 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmCoreTryCompile.h"
  4. #include <array>
  5. #include <cstdio>
  6. #include <cstring>
  7. #include <set>
  8. #include <sstream>
  9. #include <utility>
  10. #include <cm/string_view>
  11. #include <cmext/string_view>
  12. #include "cmsys/Directory.hxx"
  13. #include "cmsys/FStream.hxx"
  14. #include "cmArgumentParser.h"
  15. #include "cmConfigureLog.h"
  16. #include "cmExperimental.h"
  17. #include "cmExportTryCompileFileGenerator.h"
  18. #include "cmGlobalGenerator.h"
  19. #include "cmList.h"
  20. #include "cmMakefile.h"
  21. #include "cmMessageType.h"
  22. #include "cmOutputConverter.h"
  23. #include "cmPolicies.h"
  24. #include "cmRange.h"
  25. #include "cmState.h"
  26. #include "cmStringAlgorithms.h"
  27. #include "cmSystemTools.h"
  28. #include "cmTarget.h"
  29. #include "cmValue.h"
  30. #include "cmVersion.h"
  31. #include "cmake.h"
  32. namespace {
  33. constexpr const char* unique_binary_directory = "CMAKE_BINARY_DIR_USE_MKDTEMP";
  34. constexpr size_t lang_property_start = 0;
  35. constexpr size_t lang_property_size = 4;
  36. constexpr size_t pie_property_start = 4;
  37. constexpr size_t pie_property_size = 2;
  38. /* clang-format off */
  39. #define SETUP_LANGUAGE(name, lang) \
  40. static const std::string name[lang_property_size + pie_property_size + 1] = \
  41. { "CMAKE_" #lang "_COMPILER_EXTERNAL_TOOLCHAIN", \
  42. "CMAKE_" #lang "_COMPILER_TARGET", \
  43. "CMAKE_" #lang "_LINK_NO_PIE_SUPPORTED", \
  44. "CMAKE_" #lang "_PIE_SUPPORTED", "" }
  45. /* clang-format on */
  46. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  47. SETUP_LANGUAGE(c_properties, C);
  48. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  49. SETUP_LANGUAGE(cxx_properties, CXX);
  50. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  51. SETUP_LANGUAGE(cuda_properties, CUDA);
  52. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  53. SETUP_LANGUAGE(fortran_properties, Fortran);
  54. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  55. SETUP_LANGUAGE(hip_properties, HIP);
  56. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  57. SETUP_LANGUAGE(objc_properties, OBJC);
  58. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  59. SETUP_LANGUAGE(objcxx_properties, OBJCXX);
  60. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  61. SETUP_LANGUAGE(ispc_properties, ISPC);
  62. // NOLINTNEXTLINE(bugprone-suspicious-missing-comma)
  63. SETUP_LANGUAGE(swift_properties, Swift);
  64. #undef SETUP_LANGUAGE
  65. std::string const kCMAKE_CUDA_ARCHITECTURES = "CMAKE_CUDA_ARCHITECTURES";
  66. std::string const kCMAKE_CUDA_RUNTIME_LIBRARY = "CMAKE_CUDA_RUNTIME_LIBRARY";
  67. std::string const kCMAKE_ENABLE_EXPORTS = "CMAKE_ENABLE_EXPORTS";
  68. std::string const kCMAKE_EXECUTABLE_ENABLE_EXPORTS =
  69. "CMAKE_EXECUTABLE_ENABLE_EXPORTS";
  70. std::string const kCMAKE_SHARED_LIBRARY_ENABLE_EXPORTS =
  71. "CMAKE_SHARED_LIBRARY_ENABLE_EXPORTS";
  72. std::string const kCMAKE_HIP_ARCHITECTURES = "CMAKE_HIP_ARCHITECTURES";
  73. std::string const kCMAKE_HIP_RUNTIME_LIBRARY = "CMAKE_HIP_RUNTIME_LIBRARY";
  74. std::string const kCMAKE_ISPC_INSTRUCTION_SETS = "CMAKE_ISPC_INSTRUCTION_SETS";
  75. std::string const kCMAKE_ISPC_HEADER_SUFFIX = "CMAKE_ISPC_HEADER_SUFFIX";
  76. std::string const kCMAKE_LINK_SEARCH_END_STATIC =
  77. "CMAKE_LINK_SEARCH_END_STATIC";
  78. std::string const kCMAKE_LINK_SEARCH_START_STATIC =
  79. "CMAKE_LINK_SEARCH_START_STATIC";
  80. std::string const kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT =
  81. "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT";
  82. std::string const kCMAKE_OSX_ARCHITECTURES = "CMAKE_OSX_ARCHITECTURES";
  83. std::string const kCMAKE_OSX_DEPLOYMENT_TARGET = "CMAKE_OSX_DEPLOYMENT_TARGET";
  84. std::string const kCMAKE_OSX_SYSROOT = "CMAKE_OSX_SYSROOT";
  85. std::string const kCMAKE_APPLE_ARCH_SYSROOTS = "CMAKE_APPLE_ARCH_SYSROOTS";
  86. std::string const kCMAKE_POSITION_INDEPENDENT_CODE =
  87. "CMAKE_POSITION_INDEPENDENT_CODE";
  88. std::string const kCMAKE_SYSROOT = "CMAKE_SYSROOT";
  89. std::string const kCMAKE_SYSROOT_COMPILE = "CMAKE_SYSROOT_COMPILE";
  90. std::string const kCMAKE_SYSROOT_LINK = "CMAKE_SYSROOT_LINK";
  91. std::string const kCMAKE_ARMClang_CMP0123 = "CMAKE_ARMClang_CMP0123";
  92. std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
  93. "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
  94. std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
  95. "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
  96. std::string const kCMAKE_WARN_DEPRECATED = "CMAKE_WARN_DEPRECATED";
  97. std::string const kCMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT =
  98. "CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT";
  99. std::string const kCMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT =
  100. "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT";
  101. /* GHS Multi platform variables */
  102. std::set<std::string> const ghs_platform_vars{
  103. "GHS_TARGET_PLATFORM", "GHS_PRIMARY_TARGET", "GHS_TOOLSET_ROOT",
  104. "GHS_OS_ROOT", "GHS_OS_DIR", "GHS_BSP_NAME",
  105. "GHS_OS_DIR_OPTION"
  106. };
  107. using Arguments = cmCoreTryCompile::Arguments;
  108. ArgumentParser::Continue TryCompileLangProp(Arguments& args,
  109. cm::string_view key,
  110. cm::string_view val)
  111. {
  112. args.LangProps[std::string(key)] = std::string(val);
  113. return ArgumentParser::Continue::No;
  114. }
  115. ArgumentParser::Continue TryCompileCompileDefs(Arguments& args,
  116. cm::string_view val)
  117. {
  118. args.CompileDefs.append(val);
  119. return ArgumentParser::Continue::Yes;
  120. }
  121. cmArgumentParser<Arguments> makeTryCompileParser(
  122. const cmArgumentParser<Arguments>& base)
  123. {
  124. return cmArgumentParser<Arguments>{ base }.Bind("OUTPUT_VARIABLE"_s,
  125. &Arguments::OutputVariable);
  126. }
  127. cmArgumentParser<Arguments> makeTryRunParser(
  128. const cmArgumentParser<Arguments>& base)
  129. {
  130. return cmArgumentParser<Arguments>{ base }
  131. .Bind("COMPILE_OUTPUT_VARIABLE"_s, &Arguments::CompileOutputVariable)
  132. .Bind("RUN_OUTPUT_VARIABLE"_s, &Arguments::RunOutputVariable)
  133. .Bind("RUN_OUTPUT_STDOUT_VARIABLE"_s, &Arguments::RunOutputStdOutVariable)
  134. .Bind("RUN_OUTPUT_STDERR_VARIABLE"_s, &Arguments::RunOutputStdErrVariable)
  135. .Bind("WORKING_DIRECTORY"_s, &Arguments::RunWorkingDirectory)
  136. .Bind("ARGS"_s, &Arguments::RunArgs)
  137. /* keep semicolon on own line */;
  138. }
  139. #define BIND_LANG_PROPS(lang) \
  140. Bind(#lang "_STANDARD"_s, TryCompileLangProp) \
  141. .Bind(#lang "_STANDARD_REQUIRED"_s, TryCompileLangProp) \
  142. .Bind(#lang "_EXTENSIONS"_s, TryCompileLangProp)
  143. auto const TryCompileBaseArgParser =
  144. cmArgumentParser<Arguments>{}
  145. .Bind(0, &Arguments::CompileResultVariable)
  146. .Bind("LOG_DESCRIPTION"_s, &Arguments::LogDescription)
  147. .Bind("NO_CACHE"_s, &Arguments::NoCache)
  148. .Bind("NO_LOG"_s, &Arguments::NoLog)
  149. .Bind("CMAKE_FLAGS"_s, &Arguments::CMakeFlags)
  150. .Bind("__CMAKE_INTERNAL"_s, &Arguments::CMakeInternal)
  151. /* keep semicolon on own line */;
  152. auto const TryCompileBaseSourcesArgParser =
  153. cmArgumentParser<Arguments>{ TryCompileBaseArgParser }
  154. .Bind("SOURCES"_s, &Arguments::Sources)
  155. .Bind("COMPILE_DEFINITIONS"_s, TryCompileCompileDefs,
  156. ArgumentParser::ExpectAtLeast{ 0 })
  157. .Bind("LINK_LIBRARIES"_s, &Arguments::LinkLibraries)
  158. .Bind("LINK_OPTIONS"_s, &Arguments::LinkOptions)
  159. .Bind("COPY_FILE"_s, &Arguments::CopyFileTo)
  160. .Bind("COPY_FILE_ERROR"_s, &Arguments::CopyFileError)
  161. .BIND_LANG_PROPS(C)
  162. .BIND_LANG_PROPS(CUDA)
  163. .BIND_LANG_PROPS(CXX)
  164. .BIND_LANG_PROPS(HIP)
  165. .BIND_LANG_PROPS(OBJC)
  166. .BIND_LANG_PROPS(OBJCXX)
  167. /* keep semicolon on own line */;
  168. auto const TryCompileBaseNewSourcesArgParser =
  169. cmArgumentParser<Arguments>{ TryCompileBaseSourcesArgParser }
  170. .Bind("SOURCE_FROM_CONTENT"_s, &Arguments::SourceFromContent)
  171. .Bind("SOURCE_FROM_VAR"_s, &Arguments::SourceFromVar)
  172. .Bind("SOURCE_FROM_FILE"_s, &Arguments::SourceFromFile)
  173. /* keep semicolon on own line */;
  174. auto const TryCompileBaseProjectArgParser =
  175. cmArgumentParser<Arguments>{ TryCompileBaseArgParser }
  176. .Bind("PROJECT"_s, &Arguments::ProjectName)
  177. .Bind("SOURCE_DIR"_s, &Arguments::SourceDirectoryOrFile)
  178. .Bind("BINARY_DIR"_s, &Arguments::BinaryDirectory)
  179. .Bind("TARGET"_s, &Arguments::TargetName)
  180. /* keep semicolon on own line */;
  181. auto const TryCompileProjectArgParser =
  182. makeTryCompileParser(TryCompileBaseProjectArgParser);
  183. auto const TryCompileSourcesArgParser =
  184. makeTryCompileParser(TryCompileBaseNewSourcesArgParser);
  185. auto const TryCompileOldArgParser =
  186. makeTryCompileParser(TryCompileBaseSourcesArgParser)
  187. .Bind(1, &Arguments::BinaryDirectory)
  188. .Bind(2, &Arguments::SourceDirectoryOrFile)
  189. .Bind(3, &Arguments::ProjectName)
  190. .Bind(4, &Arguments::TargetName)
  191. /* keep semicolon on own line */;
  192. auto const TryRunSourcesArgParser =
  193. makeTryRunParser(TryCompileBaseNewSourcesArgParser);
  194. auto const TryRunOldArgParser = makeTryRunParser(TryCompileOldArgParser);
  195. #undef BIND_LANG_PROPS
  196. std::string const TryCompileDefaultConfig = "DEBUG";
  197. }
  198. Arguments cmCoreTryCompile::ParseArgs(
  199. const cmRange<std::vector<std::string>::const_iterator>& args,
  200. const cmArgumentParser<Arguments>& parser,
  201. std::vector<std::string>& unparsedArguments)
  202. {
  203. auto arguments = parser.Parse(args, &unparsedArguments, 0);
  204. if (!arguments.MaybeReportError(*(this->Makefile)) &&
  205. !unparsedArguments.empty()) {
  206. std::string m = "Unknown arguments:";
  207. for (const auto& i : unparsedArguments) {
  208. m = cmStrCat(m, "\n \"", i, '"');
  209. }
  210. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, m);
  211. }
  212. return arguments;
  213. }
  214. Arguments cmCoreTryCompile::ParseArgs(
  215. cmRange<std::vector<std::string>::const_iterator> args, bool isTryRun)
  216. {
  217. std::vector<std::string> unparsedArguments;
  218. const auto& second = *(++args.begin());
  219. if (!isTryRun && second == "PROJECT") {
  220. // New PROJECT signature (try_compile only).
  221. auto arguments =
  222. this->ParseArgs(args, TryCompileProjectArgParser, unparsedArguments);
  223. if (!arguments.BinaryDirectory) {
  224. arguments.BinaryDirectory = unique_binary_directory;
  225. }
  226. return arguments;
  227. }
  228. if (cmHasLiteralPrefix(second, "SOURCE")) {
  229. // New SOURCES signature.
  230. auto arguments = this->ParseArgs(
  231. args, isTryRun ? TryRunSourcesArgParser : TryCompileSourcesArgParser,
  232. unparsedArguments);
  233. arguments.BinaryDirectory = unique_binary_directory;
  234. return arguments;
  235. }
  236. // Old signature.
  237. auto arguments = this->ParseArgs(
  238. args, isTryRun ? TryRunOldArgParser : TryCompileOldArgParser,
  239. unparsedArguments);
  240. // For historical reasons, treat some empty-valued keyword
  241. // arguments as if they were not specified at all.
  242. if (arguments.OutputVariable && arguments.OutputVariable->empty()) {
  243. arguments.OutputVariable = cm::nullopt;
  244. }
  245. if (isTryRun) {
  246. if (arguments.CompileOutputVariable &&
  247. arguments.CompileOutputVariable->empty()) {
  248. arguments.CompileOutputVariable = cm::nullopt;
  249. }
  250. if (arguments.RunOutputVariable && arguments.RunOutputVariable->empty()) {
  251. arguments.RunOutputVariable = cm::nullopt;
  252. }
  253. if (arguments.RunOutputStdOutVariable &&
  254. arguments.RunOutputStdOutVariable->empty()) {
  255. arguments.RunOutputStdOutVariable = cm::nullopt;
  256. }
  257. if (arguments.RunOutputStdErrVariable &&
  258. arguments.RunOutputStdErrVariable->empty()) {
  259. arguments.RunOutputStdErrVariable = cm::nullopt;
  260. }
  261. if (arguments.RunWorkingDirectory &&
  262. arguments.RunWorkingDirectory->empty()) {
  263. arguments.RunWorkingDirectory = cm::nullopt;
  264. }
  265. }
  266. return arguments;
  267. }
  268. cm::optional<cmTryCompileResult> cmCoreTryCompile::TryCompileCode(
  269. Arguments& arguments, cmStateEnums::TargetType targetType)
  270. {
  271. this->OutputFile.clear();
  272. // which signature were we called with ?
  273. this->SrcFileSignature = true;
  274. bool useUniqueBinaryDirectory = false;
  275. std::string sourceDirectory;
  276. std::string projectName;
  277. std::string targetName;
  278. if (arguments.ProjectName) {
  279. this->SrcFileSignature = false;
  280. if (!arguments.SourceDirectoryOrFile ||
  281. arguments.SourceDirectoryOrFile->empty()) {
  282. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  283. "No <srcdir> specified.");
  284. return cm::nullopt;
  285. }
  286. sourceDirectory = *arguments.SourceDirectoryOrFile;
  287. projectName = *arguments.ProjectName;
  288. if (arguments.TargetName) {
  289. targetName = *arguments.TargetName;
  290. }
  291. } else {
  292. projectName = "CMAKE_TRY_COMPILE";
  293. /* Use a random file name to avoid rapid creation and deletion
  294. of the same executable name (some filesystems fail on that). */
  295. char targetNameBuf[64];
  296. snprintf(targetNameBuf, sizeof(targetNameBuf), "cmTC_%05x",
  297. cmSystemTools::RandomSeed() & 0xFFFFF);
  298. targetName = targetNameBuf;
  299. }
  300. if (!arguments.BinaryDirectory || arguments.BinaryDirectory->empty()) {
  301. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  302. "No <bindir> specified.");
  303. return cm::nullopt;
  304. }
  305. if (*arguments.BinaryDirectory == unique_binary_directory) {
  306. // leave empty until we're ready to create it, so we don't try to remove
  307. // a non-existing directory if we abort due to e.g. bad arguments
  308. this->BinaryDirectory.clear();
  309. useUniqueBinaryDirectory = true;
  310. } else {
  311. if (!cmSystemTools::FileIsFullPath(*arguments.BinaryDirectory)) {
  312. this->Makefile->IssueMessage(
  313. MessageType::FATAL_ERROR,
  314. cmStrCat("<bindir> is not an absolute path:\n '",
  315. *arguments.BinaryDirectory, '\''));
  316. return cm::nullopt;
  317. }
  318. this->BinaryDirectory = *arguments.BinaryDirectory;
  319. // compute the binary dir when TRY_COMPILE is called with a src file
  320. // signature
  321. if (this->SrcFileSignature) {
  322. this->BinaryDirectory += "/CMakeFiles/CMakeTmp";
  323. }
  324. }
  325. std::vector<std::string> targets;
  326. if (arguments.LinkLibraries) {
  327. for (std::string const& i : *arguments.LinkLibraries) {
  328. if (cmTarget* tgt = this->Makefile->FindTargetToUse(i)) {
  329. switch (tgt->GetType()) {
  330. case cmStateEnums::SHARED_LIBRARY:
  331. case cmStateEnums::STATIC_LIBRARY:
  332. case cmStateEnums::INTERFACE_LIBRARY:
  333. case cmStateEnums::UNKNOWN_LIBRARY:
  334. break;
  335. case cmStateEnums::EXECUTABLE:
  336. if (tgt->IsExecutableWithExports()) {
  337. break;
  338. }
  339. CM_FALLTHROUGH;
  340. default:
  341. this->Makefile->IssueMessage(
  342. MessageType::FATAL_ERROR,
  343. cmStrCat("Only libraries may be used as try_compile or try_run "
  344. "IMPORTED LINK_LIBRARIES. Got ",
  345. tgt->GetName(), " of type ",
  346. cmState::GetTargetTypeName(tgt->GetType()), '.'));
  347. return cm::nullopt;
  348. }
  349. if (tgt->IsImported()) {
  350. targets.emplace_back(i);
  351. }
  352. }
  353. }
  354. }
  355. if (arguments.CopyFileTo && arguments.CopyFileTo->empty()) {
  356. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  357. "COPY_FILE must be followed by a file path");
  358. return cm::nullopt;
  359. }
  360. if (arguments.CopyFileError && arguments.CopyFileError->empty()) {
  361. this->Makefile->IssueMessage(
  362. MessageType::FATAL_ERROR,
  363. "COPY_FILE_ERROR must be followed by a variable name");
  364. return cm::nullopt;
  365. }
  366. if (arguments.CopyFileError && !arguments.CopyFileTo) {
  367. this->Makefile->IssueMessage(
  368. MessageType::FATAL_ERROR,
  369. "COPY_FILE_ERROR may be used only with COPY_FILE");
  370. return cm::nullopt;
  371. }
  372. if (arguments.Sources && arguments.Sources->empty()) {
  373. this->Makefile->IssueMessage(
  374. MessageType::FATAL_ERROR,
  375. "SOURCES must be followed by at least one source file");
  376. return cm::nullopt;
  377. }
  378. if (this->SrcFileSignature) {
  379. if (arguments.SourceFromContent &&
  380. arguments.SourceFromContent->size() % 2) {
  381. this->Makefile->IssueMessage(
  382. MessageType::FATAL_ERROR,
  383. "SOURCE_FROM_CONTENT requires exactly two arguments");
  384. return cm::nullopt;
  385. }
  386. if (arguments.SourceFromVar && arguments.SourceFromVar->size() % 2) {
  387. this->Makefile->IssueMessage(
  388. MessageType::FATAL_ERROR,
  389. "SOURCE_FROM_VAR requires exactly two arguments");
  390. return cm::nullopt;
  391. }
  392. if (arguments.SourceFromFile && arguments.SourceFromFile->size() % 2) {
  393. this->Makefile->IssueMessage(
  394. MessageType::FATAL_ERROR,
  395. "SOURCE_FROM_FILE requires exactly two arguments");
  396. return cm::nullopt;
  397. }
  398. } else {
  399. // only valid for srcfile signatures
  400. if (!arguments.LangProps.empty()) {
  401. this->Makefile->IssueMessage(
  402. MessageType::FATAL_ERROR,
  403. cmStrCat(arguments.LangProps.begin()->first,
  404. " allowed only in source file signature"));
  405. return cm::nullopt;
  406. }
  407. if (!arguments.CompileDefs.empty()) {
  408. this->Makefile->IssueMessage(
  409. MessageType::FATAL_ERROR,
  410. "COMPILE_DEFINITIONS allowed only in source file signature");
  411. return cm::nullopt;
  412. }
  413. if (arguments.CopyFileTo) {
  414. this->Makefile->IssueMessage(
  415. MessageType::FATAL_ERROR,
  416. "COPY_FILE allowed only in source file signature");
  417. return cm::nullopt;
  418. }
  419. }
  420. // make sure the binary directory exists
  421. if (useUniqueBinaryDirectory) {
  422. this->BinaryDirectory =
  423. cmStrCat(this->Makefile->GetHomeOutputDirectory(),
  424. "/CMakeFiles/CMakeScratch/TryCompile-XXXXXX");
  425. cmSystemTools::MakeTempDirectory(this->BinaryDirectory);
  426. } else {
  427. cmSystemTools::MakeDirectory(this->BinaryDirectory);
  428. }
  429. // do not allow recursive try Compiles
  430. if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory()) {
  431. std::ostringstream e;
  432. e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
  433. << " " << this->BinaryDirectory << "\n";
  434. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  435. return cm::nullopt;
  436. }
  437. std::map<std::string, std::string> cmakeVariables;
  438. std::string outFileName = cmStrCat(this->BinaryDirectory, "/CMakeLists.txt");
  439. // which signature are we using? If we are using var srcfile bindir
  440. if (this->SrcFileSignature) {
  441. // remove any CMakeCache.txt files so we will have a clean test
  442. std::string ccFile = cmStrCat(this->BinaryDirectory, "/CMakeCache.txt");
  443. cmSystemTools::RemoveFile(ccFile);
  444. // Choose sources.
  445. std::vector<std::string> sources;
  446. if (arguments.Sources) {
  447. sources = std::move(*arguments.Sources);
  448. } else if (arguments.SourceDirectoryOrFile) {
  449. sources.emplace_back(*arguments.SourceDirectoryOrFile);
  450. }
  451. if (arguments.SourceFromContent) {
  452. auto const k = arguments.SourceFromContent->size();
  453. for (auto i = decltype(k){ 0 }; i < k; i += 2) {
  454. const auto& name = (*arguments.SourceFromContent)[i + 0];
  455. const auto& content = (*arguments.SourceFromContent)[i + 1];
  456. auto out = this->WriteSource(name, content, "SOURCE_FROM_CONTENT");
  457. if (out.empty()) {
  458. return cm::nullopt;
  459. }
  460. sources.emplace_back(std::move(out));
  461. }
  462. }
  463. if (arguments.SourceFromVar) {
  464. auto const k = arguments.SourceFromVar->size();
  465. for (auto i = decltype(k){ 0 }; i < k; i += 2) {
  466. const auto& name = (*arguments.SourceFromVar)[i + 0];
  467. const auto& var = (*arguments.SourceFromVar)[i + 1];
  468. const auto& content = this->Makefile->GetDefinition(var);
  469. auto out = this->WriteSource(name, content, "SOURCE_FROM_VAR");
  470. if (out.empty()) {
  471. return cm::nullopt;
  472. }
  473. sources.emplace_back(std::move(out));
  474. }
  475. }
  476. if (arguments.SourceFromFile) {
  477. auto const k = arguments.SourceFromFile->size();
  478. for (auto i = decltype(k){ 0 }; i < k; i += 2) {
  479. const auto& dst = (*arguments.SourceFromFile)[i + 0];
  480. const auto& src = (*arguments.SourceFromFile)[i + 1];
  481. if (!cmSystemTools::GetFilenamePath(dst).empty()) {
  482. const auto& msg =
  483. cmStrCat("SOURCE_FROM_FILE given invalid filename \"", dst, '"');
  484. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, msg);
  485. return cm::nullopt;
  486. }
  487. auto dstPath = cmStrCat(this->BinaryDirectory, '/', dst);
  488. auto const result = cmSystemTools::CopyFileAlways(src, dstPath);
  489. if (!result.IsSuccess()) {
  490. const auto& msg = cmStrCat("SOURCE_FROM_FILE failed to copy \"", src,
  491. "\": ", result.GetString());
  492. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, msg);
  493. return cm::nullopt;
  494. }
  495. sources.emplace_back(std::move(dstPath));
  496. }
  497. }
  498. // TODO: ensure sources is not empty
  499. // Detect languages to enable.
  500. cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
  501. std::set<std::string> testLangs;
  502. for (std::string const& si : sources) {
  503. std::string ext = cmSystemTools::GetFilenameLastExtension(si);
  504. std::string lang = gg->GetLanguageFromExtension(ext.c_str());
  505. if (!lang.empty()) {
  506. testLangs.insert(lang);
  507. } else {
  508. std::ostringstream err;
  509. err << "Unknown extension \"" << ext
  510. << "\" for file\n"
  511. " "
  512. << si
  513. << "\n"
  514. "try_compile() works only for enabled languages. "
  515. "Currently these are:\n ";
  516. std::vector<std::string> langs;
  517. gg->GetEnabledLanguages(langs);
  518. err << cmJoin(langs, " ");
  519. err << "\nSee project() command to enable other languages.";
  520. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, err.str());
  521. return cm::nullopt;
  522. }
  523. }
  524. // when the only language is ISPC we know that the output
  525. // type must by a static library
  526. if (testLangs.size() == 1 && testLangs.count("ISPC") == 1) {
  527. targetType = cmStateEnums::STATIC_LIBRARY;
  528. }
  529. std::string const tcConfig =
  530. this->Makefile->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  531. // we need to create a directory and CMakeLists file etc...
  532. // first create the directories
  533. sourceDirectory = this->BinaryDirectory;
  534. // now create a CMakeLists.txt file in that directory
  535. FILE* fout = cmsys::SystemTools::Fopen(outFileName, "w");
  536. if (!fout) {
  537. std::ostringstream e;
  538. /* clang-format off */
  539. e << "Failed to open\n"
  540. " " << outFileName << "\n"
  541. << cmSystemTools::GetLastSystemError();
  542. /* clang-format on */
  543. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  544. return cm::nullopt;
  545. }
  546. cmValue def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
  547. fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n",
  548. cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(),
  549. cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion());
  550. if (def) {
  551. fprintf(fout, "set(CMAKE_MODULE_PATH \"%s\")\n", def->c_str());
  552. cmakeVariables.emplace("CMAKE_MODULE_PATH", *def);
  553. }
  554. /* Set MSVC runtime library policy to match our selection. */
  555. if (cmValue msvcRuntimeLibraryDefault =
  556. this->Makefile->GetDefinition(kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT)) {
  557. fprintf(fout, "cmake_policy(SET CMP0091 %s)\n",
  558. !msvcRuntimeLibraryDefault->empty() ? "NEW" : "OLD");
  559. }
  560. /* Set Watcom runtime library policy to match our selection. */
  561. if (cmValue watcomRuntimeLibraryDefault = this->Makefile->GetDefinition(
  562. kCMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT)) {
  563. fprintf(fout, "cmake_policy(SET CMP0136 %s)\n",
  564. !watcomRuntimeLibraryDefault->empty() ? "NEW" : "OLD");
  565. }
  566. /* Set CUDA architectures policy to match outer project. */
  567. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0104) !=
  568. cmPolicies::NEW &&
  569. testLangs.find("CUDA") != testLangs.end() &&
  570. this->Makefile->GetSafeDefinition(kCMAKE_CUDA_ARCHITECTURES).empty()) {
  571. fprintf(fout, "cmake_policy(SET CMP0104 OLD)\n");
  572. }
  573. /* Set ARMClang cpu/arch policy to match outer project. */
  574. if (cmValue cmp0123 =
  575. this->Makefile->GetDefinition(kCMAKE_ARMClang_CMP0123)) {
  576. fprintf(fout, "cmake_policy(SET CMP0123 %s)\n",
  577. *cmp0123 == "NEW"_s ? "NEW" : "OLD");
  578. }
  579. /* Set MSVC debug information format policy to match our selection. */
  580. if (cmValue msvcDebugInformationFormatDefault =
  581. this->Makefile->GetDefinition(
  582. kCMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT)) {
  583. fprintf(fout, "cmake_policy(SET CMP0141 %s)\n",
  584. !msvcDebugInformationFormatDefault->empty() ? "NEW" : "OLD");
  585. }
  586. /* Set cache/normal variable policy to match outer project.
  587. It may affect toolchain files. */
  588. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) !=
  589. cmPolicies::NEW) {
  590. fprintf(fout, "cmake_policy(SET CMP0126 OLD)\n");
  591. }
  592. /* Set language extensions policy to match outer project. */
  593. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0128) !=
  594. cmPolicies::NEW) {
  595. fprintf(fout, "cmake_policy(SET CMP0128 OLD)\n");
  596. }
  597. std::string projectLangs;
  598. for (std::string const& li : testLangs) {
  599. projectLangs += cmStrCat(' ', li);
  600. std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
  601. std::string rulesOverrideLang = cmStrCat(rulesOverrideBase, '_', li);
  602. if (cmValue rulesOverridePath =
  603. this->Makefile->GetDefinition(rulesOverrideLang)) {
  604. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(),
  605. rulesOverridePath->c_str());
  606. cmakeVariables.emplace(rulesOverrideLang, *rulesOverridePath);
  607. } else if (cmValue rulesOverridePath2 =
  608. this->Makefile->GetDefinition(rulesOverrideBase)) {
  609. fprintf(fout, "set(%s \"%s\")\n", rulesOverrideBase.c_str(),
  610. rulesOverridePath2->c_str());
  611. cmakeVariables.emplace(rulesOverrideBase, *rulesOverridePath2);
  612. }
  613. }
  614. fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
  615. if (arguments.CMakeInternal == "ABI") {
  616. // This is the ABI detection step, also used for implicit includes.
  617. // Erase any include_directories() calls from the toolchain file so
  618. // that we do not see them as implicit. Our ABI detection source
  619. // does not include any system headers anyway.
  620. fprintf(fout,
  621. "set_property(DIRECTORY PROPERTY INCLUDE_DIRECTORIES \"\")\n");
  622. // The link and compile lines for ABI detection step need to not use
  623. // response files so we can extract implicit includes given to
  624. // the underlying host compiler
  625. if (testLangs.find("CUDA") != testLangs.end()) {
  626. fprintf(fout, "set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_INCLUDES OFF)\n");
  627. fprintf(fout, "set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_LIBRARIES OFF)\n");
  628. fprintf(fout, "set(CMAKE_CUDA_USE_RESPONSE_FILE_FOR_OBJECTS OFF)\n");
  629. }
  630. }
  631. fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n");
  632. for (std::string const& li : testLangs) {
  633. std::string langFlags = cmStrCat("CMAKE_", li, "_FLAGS");
  634. cmValue flags = this->Makefile->GetDefinition(langFlags);
  635. fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li.c_str(),
  636. cmOutputConverter::EscapeForCMake(*flags).c_str());
  637. fprintf(fout,
  638. "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
  639. " ${COMPILE_DEFINITIONS}\")\n",
  640. li.c_str(), li.c_str());
  641. if (flags) {
  642. cmakeVariables.emplace(langFlags, *flags);
  643. }
  644. }
  645. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) {
  646. case cmPolicies::WARN:
  647. if (this->Makefile->PolicyOptionalWarningEnabled(
  648. "CMAKE_POLICY_WARNING_CMP0066")) {
  649. std::ostringstream w;
  650. /* clang-format off */
  651. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0066) << "\n"
  652. "For compatibility with older versions of CMake, try_compile "
  653. "is not honoring caller config-specific compiler flags "
  654. "(e.g. CMAKE_C_FLAGS_DEBUG) in the test project."
  655. ;
  656. /* clang-format on */
  657. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  658. }
  659. CM_FALLTHROUGH;
  660. case cmPolicies::OLD:
  661. // OLD behavior is to do nothing.
  662. break;
  663. case cmPolicies::REQUIRED_IF_USED:
  664. case cmPolicies::REQUIRED_ALWAYS:
  665. this->Makefile->IssueMessage(
  666. MessageType::FATAL_ERROR,
  667. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0066));
  668. CM_FALLTHROUGH;
  669. case cmPolicies::NEW: {
  670. // NEW behavior is to pass config-specific compiler flags.
  671. std::string const cfg = !tcConfig.empty()
  672. ? cmSystemTools::UpperCase(tcConfig)
  673. : TryCompileDefaultConfig;
  674. for (std::string const& li : testLangs) {
  675. std::string const langFlagsCfg =
  676. cmStrCat("CMAKE_", li, "_FLAGS_", cfg);
  677. cmValue flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
  678. fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
  679. cmOutputConverter::EscapeForCMake(*flagsCfg).c_str());
  680. if (flagsCfg) {
  681. cmakeVariables.emplace(langFlagsCfg, *flagsCfg);
  682. }
  683. }
  684. } break;
  685. }
  686. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0056)) {
  687. case cmPolicies::WARN:
  688. if (this->Makefile->PolicyOptionalWarningEnabled(
  689. "CMAKE_POLICY_WARNING_CMP0056")) {
  690. std::ostringstream w;
  691. /* clang-format off */
  692. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0056) << "\n"
  693. "For compatibility with older versions of CMake, try_compile "
  694. "is not honoring caller link flags (e.g. CMAKE_EXE_LINKER_FLAGS) "
  695. "in the test project."
  696. ;
  697. /* clang-format on */
  698. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  699. }
  700. CM_FALLTHROUGH;
  701. case cmPolicies::OLD:
  702. // OLD behavior is to do nothing.
  703. break;
  704. case cmPolicies::REQUIRED_IF_USED:
  705. case cmPolicies::REQUIRED_ALWAYS:
  706. this->Makefile->IssueMessage(
  707. MessageType::FATAL_ERROR,
  708. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0056));
  709. CM_FALLTHROUGH;
  710. case cmPolicies::NEW:
  711. // NEW behavior is to pass linker flags.
  712. {
  713. cmValue exeLinkFlags =
  714. this->Makefile->GetDefinition("CMAKE_EXE_LINKER_FLAGS");
  715. fprintf(fout, "set(CMAKE_EXE_LINKER_FLAGS %s)\n",
  716. cmOutputConverter::EscapeForCMake(*exeLinkFlags).c_str());
  717. if (exeLinkFlags) {
  718. cmakeVariables.emplace("CMAKE_EXE_LINKER_FLAGS", *exeLinkFlags);
  719. }
  720. }
  721. break;
  722. }
  723. fprintf(fout,
  724. "set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS}"
  725. " ${EXE_LINKER_FLAGS}\")\n");
  726. fprintf(fout, "include_directories(${INCLUDE_DIRECTORIES})\n");
  727. fprintf(fout, "set(CMAKE_SUPPRESS_REGENERATION 1)\n");
  728. fprintf(fout, "link_directories(${LINK_DIRECTORIES})\n");
  729. // handle any compile flags we need to pass on
  730. if (!arguments.CompileDefs.empty()) {
  731. // Pass using bracket arguments to preserve content.
  732. fprintf(fout, "add_definitions([==[%s]==])\n",
  733. arguments.CompileDefs.join("]==] [==[").c_str());
  734. }
  735. if (!targets.empty()) {
  736. std::string fname = cmStrCat('/', targetName, "Targets.cmake");
  737. cmExportTryCompileFileGenerator tcfg(gg, targets, this->Makefile,
  738. testLangs);
  739. tcfg.SetExportFile(cmStrCat(this->BinaryDirectory, fname).c_str());
  740. tcfg.SetConfig(tcConfig);
  741. if (!tcfg.GenerateImportFile()) {
  742. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  743. "could not write export file.");
  744. fclose(fout);
  745. return cm::nullopt;
  746. }
  747. fprintf(fout, "\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/%s\")\n\n",
  748. fname.c_str());
  749. }
  750. /* Set the appropriate policy information for ENABLE_EXPORTS */
  751. fprintf(fout, "cmake_policy(SET CMP0065 %s)\n",
  752. this->Makefile->GetPolicyStatus(cmPolicies::CMP0065) ==
  753. cmPolicies::NEW
  754. ? "NEW"
  755. : "OLD");
  756. /* Set the appropriate policy information for PIE link flags */
  757. fprintf(fout, "cmake_policy(SET CMP0083 %s)\n",
  758. this->Makefile->GetPolicyStatus(cmPolicies::CMP0083) ==
  759. cmPolicies::NEW
  760. ? "NEW"
  761. : "OLD");
  762. // Workaround for -Wl,-headerpad_max_install_names issue until we can avoid
  763. // adding that flag in the platform and compiler language files
  764. fprintf(fout,
  765. "include(\"${CMAKE_ROOT}/Modules/Internal/"
  766. "HeaderpadWorkaround.cmake\")\n");
  767. if (targetType == cmStateEnums::EXECUTABLE) {
  768. /* Put the executable at a known location (for COPY_FILE). */
  769. fprintf(fout, "set(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
  770. this->BinaryDirectory.c_str());
  771. /* Create the actual executable. */
  772. fprintf(fout, "add_executable(%s", targetName.c_str());
  773. } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
  774. {
  775. /* Put the static library at a known location (for COPY_FILE). */
  776. fprintf(fout, "set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"%s\")\n",
  777. this->BinaryDirectory.c_str());
  778. /* Create the actual static library. */
  779. fprintf(fout, "add_library(%s STATIC", targetName.c_str());
  780. }
  781. for (std::string const& si : sources) {
  782. fprintf(fout, " \"%s\"", si.c_str());
  783. // Add dependencies on any non-temporary sources.
  784. if (!IsTemporary(si)) {
  785. this->Makefile->AddCMakeDependFile(si);
  786. }
  787. }
  788. fprintf(fout, ")\n");
  789. /* Write out the output location of the target we are building */
  790. std::string perConfigGenex;
  791. if (this->Makefile->GetGlobalGenerator()->IsMultiConfig()) {
  792. perConfigGenex = "_$<UPPER_CASE:$<CONFIG>>";
  793. }
  794. fprintf(fout,
  795. "file(GENERATE OUTPUT "
  796. "\"${CMAKE_BINARY_DIR}/%s%s_loc\"\n",
  797. targetName.c_str(), perConfigGenex.c_str());
  798. fprintf(fout, " CONTENT $<TARGET_FILE:%s>)\n", targetName.c_str());
  799. bool warnCMP0067 = false;
  800. bool honorStandard = true;
  801. if (arguments.LangProps.empty()) {
  802. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0067)) {
  803. case cmPolicies::WARN:
  804. warnCMP0067 = this->Makefile->PolicyOptionalWarningEnabled(
  805. "CMAKE_POLICY_WARNING_CMP0067");
  806. CM_FALLTHROUGH;
  807. case cmPolicies::OLD:
  808. // OLD behavior is to not honor the language standard variables.
  809. honorStandard = false;
  810. break;
  811. case cmPolicies::REQUIRED_IF_USED:
  812. case cmPolicies::REQUIRED_ALWAYS:
  813. this->Makefile->IssueMessage(
  814. MessageType::FATAL_ERROR,
  815. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0067));
  816. break;
  817. case cmPolicies::NEW:
  818. // NEW behavior is to honor the language standard variables.
  819. // We already initialized honorStandard to true.
  820. break;
  821. }
  822. }
  823. std::vector<std::string> warnCMP0067Variables;
  824. if (honorStandard || warnCMP0067) {
  825. static std::array<std::string, 6> const possibleLangs{
  826. { "C", "CXX", "CUDA", "HIP", "OBJC", "OBJCXX" }
  827. };
  828. static std::array<cm::string_view, 3> const langPropSuffixes{
  829. { "_STANDARD"_s, "_STANDARD_REQUIRED"_s, "_EXTENSIONS"_s }
  830. };
  831. for (std::string const& lang : possibleLangs) {
  832. if (testLangs.find(lang) == testLangs.end()) {
  833. continue;
  834. }
  835. for (cm::string_view propSuffix : langPropSuffixes) {
  836. std::string langProp = cmStrCat(lang, propSuffix);
  837. if (!arguments.LangProps.count(langProp)) {
  838. std::string langPropVar = cmStrCat("CMAKE_"_s, langProp);
  839. std::string value = this->Makefile->GetSafeDefinition(langPropVar);
  840. if (warnCMP0067 && !value.empty()) {
  841. value.clear();
  842. warnCMP0067Variables.emplace_back(langPropVar);
  843. }
  844. if (!value.empty()) {
  845. arguments.LangProps[langProp] = value;
  846. }
  847. }
  848. }
  849. }
  850. }
  851. if (!warnCMP0067Variables.empty()) {
  852. std::ostringstream w;
  853. /* clang-format off */
  854. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0067) << "\n"
  855. "For compatibility with older versions of CMake, try_compile "
  856. "is not honoring language standard variables in the test project:\n"
  857. ;
  858. /* clang-format on */
  859. for (std::string const& vi : warnCMP0067Variables) {
  860. w << " " << vi << "\n";
  861. }
  862. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  863. }
  864. for (auto const& p : arguments.LangProps) {
  865. if (p.second.empty()) {
  866. continue;
  867. }
  868. fprintf(fout, "set_property(TARGET %s PROPERTY %s %s)\n",
  869. targetName.c_str(),
  870. cmOutputConverter::EscapeForCMake(p.first).c_str(),
  871. cmOutputConverter::EscapeForCMake(p.second).c_str());
  872. }
  873. if (!arguments.LinkOptions.empty()) {
  874. std::vector<std::string> options;
  875. options.reserve(arguments.LinkOptions.size());
  876. for (const auto& option : arguments.LinkOptions) {
  877. options.emplace_back(cmOutputConverter::EscapeForCMake(option));
  878. }
  879. if (targetType == cmStateEnums::STATIC_LIBRARY) {
  880. fprintf(fout,
  881. "set_property(TARGET %s PROPERTY STATIC_LIBRARY_OPTIONS %s)\n",
  882. targetName.c_str(), cmJoin(options, " ").c_str());
  883. } else {
  884. fprintf(fout, "target_link_options(%s PRIVATE %s)\n",
  885. targetName.c_str(), cmJoin(options, " ").c_str());
  886. }
  887. }
  888. if (arguments.LinkLibraries) {
  889. std::string libsToLink = " ";
  890. for (std::string const& i : *arguments.LinkLibraries) {
  891. libsToLink += cmStrCat('"', cmTrimWhitespace(i), "\" ");
  892. }
  893. fprintf(fout, "target_link_libraries(%s %s)\n", targetName.c_str(),
  894. libsToLink.c_str());
  895. } else {
  896. fprintf(fout, "target_link_libraries(%s ${LINK_LIBRARIES})\n",
  897. targetName.c_str());
  898. }
  899. fclose(fout);
  900. }
  901. // Forward a set of variables to the inner project cache.
  902. if ((this->SrcFileSignature ||
  903. this->Makefile->GetPolicyStatus(cmPolicies::CMP0137) ==
  904. cmPolicies::NEW) &&
  905. !this->Makefile->IsOn("CMAKE_TRY_COMPILE_NO_PLATFORM_VARIABLES")) {
  906. std::set<std::string> vars;
  907. vars.insert(&c_properties[lang_property_start],
  908. &c_properties[lang_property_start + lang_property_size]);
  909. vars.insert(&cxx_properties[lang_property_start],
  910. &cxx_properties[lang_property_start + lang_property_size]);
  911. vars.insert(&cuda_properties[lang_property_start],
  912. &cuda_properties[lang_property_start + lang_property_size]);
  913. vars.insert(&fortran_properties[lang_property_start],
  914. &fortran_properties[lang_property_start + lang_property_size]);
  915. vars.insert(&hip_properties[lang_property_start],
  916. &hip_properties[lang_property_start + lang_property_size]);
  917. vars.insert(&objc_properties[lang_property_start],
  918. &objc_properties[lang_property_start + lang_property_size]);
  919. vars.insert(&objcxx_properties[lang_property_start],
  920. &objcxx_properties[lang_property_start + lang_property_size]);
  921. vars.insert(&ispc_properties[lang_property_start],
  922. &ispc_properties[lang_property_start + lang_property_size]);
  923. vars.insert(&swift_properties[lang_property_start],
  924. &swift_properties[lang_property_start + lang_property_size]);
  925. vars.insert(kCMAKE_CUDA_ARCHITECTURES);
  926. vars.insert(kCMAKE_CUDA_RUNTIME_LIBRARY);
  927. vars.insert(kCMAKE_ENABLE_EXPORTS);
  928. vars.insert(kCMAKE_EXECUTABLE_ENABLE_EXPORTS);
  929. vars.insert(kCMAKE_SHARED_LIBRARY_ENABLE_EXPORTS);
  930. vars.insert(kCMAKE_HIP_ARCHITECTURES);
  931. vars.insert(kCMAKE_HIP_RUNTIME_LIBRARY);
  932. vars.insert(kCMAKE_ISPC_INSTRUCTION_SETS);
  933. vars.insert(kCMAKE_ISPC_HEADER_SUFFIX);
  934. vars.insert(kCMAKE_LINK_SEARCH_END_STATIC);
  935. vars.insert(kCMAKE_LINK_SEARCH_START_STATIC);
  936. vars.insert(kCMAKE_OSX_ARCHITECTURES);
  937. vars.insert(kCMAKE_OSX_DEPLOYMENT_TARGET);
  938. vars.insert(kCMAKE_OSX_SYSROOT);
  939. vars.insert(kCMAKE_APPLE_ARCH_SYSROOTS);
  940. vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
  941. vars.insert(kCMAKE_SYSROOT);
  942. vars.insert(kCMAKE_SYSROOT_COMPILE);
  943. vars.insert(kCMAKE_SYSROOT_LINK);
  944. vars.insert(kCMAKE_WARN_DEPRECATED);
  945. vars.emplace("CMAKE_MSVC_RUNTIME_LIBRARY"_s);
  946. vars.emplace("CMAKE_WATCOM_RUNTIME_LIBRARY"_s);
  947. vars.emplace("CMAKE_MSVC_DEBUG_INFORMATION_FORMAT"_s);
  948. if (cmValue varListStr = this->Makefile->GetDefinition(
  949. kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES)) {
  950. cmList varList{ *varListStr };
  951. vars.insert(varList.begin(), varList.end());
  952. }
  953. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0083) ==
  954. cmPolicies::NEW) {
  955. // To ensure full support of PIE, propagate cache variables
  956. // driving the link options
  957. vars.insert(&c_properties[pie_property_start],
  958. &c_properties[pie_property_start + pie_property_size]);
  959. vars.insert(&cxx_properties[pie_property_start],
  960. &cxx_properties[pie_property_start + pie_property_size]);
  961. vars.insert(&cuda_properties[pie_property_start],
  962. &cuda_properties[pie_property_start + pie_property_size]);
  963. vars.insert(&fortran_properties[pie_property_start],
  964. &fortran_properties[pie_property_start + pie_property_size]);
  965. vars.insert(&hip_properties[pie_property_start],
  966. &hip_properties[pie_property_start + pie_property_size]);
  967. vars.insert(&objc_properties[pie_property_start],
  968. &objc_properties[pie_property_start + pie_property_size]);
  969. vars.insert(&objcxx_properties[pie_property_start],
  970. &objcxx_properties[pie_property_start + pie_property_size]);
  971. vars.insert(&ispc_properties[pie_property_start],
  972. &ispc_properties[pie_property_start + pie_property_size]);
  973. vars.insert(&swift_properties[pie_property_start],
  974. &swift_properties[pie_property_start + pie_property_size]);
  975. }
  976. /* for the TRY_COMPILEs we want to be able to specify the architecture.
  977. So the user can set CMAKE_OSX_ARCHITECTURES to i386;ppc and then set
  978. CMAKE_TRY_COMPILE_OSX_ARCHITECTURES first to i386 and then to ppc to
  979. have the tests run for each specific architecture. Since
  980. cmLocalGenerator doesn't allow building for "the other"
  981. architecture only via CMAKE_OSX_ARCHITECTURES.
  982. */
  983. if (cmValue tcArchs = this->Makefile->GetDefinition(
  984. kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES)) {
  985. vars.erase(kCMAKE_OSX_ARCHITECTURES);
  986. std::string flag = cmStrCat("-DCMAKE_OSX_ARCHITECTURES=", *tcArchs);
  987. arguments.CMakeFlags.emplace_back(std::move(flag));
  988. cmakeVariables.emplace("CMAKE_OSX_ARCHITECTURES", *tcArchs);
  989. }
  990. // Pass down CMAKE_EXPERIMENTAL_* feature flags
  991. for (std::size_t i = 0;
  992. i < static_cast<std::size_t>(cmExperimental::Feature::Sentinel);
  993. i++) {
  994. auto const& data = cmExperimental::DataForFeature(
  995. static_cast<cmExperimental::Feature>(i));
  996. if (data.ForwardThroughTryCompile) {
  997. vars.insert(data.Variable);
  998. }
  999. }
  1000. for (std::string const& var : vars) {
  1001. if (cmValue val = this->Makefile->GetDefinition(var)) {
  1002. std::string flag = cmStrCat("-D", var, '=', *val);
  1003. arguments.CMakeFlags.emplace_back(std::move(flag));
  1004. cmakeVariables.emplace(var, *val);
  1005. }
  1006. }
  1007. }
  1008. if (this->Makefile->GetState()->UseGhsMultiIDE()) {
  1009. // Forward the GHS variables to the inner project cache.
  1010. for (std::string const& var : ghs_platform_vars) {
  1011. if (cmValue val = this->Makefile->GetDefinition(var)) {
  1012. std::string flag = cmStrCat("-D", var, "=\'", *val, '\'');
  1013. arguments.CMakeFlags.emplace_back(std::move(flag));
  1014. cmakeVariables.emplace(var, *val);
  1015. }
  1016. }
  1017. }
  1018. if (this->Makefile->GetCMakeInstance()->GetDebugTryCompile()) {
  1019. auto msg =
  1020. cmStrCat("Executing try_compile (", *arguments.CompileResultVariable,
  1021. ") in:\n ", this->BinaryDirectory);
  1022. this->Makefile->IssueMessage(MessageType::LOG, msg);
  1023. }
  1024. bool erroroc = cmSystemTools::GetErrorOccurredFlag();
  1025. cmSystemTools::ResetErrorOccurredFlag();
  1026. std::string output;
  1027. // actually do the try compile now that everything is setup
  1028. int res = this->Makefile->TryCompile(
  1029. sourceDirectory, this->BinaryDirectory, projectName, targetName,
  1030. this->SrcFileSignature, cmake::NO_BUILD_PARALLEL_LEVEL,
  1031. &arguments.CMakeFlags, output);
  1032. if (erroroc) {
  1033. cmSystemTools::SetErrorOccurred();
  1034. }
  1035. // set the result var to the return value to indicate success or failure
  1036. if (arguments.NoCache) {
  1037. this->Makefile->AddDefinition(*arguments.CompileResultVariable,
  1038. (res == 0 ? "TRUE" : "FALSE"));
  1039. } else {
  1040. this->Makefile->AddCacheDefinition(
  1041. *arguments.CompileResultVariable, (res == 0 ? "TRUE" : "FALSE"),
  1042. "Result of TRY_COMPILE", cmStateEnums::INTERNAL);
  1043. }
  1044. if (arguments.OutputVariable) {
  1045. this->Makefile->AddDefinition(*arguments.OutputVariable, output);
  1046. }
  1047. if (this->SrcFileSignature) {
  1048. std::string copyFileErrorMessage;
  1049. this->FindOutputFile(targetName);
  1050. if ((res == 0) && arguments.CopyFileTo) {
  1051. std::string const& copyFile = *arguments.CopyFileTo;
  1052. cmsys::SystemTools::CopyStatus status =
  1053. cmSystemTools::CopyFileAlways(this->OutputFile, copyFile);
  1054. if (!status) {
  1055. std::string err = status.GetString();
  1056. switch (status.Path) {
  1057. case cmsys::SystemTools::CopyStatus::SourcePath:
  1058. err = cmStrCat(err, " (input)");
  1059. break;
  1060. case cmsys::SystemTools::CopyStatus::DestPath:
  1061. err = cmStrCat(err, " (output)");
  1062. break;
  1063. default:
  1064. break;
  1065. }
  1066. /* clang-format off */
  1067. err = cmStrCat(
  1068. "Cannot copy output executable\n"
  1069. " '", this->OutputFile, "'\n"
  1070. "to destination specified by COPY_FILE:\n"
  1071. " '", copyFile, "'\n"
  1072. "because:\n"
  1073. " ", err, "\n",
  1074. this->FindErrorMessage);
  1075. /* clang-format on */
  1076. if (!arguments.CopyFileError) {
  1077. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, err);
  1078. return cm::nullopt;
  1079. }
  1080. copyFileErrorMessage = std::move(err);
  1081. }
  1082. }
  1083. if (arguments.CopyFileError) {
  1084. std::string const& copyFileError = *arguments.CopyFileError;
  1085. this->Makefile->AddDefinition(copyFileError, copyFileErrorMessage);
  1086. }
  1087. }
  1088. cmTryCompileResult result;
  1089. if (arguments.LogDescription) {
  1090. result.LogDescription = *arguments.LogDescription;
  1091. }
  1092. result.CMakeVariables = std::move(cmakeVariables);
  1093. result.SourceDirectory = sourceDirectory;
  1094. result.BinaryDirectory = this->BinaryDirectory;
  1095. result.Variable = *arguments.CompileResultVariable;
  1096. result.VariableCached = !arguments.NoCache;
  1097. result.Output = std::move(output);
  1098. result.ExitCode = res;
  1099. return cm::optional<cmTryCompileResult>(std::move(result));
  1100. }
  1101. bool cmCoreTryCompile::IsTemporary(std::string const& path)
  1102. {
  1103. return ((path.find("CMakeTmp") != std::string::npos) ||
  1104. (path.find("CMakeScratch") != std::string::npos));
  1105. }
  1106. void cmCoreTryCompile::CleanupFiles(std::string const& binDir)
  1107. {
  1108. if (binDir.empty()) {
  1109. return;
  1110. }
  1111. if (!IsTemporary(binDir)) {
  1112. cmSystemTools::Error(cmStrCat(
  1113. "TRY_COMPILE attempt to remove -rf directory that does not contain "
  1114. "CMakeTmp or CMakeScratch: \"",
  1115. binDir, '"'));
  1116. return;
  1117. }
  1118. cmsys::Directory dir;
  1119. dir.Load(binDir);
  1120. std::set<std::string> deletedFiles;
  1121. for (unsigned long i = 0; i < dir.GetNumberOfFiles(); ++i) {
  1122. const char* fileName = dir.GetFile(i);
  1123. if (strcmp(fileName, ".") != 0 && strcmp(fileName, "..") != 0 &&
  1124. // Do not delete NFS temporary files.
  1125. !cmHasPrefix(fileName, ".nfs")) {
  1126. if (deletedFiles.insert(fileName).second) {
  1127. std::string const fullPath = cmStrCat(binDir, '/', fileName);
  1128. if (cmSystemTools::FileIsSymlink(fullPath)) {
  1129. cmSystemTools::RemoveFile(fullPath);
  1130. } else if (cmSystemTools::FileIsDirectory(fullPath)) {
  1131. this->CleanupFiles(fullPath);
  1132. cmSystemTools::RemoveADirectory(fullPath);
  1133. } else {
  1134. #ifdef _WIN32
  1135. // Sometimes anti-virus software hangs on to new files so we
  1136. // cannot delete them immediately. Try a few times.
  1137. cmSystemTools::WindowsFileRetry retry =
  1138. cmSystemTools::GetWindowsFileRetry();
  1139. cmsys::Status status;
  1140. while (!((status = cmSystemTools::RemoveFile(fullPath))) &&
  1141. --retry.Count && cmSystemTools::FileExists(fullPath)) {
  1142. cmSystemTools::Delay(retry.Delay);
  1143. }
  1144. if (retry.Count == 0)
  1145. #else
  1146. cmsys::Status status = cmSystemTools::RemoveFile(fullPath);
  1147. if (!status)
  1148. #endif
  1149. {
  1150. this->Makefile->IssueMessage(
  1151. MessageType::FATAL_ERROR,
  1152. cmStrCat("The file:\n ", fullPath,
  1153. "\ncould not be removed:\n ", status.GetString()));
  1154. }
  1155. }
  1156. }
  1157. }
  1158. }
  1159. if (binDir.find("CMakeScratch") != std::string::npos) {
  1160. cmSystemTools::RemoveADirectory(binDir);
  1161. }
  1162. }
  1163. void cmCoreTryCompile::FindOutputFile(const std::string& targetName)
  1164. {
  1165. this->FindErrorMessage.clear();
  1166. this->OutputFile.clear();
  1167. std::string tmpOutputFile = "/";
  1168. tmpOutputFile += targetName;
  1169. if (this->Makefile->GetGlobalGenerator()->IsMultiConfig()) {
  1170. std::string const tcConfig =
  1171. this->Makefile->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
  1172. std::string const cfg = !tcConfig.empty()
  1173. ? cmSystemTools::UpperCase(tcConfig)
  1174. : TryCompileDefaultConfig;
  1175. tmpOutputFile = cmStrCat(tmpOutputFile, '_', cfg);
  1176. }
  1177. tmpOutputFile += "_loc";
  1178. std::string command = cmStrCat(this->BinaryDirectory, tmpOutputFile);
  1179. if (!cmSystemTools::FileExists(command)) {
  1180. std::ostringstream emsg;
  1181. emsg << "Unable to find the recorded try_compile output location:\n";
  1182. emsg << cmStrCat(" ", command, "\n");
  1183. this->FindErrorMessage = emsg.str();
  1184. return;
  1185. }
  1186. std::string outputFileLocation;
  1187. cmsys::ifstream ifs(command.c_str());
  1188. cmSystemTools::GetLineFromStream(ifs, outputFileLocation);
  1189. if (!cmSystemTools::FileExists(outputFileLocation)) {
  1190. std::ostringstream emsg;
  1191. emsg << "Recorded try_compile output location doesn't exist:\n";
  1192. emsg << cmStrCat(" ", outputFileLocation, "\n");
  1193. this->FindErrorMessage = emsg.str();
  1194. return;
  1195. }
  1196. this->OutputFile = cmSystemTools::CollapseFullPath(outputFileLocation);
  1197. }
  1198. std::string cmCoreTryCompile::WriteSource(std::string const& filename,
  1199. std::string const& content,
  1200. char const* command) const
  1201. {
  1202. if (!cmSystemTools::GetFilenamePath(filename).empty()) {
  1203. const auto& msg =
  1204. cmStrCat(command, " given invalid filename \"", filename, '"');
  1205. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, msg);
  1206. return {};
  1207. }
  1208. auto filepath = cmStrCat(this->BinaryDirectory, '/', filename);
  1209. cmsys::ofstream file{ filepath.c_str(), std::ios::out };
  1210. if (!file) {
  1211. const auto& msg =
  1212. cmStrCat(command, " failed to open \"", filename, "\" for writing");
  1213. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, msg);
  1214. return {};
  1215. }
  1216. file << content;
  1217. if (!file) {
  1218. const auto& msg = cmStrCat(command, " failed to write \"", filename, '"');
  1219. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, msg);
  1220. return {};
  1221. }
  1222. file.close();
  1223. return filepath;
  1224. }
  1225. void cmCoreTryCompile::WriteTryCompileEventFields(
  1226. cmConfigureLog& log, cmTryCompileResult const& compileResult)
  1227. {
  1228. #ifndef CMAKE_BOOTSTRAP
  1229. if (compileResult.LogDescription) {
  1230. log.WriteValue("description"_s, *compileResult.LogDescription);
  1231. }
  1232. log.BeginObject("directories"_s);
  1233. log.WriteValue("source"_s, compileResult.SourceDirectory);
  1234. log.WriteValue("binary"_s, compileResult.BinaryDirectory);
  1235. log.EndObject();
  1236. if (!compileResult.CMakeVariables.empty()) {
  1237. log.WriteValue("cmakeVariables"_s, compileResult.CMakeVariables);
  1238. }
  1239. log.BeginObject("buildResult"_s);
  1240. log.WriteValue("variable"_s, compileResult.Variable);
  1241. log.WriteValue("cached"_s, compileResult.VariableCached);
  1242. log.WriteLiteralTextBlock("stdout"_s, compileResult.Output);
  1243. log.WriteValue("exitCode"_s, compileResult.ExitCode);
  1244. log.EndObject();
  1245. #endif
  1246. }