cmCoreTryCompile.cxx 46 KB

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