cmCoreTryCompile.cxx 57 KB

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