Coverage Report

Created: 2026-02-09 06:05

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