cmCoreTryCompile.cxx 50 KB

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