Coverage Report

Created: 2026-06-15 07:03

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