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.

1252 lines
48 KiB

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