Coverage Report

Created: 2026-07-14 07:09

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