Coverage Report

Created: 2026-03-12 06:35

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 "cmExperimental.h"
22
#include "cmExportTryCompileFileGenerator.h"
23
#include "cmGlobalGenerator.h"
24
#include "cmList.h"
25
#include "cmMakefile.h"
26
#include "cmMessageType.h"
27
#include "cmPolicies.h"
28
#include "cmRange.h"
29
#include "cmScriptGenerator.h"
30
#include "cmState.h"
31
#include "cmStringAlgorithms.h"
32
#include "cmSystemTools.h"
33
#include "cmTarget.h"
34
#include "cmValue.h"
35
#include "cmVersion.h"
36
#include "cmake.h"
37
38
namespace {
39
constexpr char const* unique_binary_directory = "CMAKE_BINARY_DIR_USE_MKDTEMP";
40
41
std::array<cm::string_view, 9> const kLanguageNames{ {
42
  "C"_s,
43
  "CUDA"_s,
44
  "CXX"_s,
45
  "Fortran"_s,
46
  "HIP"_s,
47
  "ISPC"_s,
48
  "OBJC"_s,
49
  "OBJCXX"_s,
50
  "Swift"_s,
51
} };
52
53
std::string const kCMAKE_CUDA_ARCHITECTURES = "CMAKE_CUDA_ARCHITECTURES";
54
std::string const kCMAKE_CUDA_RUNTIME_LIBRARY = "CMAKE_CUDA_RUNTIME_LIBRARY";
55
std::string const kCMAKE_CXX_SCAN_FOR_MODULES = "CMAKE_CXX_SCAN_FOR_MODULES";
56
std::string const kCMAKE_ENABLE_EXPORTS = "CMAKE_ENABLE_EXPORTS";
57
std::string const kCMAKE_EXECUTABLE_ENABLE_EXPORTS =
58
  "CMAKE_EXECUTABLE_ENABLE_EXPORTS";
59
std::string const kCMAKE_SHARED_LIBRARY_ENABLE_EXPORTS =
60
  "CMAKE_SHARED_LIBRARY_ENABLE_EXPORTS";
61
std::string const kCMAKE_HIP_ARCHITECTURES = "CMAKE_HIP_ARCHITECTURES";
62
std::string const kCMAKE_HIP_PLATFORM = "CMAKE_HIP_PLATFORM";
63
std::string const kCMAKE_HIP_RUNTIME_LIBRARY = "CMAKE_HIP_RUNTIME_LIBRARY";
64
std::string const kCMAKE_ISPC_INSTRUCTION_SETS = "CMAKE_ISPC_INSTRUCTION_SETS";
65
std::string const kCMAKE_ISPC_HEADER_SUFFIX = "CMAKE_ISPC_HEADER_SUFFIX";
66
std::string const kCMAKE_LINKER_TYPE = "CMAKE_LINKER_TYPE";
67
std::string const kCMAKE_LINK_SEARCH_END_STATIC =
68
  "CMAKE_LINK_SEARCH_END_STATIC";
69
std::string const kCMAKE_LINK_SEARCH_START_STATIC =
70
  "CMAKE_LINK_SEARCH_START_STATIC";
71
std::string const kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT =
72
  "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT";
73
std::string const kCMAKE_OSX_ARCHITECTURES = "CMAKE_OSX_ARCHITECTURES";
74
std::string const kCMAKE_OSX_DEPLOYMENT_TARGET = "CMAKE_OSX_DEPLOYMENT_TARGET";
75
std::string const kCMAKE_OSX_SYSROOT = "CMAKE_OSX_SYSROOT";
76
std::string const kCMAKE_APPLE_ARCH_SYSROOTS = "CMAKE_APPLE_ARCH_SYSROOTS";
77
std::string const kCMAKE_POSITION_INDEPENDENT_CODE =
78
  "CMAKE_POSITION_INDEPENDENT_CODE";
79
std::string const kCMAKE_SYSROOT = "CMAKE_SYSROOT";
80
std::string const kCMAKE_SYSROOT_COMPILE = "CMAKE_SYSROOT_COMPILE";
81
std::string const kCMAKE_SYSROOT_LINK = "CMAKE_SYSROOT_LINK";
82
std::string const kCMAKE_ARMClang_CMP0123 = "CMAKE_ARMClang_CMP0123";
83
std::string const kCMAKE_TRY_COMPILE_OSX_ARCHITECTURES =
84
  "CMAKE_TRY_COMPILE_OSX_ARCHITECTURES";
85
std::string const kCMAKE_TRY_COMPILE_PLATFORM_VARIABLES =
86
  "CMAKE_TRY_COMPILE_PLATFORM_VARIABLES";
87
std::string const kCMAKE_WARN_DEPRECATED = "CMAKE_WARN_DEPRECATED";
88
std::string const kCMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT =
89
  "CMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT";
90
std::string const kCMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT =
91
  "CMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT";
92
std::string const kCMAKE_MSVC_RUNTIME_CHECKS_DEFAULT =
93
  "CMAKE_MSVC_RUNTIME_CHECKS_DEFAULT";
94
std::string const kCMAKE_MSVC_CMP0197 = "CMAKE_MSVC_CMP0197";
95
96
/* GHS Multi platform variables */
97
std::set<std::string> const ghs_platform_vars{
98
  "GHS_TARGET_PLATFORM", "GHS_PRIMARY_TARGET", "GHS_TOOLSET_ROOT",
99
  "GHS_OS_ROOT",         "GHS_OS_DIR",         "GHS_BSP_NAME",
100
  "GHS_OS_DIR_OPTION"
101
};
102
using Arguments = cmCoreTryCompile::Arguments;
103
104
ArgumentParser::Continue TryCompileLangProp(Arguments& args,
105
                                            cm::string_view key,
106
                                            cm::string_view val)
107
0
{
108
0
  args.LangProps[std::string(key)] = std::string(val);
109
0
  return ArgumentParser::Continue::No;
110
0
}
111
112
ArgumentParser::Continue TryCompileCompileDefs(Arguments& args,
113
                                               cm::string_view val)
114
0
{
115
0
  args.CompileDefs.append(val);
116
0
  return ArgumentParser::Continue::Yes;
117
0
}
118
119
cmArgumentParser<Arguments> makeTryCompileParser(
120
  cmArgumentParser<Arguments> const& base)
121
12
{
122
12
  return cmArgumentParser<Arguments>{ base }.Bind("OUTPUT_VARIABLE"_s,
123
12
                                                  &Arguments::OutputVariable);
124
12
}
125
126
cmArgumentParser<Arguments> makeTryRunParser(
127
  cmArgumentParser<Arguments> const& base)
128
8
{
129
8
  return cmArgumentParser<Arguments>{ base }
130
8
    .Bind("COMPILE_OUTPUT_VARIABLE"_s, &Arguments::CompileOutputVariable)
131
8
    .Bind("RUN_OUTPUT_VARIABLE"_s, &Arguments::RunOutputVariable)
132
8
    .Bind("RUN_OUTPUT_STDOUT_VARIABLE"_s, &Arguments::RunOutputStdOutVariable)
133
8
    .Bind("RUN_OUTPUT_STDERR_VARIABLE"_s, &Arguments::RunOutputStdErrVariable)
134
8
    .Bind("WORKING_DIRECTORY"_s, &Arguments::RunWorkingDirectory)
135
8
    .Bind("ARGS"_s, &Arguments::RunArgs)
136
8
    /* keep semicolon on own line */;
137
8
}
138
139
#define BIND_LANG_PROPS(lang)                                                 \
140
  Bind(#lang "_STANDARD"_s, TryCompileLangProp)                               \
141
    .Bind(#lang "_STANDARD_REQUIRED"_s, TryCompileLangProp)                   \
142
    .Bind(#lang "_EXTENSIONS"_s, TryCompileLangProp)
143
144
auto const TryCompileBaseArgParser =
145
  cmArgumentParser<Arguments>{}
146
    .Bind(0, &Arguments::CompileResultVariable)
147
    .Bind("LOG_DESCRIPTION"_s, &Arguments::LogDescription)
148
    .Bind("NO_CACHE"_s, &Arguments::NoCache)
149
    .Bind("NO_LOG"_s, &Arguments::NoLog)
150
    .Bind("CMAKE_FLAGS"_s, &Arguments::CMakeFlags)
151
    .Bind("__CMAKE_INTERNAL"_s, &Arguments::CMakeInternal)
152
  /* keep semicolon on own line */;
153
154
auto const TryCompileBaseSourcesArgParser =
155
  cmArgumentParser<Arguments>{ TryCompileBaseArgParser }
156
    .Bind("SOURCES_TYPE"_s, &Arguments::SetSourceType)
157
    .BindWithContext("SOURCES"_s, &Arguments::Sources,
158
                     &Arguments::SourceTypeContext)
159
    .Bind("COMPILE_DEFINITIONS"_s, TryCompileCompileDefs,
160
          ArgumentParser::ExpectAtLeast{ 0 })
161
    .Bind("LINK_LIBRARIES"_s, &Arguments::LinkLibraries)
162
    .Bind("LINK_OPTIONS"_s, &Arguments::LinkOptions)
163
    .Bind("LINKER_LANGUAGE"_s, &Arguments::LinkerLanguage)
164
    .Bind("COPY_FILE"_s, &Arguments::CopyFileTo)
165
    .Bind("COPY_FILE_ERROR"_s, &Arguments::CopyFileError)
166
    .BIND_LANG_PROPS(C)
167
    .BIND_LANG_PROPS(CUDA)
168
    .BIND_LANG_PROPS(CXX)
169
    .BIND_LANG_PROPS(HIP)
170
    .BIND_LANG_PROPS(OBJC)
171
    .BIND_LANG_PROPS(OBJCXX)
172
  /* keep semicolon on own line */;
173
174
auto const TryCompileBaseNewSourcesArgParser =
175
  cmArgumentParser<Arguments>{ TryCompileBaseSourcesArgParser }
176
    .BindWithContext("SOURCE_FROM_CONTENT"_s, &Arguments::SourceFromContent,
177
                     &Arguments::SourceTypeContext)
178
    .BindWithContext("SOURCE_FROM_VAR"_s, &Arguments::SourceFromVar,
179
                     &Arguments::SourceTypeContext)
180
    .BindWithContext("SOURCE_FROM_FILE"_s, &Arguments::SourceFromFile,
181
                     &Arguments::SourceTypeContext)
182
  /* keep semicolon on own line */;
183
184
auto const TryCompileBaseProjectArgParser =
185
  cmArgumentParser<Arguments>{ TryCompileBaseArgParser }
186
    .Bind("PROJECT"_s, &Arguments::ProjectName)
187
    .Bind("SOURCE_DIR"_s, &Arguments::SourceDirectoryOrFile)
188
    .Bind("BINARY_DIR"_s, &Arguments::BinaryDirectory)
189
    .Bind("TARGET"_s, &Arguments::TargetName)
190
  /* keep semicolon on own line */;
191
192
auto const TryCompileProjectArgParser =
193
  makeTryCompileParser(TryCompileBaseProjectArgParser);
194
195
auto const TryCompileSourcesArgParser =
196
  makeTryCompileParser(TryCompileBaseNewSourcesArgParser);
197
198
auto const TryCompileOldArgParser =
199
  makeTryCompileParser(TryCompileBaseSourcesArgParser)
200
    .Bind(1, &Arguments::BinaryDirectory)
201
    .Bind(2, &Arguments::SourceDirectoryOrFile)
202
    .Bind(3, &Arguments::ProjectName)
203
    .Bind(4, &Arguments::TargetName)
204
  /* keep semicolon on own line */;
205
206
auto const TryRunSourcesArgParser =
207
  makeTryRunParser(TryCompileBaseNewSourcesArgParser);
208
209
auto const TryRunOldArgParser = makeTryRunParser(TryCompileOldArgParser);
210
211
#undef BIND_LANG_PROPS
212
213
std::string const TryCompileDefaultConfig = "DEBUG";
214
}
215
216
ArgumentParser::Continue cmCoreTryCompile::Arguments::SetSourceType(
217
  cm::string_view sourceType)
218
0
{
219
0
  bool matched = false;
220
0
  if (sourceType == "NORMAL"_s) {
221
0
    this->SourceTypeContext = SourceType::Normal;
222
0
    matched = true;
223
0
  } else if (sourceType == "CXX_MODULE"_s) {
224
0
    this->SourceTypeContext = SourceType::CxxModule;
225
0
    matched = true;
226
0
  }
227
228
0
  if (!matched && this->SourceTypeError.empty()) {
229
    // Only remember one error at a time; all other errors related to argument
230
    // parsing are "indicate one error and return" anyways.
231
0
    this->SourceTypeError =
232
0
      cmStrCat("Invalid 'SOURCE_TYPE' '", sourceType,
233
0
               "'; must be one of 'SOURCE' or 'CXX_MODULE'");
234
0
  }
235
0
  return ArgumentParser::Continue::Yes;
236
0
}
237
238
Arguments cmCoreTryCompile::ParseArgs(
239
  cmRange<std::vector<std::string>::const_iterator> args,
240
  cmArgumentParser<Arguments> const& parser,
241
  std::vector<std::string>& unparsedArguments)
242
0
{
243
0
  Arguments arguments{ this->Makefile };
244
0
  parser.Parse(arguments, args, &unparsedArguments, 0);
245
0
  if (!arguments.MaybeReportError(*(this->Makefile)) &&
246
0
      !unparsedArguments.empty()) {
247
0
    std::string m = "Unknown arguments:";
248
0
    for (auto const& i : unparsedArguments) {
249
0
      m = cmStrCat(m, "\n  \"", i, '"');
250
0
    }
251
0
    this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, m);
252
0
  }
253
0
  return arguments;
254
0
}
255
256
Arguments cmCoreTryCompile::ParseArgs(
257
  cmRange<std::vector<std::string>::const_iterator> args, bool isTryRun)
258
0
{
259
0
  std::vector<std::string> unparsedArguments;
260
0
  auto const& second = *(++args.begin());
261
262
0
  if (!isTryRun && second == "PROJECT") {
263
    // New PROJECT signature (try_compile only).
264
0
    auto arguments =
265
0
      this->ParseArgs(args, TryCompileProjectArgParser, unparsedArguments);
266
0
    if (!arguments.BinaryDirectory) {
267
0
      arguments.BinaryDirectory = unique_binary_directory;
268
0
    }
269
0
    return arguments;
270
0
  }
271
272
0
  if (cmHasLiteralPrefix(second, "SOURCE")) {
273
    // New SOURCES signature.
274
0
    auto arguments = this->ParseArgs(
275
0
      args, isTryRun ? TryRunSourcesArgParser : TryCompileSourcesArgParser,
276
0
      unparsedArguments);
277
0
    arguments.BinaryDirectory = unique_binary_directory;
278
0
    return arguments;
279
0
  }
280
281
  // Old signature.
282
0
  auto arguments = this->ParseArgs(
283
0
    args, isTryRun ? TryRunOldArgParser : TryCompileOldArgParser,
284
0
    unparsedArguments);
285
  // For historical reasons, treat some empty-valued keyword
286
  // arguments as if they were not specified at all.
287
0
  if (arguments.OutputVariable && arguments.OutputVariable->empty()) {
288
0
    arguments.OutputVariable = cm::nullopt;
289
0
  }
290
0
  if (isTryRun) {
291
0
    if (arguments.CompileOutputVariable &&
292
0
        arguments.CompileOutputVariable->empty()) {
293
0
      arguments.CompileOutputVariable = cm::nullopt;
294
0
    }
295
0
    if (arguments.RunOutputVariable && arguments.RunOutputVariable->empty()) {
296
0
      arguments.RunOutputVariable = cm::nullopt;
297
0
    }
298
0
    if (arguments.RunOutputStdOutVariable &&
299
0
        arguments.RunOutputStdOutVariable->empty()) {
300
0
      arguments.RunOutputStdOutVariable = cm::nullopt;
301
0
    }
302
0
    if (arguments.RunOutputStdErrVariable &&
303
0
        arguments.RunOutputStdErrVariable->empty()) {
304
0
      arguments.RunOutputStdErrVariable = cm::nullopt;
305
0
    }
306
0
    if (arguments.RunWorkingDirectory &&
307
0
        arguments.RunWorkingDirectory->empty()) {
308
0
      arguments.RunWorkingDirectory = cm::nullopt;
309
0
    }
310
0
  }
311
0
  return arguments;
312
0
}
313
314
cm::optional<cmTryCompileResult> cmCoreTryCompile::TryCompileCode(
315
  Arguments& arguments, cmStateEnums::TargetType targetType)
316
0
{
317
0
  this->OutputFile.clear();
318
  // which signature were we called with ?
319
0
  this->SrcFileSignature = true;
320
321
0
  bool useUniqueBinaryDirectory = false;
322
0
  std::string sourceDirectory;
323
0
  std::string projectName;
324
0
  std::string targetName;
325
0
  if (arguments.ProjectName) {
326
0
    this->SrcFileSignature = false;
327
0
    if (!arguments.SourceDirectoryOrFile ||
328
0
        arguments.SourceDirectoryOrFile->empty()) {
329
0
      this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
330
0
                                   "No <srcdir> specified.");
331
0
      return cm::nullopt;
332
0
    }
333
0
    sourceDirectory = *arguments.SourceDirectoryOrFile;
334
0
    projectName = *arguments.ProjectName;
335
0
    if (arguments.TargetName) {
336
0
      targetName = *arguments.TargetName;
337
0
    }
338
0
  } else {
339
0
    projectName = "CMAKE_TRY_COMPILE";
340
    /* Use a random file name to avoid rapid creation and deletion
341
       of the same executable name (some filesystems fail on that).  */
342
0
    char targetNameBuf[64];
343
0
    snprintf(targetNameBuf, sizeof(targetNameBuf), "cmTC_%05x",
344
0
             cmSystemTools::RandomNumber() & 0xFFFFF);
345
0
    targetName = targetNameBuf;
346
0
  }
347
348
0
  if (!arguments.BinaryDirectory || arguments.BinaryDirectory->empty()) {
349
0
    this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
350
0
                                 "No <bindir> specified.");
351
0
    return cm::nullopt;
352
0
  }
353
0
  if (*arguments.BinaryDirectory == unique_binary_directory) {
354
    // leave empty until we're ready to create it, so we don't try to remove
355
    // a non-existing directory if we abort due to e.g. bad arguments
356
0
    this->BinaryDirectory.clear();
357
0
    useUniqueBinaryDirectory = true;
358
0
  } else {
359
0
    if (!cmSystemTools::FileIsFullPath(*arguments.BinaryDirectory)) {
360
0
      this->Makefile->IssueMessage(
361
0
        MessageType::FATAL_ERROR,
362
0
        cmStrCat("<bindir> is not an absolute path:\n '",
363
0
                 *arguments.BinaryDirectory, '\''));
364
0
      return cm::nullopt;
365
0
    }
366
0
    this->BinaryDirectory = *arguments.BinaryDirectory;
367
    // compute the binary dir when TRY_COMPILE is called with a src file
368
    // signature
369
0
    if (this->SrcFileSignature) {
370
0
      this->BinaryDirectory += "/CMakeFiles/CMakeTmp";
371
0
    }
372
0
  }
373
374
0
  std::vector<std::string> targets;
375
0
  if (arguments.LinkLibraries) {
376
0
    for (std::string const& i : *arguments.LinkLibraries) {
377
0
      if (cmTarget* tgt = this->Makefile->FindTargetToUse(i)) {
378
0
        switch (tgt->GetType()) {
379
0
          case cmStateEnums::SHARED_LIBRARY:
380
0
          case cmStateEnums::STATIC_LIBRARY:
381
0
          case cmStateEnums::INTERFACE_LIBRARY:
382
0
          case cmStateEnums::UNKNOWN_LIBRARY:
383
0
            break;
384
0
          case cmStateEnums::EXECUTABLE:
385
0
            if (tgt->IsExecutableWithExports()) {
386
0
              break;
387
0
            }
388
0
            CM_FALLTHROUGH;
389
0
          default:
390
0
            this->Makefile->IssueMessage(
391
0
              MessageType::FATAL_ERROR,
392
0
              cmStrCat("Only libraries may be used as try_compile or try_run "
393
0
                       "IMPORTED LINK_LIBRARIES.  Got ",
394
0
                       tgt->GetName(), " of type ",
395
0
                       cmState::GetTargetTypeName(tgt->GetType()), '.'));
396
0
            return cm::nullopt;
397
0
        }
398
0
        if (tgt->IsImported()) {
399
0
          targets.emplace_back(i);
400
0
        }
401
0
      }
402
0
    }
403
0
  }
404
405
0
  if (arguments.CopyFileTo && arguments.CopyFileTo->empty()) {
406
0
    this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
407
0
                                 "COPY_FILE must be followed by a file path");
408
0
    return cm::nullopt;
409
0
  }
410
411
0
  if (arguments.CopyFileError && arguments.CopyFileError->empty()) {
412
0
    this->Makefile->IssueMessage(
413
0
      MessageType::FATAL_ERROR,
414
0
      "COPY_FILE_ERROR must be followed by a variable name");
415
0
    return cm::nullopt;
416
0
  }
417
418
0
  if (arguments.CopyFileError && !arguments.CopyFileTo) {
419
0
    this->Makefile->IssueMessage(
420
0
      MessageType::FATAL_ERROR,
421
0
      "COPY_FILE_ERROR may be used only with COPY_FILE");
422
0
    return cm::nullopt;
423
0
  }
424
425
0
  if (arguments.Sources && arguments.Sources->empty()) {
426
0
    this->Makefile->IssueMessage(
427
0
      MessageType::FATAL_ERROR,
428
0
      "SOURCES must be followed by at least one source file");
429
0
    return cm::nullopt;
430
0
  }
431
432
0
  if (this->SrcFileSignature) {
433
0
    if (arguments.SourceFromContent &&
434
0
        arguments.SourceFromContent->size() % 2) {
435
0
      this->Makefile->IssueMessage(
436
0
        MessageType::FATAL_ERROR,
437
0
        "SOURCE_FROM_CONTENT requires exactly two arguments");
438
0
      return cm::nullopt;
439
0
    }
440
0
    if (arguments.SourceFromVar && arguments.SourceFromVar->size() % 2) {
441
0
      this->Makefile->IssueMessage(
442
0
        MessageType::FATAL_ERROR,
443
0
        "SOURCE_FROM_VAR requires exactly two arguments");
444
0
      return cm::nullopt;
445
0
    }
446
0
    if (arguments.SourceFromFile && arguments.SourceFromFile->size() % 2) {
447
0
      this->Makefile->IssueMessage(
448
0
        MessageType::FATAL_ERROR,
449
0
        "SOURCE_FROM_FILE requires exactly two arguments");
450
0
      return cm::nullopt;
451
0
    }
452
0
    if (!arguments.SourceTypeError.empty()) {
453
0
      this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
454
0
                                   arguments.SourceTypeError);
455
0
      return cm::nullopt;
456
0
    }
457
0
  } else {
458
    // only valid for srcfile signatures
459
0
    if (!arguments.LangProps.empty()) {
460
0
      this->Makefile->IssueMessage(
461
0
        MessageType::FATAL_ERROR,
462
0
        cmStrCat(arguments.LangProps.begin()->first,
463
0
                 " allowed only in source file signature"));
464
0
      return cm::nullopt;
465
0
    }
466
0
    if (!arguments.CompileDefs.empty()) {
467
0
      this->Makefile->IssueMessage(
468
0
        MessageType::FATAL_ERROR,
469
0
        "COMPILE_DEFINITIONS allowed only in source file signature");
470
0
      return cm::nullopt;
471
0
    }
472
0
    if (arguments.CopyFileTo) {
473
0
      this->Makefile->IssueMessage(
474
0
        MessageType::FATAL_ERROR,
475
0
        "COPY_FILE allowed only in source file signature");
476
0
      return cm::nullopt;
477
0
    }
478
0
  }
479
480
  // make sure the binary directory exists
481
0
  if (useUniqueBinaryDirectory) {
482
0
    this->BinaryDirectory =
483
0
      cmStrCat(this->Makefile->GetHomeOutputDirectory(),
484
0
               "/CMakeFiles/CMakeScratch/TryCompile-XXXXXX");
485
0
    cmSystemTools::MakeTempDirectory(this->BinaryDirectory);
486
0
  } else {
487
0
    cmSystemTools::MakeDirectory(this->BinaryDirectory);
488
0
  }
489
490
  // do not allow recursive try Compiles
491
0
  if (this->BinaryDirectory == this->Makefile->GetHomeOutputDirectory()) {
492
0
    std::ostringstream e;
493
0
    e << "Attempt at a recursive or nested TRY_COMPILE in directory\n"
494
0
      << "  " << this->BinaryDirectory << "\n";
495
0
    this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
496
0
    return cm::nullopt;
497
0
  }
498
499
0
  std::map<std::string, std::string> cmakeVariables;
500
501
0
  std::string outFileName = cmStrCat(this->BinaryDirectory, "/CMakeLists.txt");
502
  // which signature are we using? If we are using var srcfile bindir
503
0
  if (this->SrcFileSignature) {
504
    // remove any CMakeCache.txt files so we will have a clean test
505
0
    std::string ccFile = cmStrCat(this->BinaryDirectory, "/CMakeCache.txt");
506
0
    cmSystemTools::RemoveFile(ccFile);
507
508
    // Choose sources.
509
0
    std::vector<std::pair<std::string, Arguments::SourceType>> sources;
510
0
    if (arguments.Sources) {
511
0
      sources = std::move(*arguments.Sources);
512
0
    } else if (arguments.SourceDirectoryOrFile) {
513
0
      sources.emplace_back(*arguments.SourceDirectoryOrFile,
514
0
                           Arguments::SourceType::Directory);
515
0
    }
516
0
    if (arguments.SourceFromContent) {
517
0
      auto const k = arguments.SourceFromContent->size();
518
0
      for (auto i = decltype(k){ 0 }; i < k; i += 2) {
519
0
        auto const& name = (*arguments.SourceFromContent)[i + 0].first;
520
0
        auto const& content = (*arguments.SourceFromContent)[i + 1].first;
521
0
        auto out = this->WriteSource(name, content, "SOURCE_FROM_CONTENT");
522
0
        if (out.empty()) {
523
0
          return cm::nullopt;
524
0
        }
525
0
        sources.emplace_back(std::move(out),
526
0
                             (*arguments.SourceFromContent)[i + 0].second);
527
0
      }
528
0
    }
529
0
    if (arguments.SourceFromVar) {
530
0
      auto const k = arguments.SourceFromVar->size();
531
0
      for (auto i = decltype(k){ 0 }; i < k; i += 2) {
532
0
        auto const& name = (*arguments.SourceFromVar)[i + 0].first;
533
0
        auto const& var = (*arguments.SourceFromVar)[i + 1].first;
534
0
        auto const& content = this->Makefile->GetDefinition(var);
535
0
        auto out = this->WriteSource(name, content, "SOURCE_FROM_VAR");
536
0
        if (out.empty()) {
537
0
          return cm::nullopt;
538
0
        }
539
0
        sources.emplace_back(std::move(out),
540
0
                             (*arguments.SourceFromVar)[i + 0].second);
541
0
      }
542
0
    }
543
0
    if (arguments.SourceFromFile) {
544
0
      auto const k = arguments.SourceFromFile->size();
545
0
      for (auto i = decltype(k){ 0 }; i < k; i += 2) {
546
0
        auto const& dst = (*arguments.SourceFromFile)[i + 0].first;
547
0
        auto const& src = (*arguments.SourceFromFile)[i + 1].first;
548
549
0
        if (!cmSystemTools::GetFilenamePath(dst).empty()) {
550
0
          auto const& msg =
551
0
            cmStrCat("SOURCE_FROM_FILE given invalid filename \"", dst, '"');
552
0
          this->Makefile->IssueMessage(MessageType::FATAL_ERROR, msg);
553
0
          return cm::nullopt;
554
0
        }
555
556
0
        auto dstPath = cmStrCat(this->BinaryDirectory, '/', dst);
557
0
        auto const result = cmSystemTools::CopyFileAlways(src, dstPath);
558
0
        if (!result.IsSuccess()) {
559
0
          auto const& msg = cmStrCat("SOURCE_FROM_FILE failed to copy \"", src,
560
0
                                     "\": ", result.GetString());
561
0
          this->Makefile->IssueMessage(MessageType::FATAL_ERROR, msg);
562
0
          return cm::nullopt;
563
0
        }
564
565
0
        sources.emplace_back(std::move(dstPath),
566
0
                             (*arguments.SourceFromFile)[i + 0].second);
567
0
      }
568
0
    }
569
    // TODO: ensure sources is not empty
570
571
    // Detect languages to enable.
572
0
    cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
573
0
    std::set<std::string> testLangs;
574
0
    for (auto const& source : sources) {
575
0
      auto const& si = source.first;
576
0
      std::string ext = cmSystemTools::GetFilenameLastExtension(si);
577
0
      cm::string_view lang = gg->GetLanguageFromExtension(ext);
578
0
      if (!lang.empty()) {
579
0
        testLangs.insert(std::string(lang));
580
0
      } else {
581
0
        std::ostringstream err;
582
0
        err << "Unknown extension \"" << ext
583
0
            << "\" for file\n"
584
0
               "  "
585
0
            << si
586
0
            << "\n"
587
0
               "try_compile() works only for enabled languages.  "
588
0
               "Currently these are:\n  ";
589
0
        std::vector<std::string> langs;
590
0
        gg->GetEnabledLanguages(langs);
591
0
        err << cmJoin(langs, " ");
592
0
        err << "\nSee project() command to enable other languages.";
593
0
        this->Makefile->IssueMessage(MessageType::FATAL_ERROR, err.str());
594
0
        return cm::nullopt;
595
0
      }
596
0
    }
597
598
    // when the only language is ISPC we know that the output
599
    // type must by a static library
600
0
    if (testLangs.size() == 1 && testLangs.count("ISPC") == 1) {
601
0
      targetType = cmStateEnums::STATIC_LIBRARY;
602
0
    }
603
604
0
    std::string const tcConfig =
605
0
      this->Makefile->GetSafeDefinition("CMAKE_TRY_COMPILE_CONFIGURATION");
606
607
    // we need to create a directory and CMakeLists file etc...
608
    // first create the directories
609
0
    sourceDirectory = this->BinaryDirectory;
610
611
    // now create a CMakeLists.txt file in that directory
612
0
    FILE* fout = cmsys::SystemTools::Fopen(outFileName, "w");
613
0
    if (!fout) {
614
0
      this->Makefile->IssueMessage(
615
0
        MessageType::FATAL_ERROR,
616
0
        cmStrCat("Failed to open\n"
617
0
                 "  ",
618
0
                 outFileName, '\n', cmSystemTools::GetLastSystemError()));
619
0
      return cm::nullopt;
620
0
    }
621
622
0
    cmValue def = this->Makefile->GetDefinition("CMAKE_MODULE_PATH");
623
0
    fprintf(fout, "cmake_minimum_required(VERSION %u.%u.%u.%u)\n",
624
0
            cmVersion::GetMajorVersion(), cmVersion::GetMinorVersion(),
625
0
            cmVersion::GetPatchVersion(), cmVersion::GetTweakVersion());
626
0
    if (def) {
627
0
      fprintf(fout, "set(CMAKE_MODULE_PATH \"%s\")\n", def->c_str());
628
0
      cmakeVariables.emplace("CMAKE_MODULE_PATH", *def);
629
0
    }
630
631
    /* Set MSVC runtime library policy to match our selection.  */
632
0
    if (cmValue msvcRuntimeLibraryDefault =
633
0
          this->Makefile->GetDefinition(kCMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT)) {
634
0
      fprintf(fout, "cmake_policy(SET CMP0091 %s)\n",
635
0
              !msvcRuntimeLibraryDefault->empty() ? "NEW" : "OLD");
636
0
    }
637
638
    /* Set Watcom runtime library policy to match our selection.  */
639
0
    if (cmValue watcomRuntimeLibraryDefault = this->Makefile->GetDefinition(
640
0
          kCMAKE_WATCOM_RUNTIME_LIBRARY_DEFAULT)) {
641
0
      fprintf(fout, "cmake_policy(SET CMP0136 %s)\n",
642
0
              !watcomRuntimeLibraryDefault->empty() ? "NEW" : "OLD");
643
0
    }
644
645
    /* Set CUDA architectures policy to match outer project.  */
646
0
    if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0104) !=
647
0
          cmPolicies::NEW &&
648
0
        testLangs.find("CUDA") != testLangs.end() &&
649
0
        this->Makefile->GetSafeDefinition(kCMAKE_CUDA_ARCHITECTURES).empty()) {
650
0
      fprintf(fout, "cmake_policy(SET CMP0104 OLD)\n");
651
0
    }
652
653
    /* Set ARMClang cpu/arch policy to match outer project.  */
654
0
    if (cmValue cmp0123 =
655
0
          this->Makefile->GetDefinition(kCMAKE_ARMClang_CMP0123)) {
656
0
      fprintf(fout, "cmake_policy(SET CMP0123 %s)\n",
657
0
              *cmp0123 == "NEW"_s ? "NEW" : "OLD");
658
0
    }
659
660
    /* Set MSVC debug information format policy to match our selection.  */
661
0
    if (cmValue msvcDebugInformationFormatDefault =
662
0
          this->Makefile->GetDefinition(
663
0
            kCMAKE_MSVC_DEBUG_INFORMATION_FORMAT_DEFAULT)) {
664
0
      fprintf(fout, "cmake_policy(SET CMP0141 %s)\n",
665
0
              !msvcDebugInformationFormatDefault->empty() ? "NEW" : "OLD");
666
0
    }
667
668
    /* Set MSVC runtime checks policy to match our selection.  */
669
0
    if (cmValue msvcRuntimeChecksDefault =
670
0
          this->Makefile->GetDefinition(kCMAKE_MSVC_RUNTIME_CHECKS_DEFAULT)) {
671
0
      fprintf(fout, "cmake_policy(SET CMP0184 %s)\n",
672
0
              !msvcRuntimeChecksDefault->empty() ? "NEW" : "OLD");
673
0
    }
674
675
    /* Set cache/normal variable policy to match outer project.
676
       It may affect toolchain files.  */
677
0
    if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) !=
678
0
        cmPolicies::NEW) {
679
0
      fprintf(fout, "cmake_policy(SET CMP0126 OLD)\n");
680
0
    }
681
682
    /* Set language extensions policy to match outer project.  */
683
0
    if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0128) !=
684
0
        cmPolicies::NEW) {
685
0
      fprintf(fout, "cmake_policy(SET CMP0128 OLD)\n");
686
0
    }
687
688
    /* Set MSVC link -machine: policy to match outer project.  */
689
0
    if (cmValue cmp0197 = this->Makefile->GetDefinition(kCMAKE_MSVC_CMP0197)) {
690
0
      fprintf(fout, "cmake_policy(SET CMP0197 %s)\n",
691
0
              *cmp0197 == "NEW"_s ? "NEW" : "OLD");
692
0
    }
693
694
0
    std::string projectLangs;
695
0
    for (std::string const& li : testLangs) {
696
0
      projectLangs += cmStrCat(' ', li);
697
0
      std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
698
0
      std::string rulesOverrideLang = cmStrCat(rulesOverrideBase, '_', li);
699
0
      if (cmValue rulesOverridePath =
700
0
            this->Makefile->GetDefinition(rulesOverrideLang)) {
701
0
        fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(),
702
0
                rulesOverridePath->c_str());
703
0
        cmakeVariables.emplace(rulesOverrideLang, *rulesOverridePath);
704
0
      } else if (cmValue rulesOverridePath2 =
705
0
                   this->Makefile->GetDefinition(rulesOverrideBase)) {
706
0
        fprintf(fout, "set(%s \"%s\")\n", rulesOverrideBase.c_str(),
707
0
                rulesOverridePath2->c_str());
708
0
        cmakeVariables.emplace(rulesOverrideBase, *rulesOverridePath2);
709
0
      }
710
0
    }
711
0
    fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
712
0
    if (arguments.CMakeInternal == "ABI") {
713
      // This is the ABI detection step, also used for implicit includes.
714
      // Erase any include_directories() calls from the toolchain file so
715
      // that we do not see them as implicit.  Our ABI detection source
716
      // does not include any system headers anyway.
717
0
      fprintf(fout,
718
0
              "set_property(DIRECTORY PROPERTY INCLUDE_DIRECTORIES \"\")\n");
719
720
      // The link and compile lines for ABI detection step need to not use
721
      // response files so we can extract implicit includes given to
722
      // the underlying host compiler
723
0
      static std::array<std::string, 2> const noRSP{ { "CUDA", "HIP" } };
724
0
      for (std::string const& lang : noRSP) {
725
0
        if (testLangs.find(lang) != testLangs.end()) {
726
0
          fprintf(fout, "set(CMAKE_%s_USE_RESPONSE_FILE_FOR_INCLUDES OFF)\n",
727
0
                  lang.c_str());
728
0
          fprintf(fout, "set(CMAKE_%s_USE_RESPONSE_FILE_FOR_LIBRARIES OFF)\n",
729
0
                  lang.c_str());
730
0
          fprintf(fout, "set(CMAKE_%s_USE_RESPONSE_FILE_FOR_OBJECTS OFF)\n",
731
0
                  lang.c_str());
732
0
        }
733
0
      }
734
0
    }
735
0
    fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n");
736
0
    for (std::string const& li : testLangs) {
737
0
      std::string langFlags = cmStrCat("CMAKE_", li, "_FLAGS");
738
0
      cmValue flags = this->Makefile->GetDefinition(langFlags);
739
0
      fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li.c_str(),
740
0
              cmScriptGenerator::Quote(*flags).str().c_str());
741
0
      fprintf(fout,
742
0
              "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
743
0
              " ${COMPILE_DEFINITIONS}\")\n",
744
0
              li.c_str(), li.c_str());
745
0
      if (flags) {
746
0
        cmakeVariables.emplace(langFlags, *flags);
747
0
      }
748
0
    }
749
0
    switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) {
750
0
      case cmPolicies::WARN:
751
0
        if (this->Makefile->PolicyOptionalWarningEnabled(
752
0
              "CMAKE_POLICY_WARNING_CMP0066")) {
753
0
          std::ostringstream w;
754
          /* clang-format off */
755
0
          w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0066) << "\n"
756
0
            "For compatibility with older versions of CMake, try_compile "
757
0
            "is not honoring caller config-specific compiler flags "
758
0
            "(e.g. CMAKE_C_FLAGS_DEBUG) in the test project."
759
0
            ;
760
          /* clang-format on */
761
0
          this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
762
0
        }
763
0
        CM_FALLTHROUGH;
764
0
      case cmPolicies::OLD:
765
        // OLD behavior is to do nothing.
766
0
        break;
767
0
      case cmPolicies::NEW: {
768
        // NEW behavior is to pass config-specific compiler flags.
769
0
        std::string const cfg = !tcConfig.empty()
770
0
          ? cmSystemTools::UpperCase(tcConfig)
771
0
          : TryCompileDefaultConfig;
772
0
        for (std::string const& li : testLangs) {
773
0
          std::string const langFlagsCfg =
774
0
            cmStrCat("CMAKE_", li, "_FLAGS_", cfg);
775
0
          cmValue flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
776
0
          fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
777
0
                  cmScriptGenerator::Quote(*flagsCfg).str().c_str());
778
0
          if (flagsCfg) {
779
0
            cmakeVariables.emplace(langFlagsCfg, *flagsCfg);
780
0
          }
781
0
        }
782
0
      } break;
783
0
    }
784
0
    {
785
0
      cmValue exeLinkFlags =
786
0
        this->Makefile->GetDefinition("CMAKE_EXE_LINKER_FLAGS");
787
0
      fprintf(fout, "set(CMAKE_EXE_LINKER_FLAGS %s)\n",
788
0
              cmScriptGenerator::Quote(*exeLinkFlags).str().c_str());
789
0
      if (exeLinkFlags) {
790
0
        cmakeVariables.emplace("CMAKE_EXE_LINKER_FLAGS", *exeLinkFlags);
791
0
      }
792
0
    }
793
0
    fprintf(fout,
794
0
            "set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS}"
795
0
            " ${EXE_LINKER_FLAGS}\")\n");
796
797
0
    switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0210)) {
798
0
      case cmPolicies::WARN:
799
        // This policy does WARN, but not during try_compile.
800
0
        CM_FALLTHROUGH;
801
0
      case cmPolicies::OLD:
802
        // OLD behavior is to do nothing here. CMAKE_<LANG>_LINK_FLAGS was
803
        // previously used internally by executables only, and not during
804
        // try_compile.
805
0
        break;
806
0
      case cmPolicies::NEW:
807
        // NEW behavior is to propagate language-specific link flags (stored
808
        // in both the default and per-configuration variables, similar to the
809
        // NEW behavior of CMP0066) to the test project.
810
0
        for (std::string const& li : testLangs) {
811
0
          std::string langLinkFlags = cmStrCat("CMAKE_", li, "_LINK_FLAGS");
812
0
          cmValue flags = this->Makefile->GetDefinition(langLinkFlags);
813
0
          fprintf(fout, "set(CMAKE_%s_LINK_FLAGS %s)\n", li.c_str(),
814
0
                  cmScriptGenerator::Quote(*flags).str().c_str());
815
0
          std::string langLinkFlagsConfig =
816
0
            cmStrCat("CMAKE_", li, "_LINK_FLAGS_", tcConfig);
817
0
          cmValue flagsConfig =
818
0
            this->Makefile->GetDefinition(langLinkFlagsConfig);
819
0
          fprintf(fout, "set(CMAKE_%s_LINK_FLAGS_%s %s)\n", li.c_str(),
820
0
                  tcConfig.c_str(),
821
0
                  cmScriptGenerator::Quote(*flagsConfig).str().c_str());
822
823
0
          if (flags) {
824
0
            cmakeVariables.emplace(langLinkFlags, *flags);
825
0
          }
826
0
          if (flagsConfig) {
827
0
            cmakeVariables.emplace(langLinkFlagsConfig, *flagsConfig);
828
0
          }
829
0
        }
830
0
        break;
831
0
    }
832
833
0
    fprintf(fout, "include_directories(${INCLUDE_DIRECTORIES})\n");
834
0
    fprintf(fout, "set(CMAKE_SUPPRESS_REGENERATION 1)\n");
835
0
    fprintf(fout, "link_directories(${LINK_DIRECTORIES})\n");
836
    // handle any compile flags we need to pass on
837
0
    if (!arguments.CompileDefs.empty()) {
838
      // Pass using bracket arguments to preserve content.
839
0
      fprintf(fout, "add_definitions([==[%s]==])\n",
840
0
              arguments.CompileDefs.join("]==] [==[").c_str());
841
0
    }
842
843
0
    if (!targets.empty()) {
844
0
      std::string fname = cmStrCat('/', targetName, "Targets.cmake");
845
0
      cmExportTryCompileFileGenerator tcfg(gg, targets, this->Makefile,
846
0
                                           testLangs);
847
0
      tcfg.SetExportFile(cmStrCat(this->BinaryDirectory, fname).c_str());
848
0
      tcfg.SetConfig(tcConfig);
849
850
0
      if (!tcfg.GenerateImportFile()) {
851
0
        this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
852
0
                                     "could not write export file.");
853
0
        fclose(fout);
854
0
        return cm::nullopt;
855
0
      }
856
0
      fprintf(fout, "\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/%s\")\n",
857
0
              fname.c_str());
858
      // Create all relevant alias targets
859
0
      if (arguments.LinkLibraries) {
860
0
        auto const& aliasTargets = this->Makefile->GetAliasTargets();
861
0
        for (std::string const& i : *arguments.LinkLibraries) {
862
0
          auto alias = aliasTargets.find(i);
863
0
          if (alias != aliasTargets.end()) {
864
0
            auto const& aliasTarget =
865
0
              this->Makefile->FindTargetToUse(alias->second);
866
            // Create equivalent library/executable alias
867
0
            if (aliasTarget->GetType() == cmStateEnums::EXECUTABLE) {
868
0
              fprintf(fout, "add_executable(\"%s\" ALIAS \"%s\")\n", i.c_str(),
869
0
                      alias->second.c_str());
870
0
            } else {
871
              // Other cases like UTILITY and GLOBAL_TARGET are excluded
872
              // when arguments.LinkLibraries is initially parsed in this
873
              // function.
874
0
              fprintf(fout, "add_library(\"%s\" ALIAS \"%s\")\n", i.c_str(),
875
0
                      alias->second.c_str());
876
0
            }
877
0
          }
878
0
        }
879
0
      }
880
0
      fprintf(fout, "\n");
881
0
    }
882
883
    /* Set the appropriate policy information for PIE link flags */
884
0
    fprintf(fout, "cmake_policy(SET CMP0083 %s)\n",
885
0
            this->Makefile->GetPolicyStatus(cmPolicies::CMP0083) ==
886
0
                cmPolicies::NEW
887
0
              ? "NEW"
888
0
              : "OLD");
889
890
    /* Set the appropriate policy information for C++ module support */
891
0
    fprintf(fout, "cmake_policy(SET CMP0155 %s)\n",
892
0
            this->Makefile->GetPolicyStatus(cmPolicies::CMP0155) ==
893
0
                cmPolicies::NEW
894
0
              ? "NEW"
895
0
              : "OLD");
896
897
    /* Set the appropriate policy information for Swift compilation mode */
898
0
    fprintf(
899
0
      fout, "cmake_policy(SET CMP0157 %s)\n",
900
0
      this->Makefile->GetDefinition("CMAKE_Swift_COMPILATION_MODE_DEFAULT")
901
0
          .IsEmpty()
902
0
        ? "OLD"
903
0
        : "NEW");
904
905
    /* Set the appropriate policy information for the LINKER: prefix
906
     * expansion
907
     */
908
0
    fprintf(fout, "cmake_policy(SET CMP0181 %s)\n",
909
0
            this->Makefile->GetPolicyStatus(cmPolicies::CMP0181) ==
910
0
                cmPolicies::NEW
911
0
              ? "NEW"
912
0
              : "OLD");
913
914
    /* Set the appropriate policy information for passing
915
     * CMAKE_<LANG>_LINK_FLAGS
916
     */
917
0
    fprintf(fout, "cmake_policy(SET CMP0210 %s)\n",
918
0
            this->Makefile->GetPolicyStatus(cmPolicies::CMP0210) ==
919
0
                cmPolicies::NEW
920
0
              ? "NEW"
921
0
              : "OLD");
922
923
    // Workaround for -Wl,-headerpad_max_install_names issue until we can
924
    // avoid adding that flag in the platform and compiler language files
925
0
    fprintf(fout,
926
0
            "include(\"${CMAKE_ROOT}/Modules/Internal/"
927
0
            "HeaderpadWorkaround.cmake\")\n");
928
929
0
    if (targetType == cmStateEnums::EXECUTABLE) {
930
      /* Put the executable at a known location (for COPY_FILE).  */
931
0
      fprintf(fout, "set(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"%s\")\n",
932
0
              this->BinaryDirectory.c_str());
933
      /* Create the actual executable.  */
934
0
      fprintf(fout, "add_executable(%s)\n", targetName.c_str());
935
0
    } else // if (targetType == cmStateEnums::STATIC_LIBRARY)
936
0
    {
937
      /* Put the static library at a known location (for COPY_FILE).  */
938
0
      fprintf(fout, "set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY \"%s\")\n",
939
0
              this->BinaryDirectory.c_str());
940
      /* Create the actual static library.  */
941
0
      fprintf(fout, "add_library(%s STATIC)\n", targetName.c_str());
942
0
    }
943
0
    fprintf(fout, "target_sources(%s PRIVATE\n", targetName.c_str());
944
0
    std::string file_set_name;
945
0
    bool in_file_set = false;
946
0
    for (auto const& source : sources) {
947
0
      auto const& si = source.first;
948
0
      switch (source.second) {
949
0
        case Arguments::SourceType::Normal: {
950
0
          if (in_file_set) {
951
0
            fprintf(fout, "  PRIVATE\n");
952
0
            in_file_set = false;
953
0
          }
954
0
        } break;
955
0
        case Arguments::SourceType::CxxModule: {
956
0
          if (!in_file_set) {
957
0
            file_set_name += 'a';
958
0
            fprintf(fout,
959
0
                    "  PRIVATE FILE_SET %s TYPE CXX_MODULES BASE_DIRS \"%s\" "
960
0
                    "FILES\n",
961
0
                    file_set_name.c_str(),
962
0
                    this->Makefile->GetCurrentSourceDirectory().c_str());
963
0
            in_file_set = true;
964
0
          }
965
0
        } break;
966
0
        case Arguments::SourceType::Directory:
967
          /* Handled elsewhere. */
968
0
          break;
969
0
      }
970
0
      fprintf(fout, "  \"%s\"\n", si.c_str());
971
972
      // Add dependencies on any non-temporary sources.
973
0
      if (!IsTemporary(si)) {
974
0
        this->Makefile->AddCMakeDependFile(si);
975
0
      }
976
0
    }
977
0
    fprintf(fout, ")\n");
978
979
    /* Write out the output location of the target we are building */
980
0
    std::string perConfigGenex;
981
0
    if (this->Makefile->GetGlobalGenerator()->IsMultiConfig()) {
982
0
      perConfigGenex = "_$<UPPER_CASE:$<CONFIG>>";
983
0
    }
984
0
    fprintf(fout,
985
0
            "file(GENERATE OUTPUT "
986
0
            "\"${CMAKE_BINARY_DIR}/%s%s_loc\"\n",
987
0
            targetName.c_str(), perConfigGenex.c_str());
988
0
    fprintf(fout, "     CONTENT $<TARGET_FILE:%s>)\n", targetName.c_str());
989
990
0
    bool warnCMP0067 = false;
991
0
    bool honorStandard = true;
992
993
0
    if (arguments.LangProps.empty()) {
994
0
      switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0067)) {
995
0
        case cmPolicies::WARN:
996
0
          warnCMP0067 = this->Makefile->PolicyOptionalWarningEnabled(
997
0
            "CMAKE_POLICY_WARNING_CMP0067");
998
0
          CM_FALLTHROUGH;
999
0
        case cmPolicies::OLD:
1000
          // OLD behavior is to not honor the language standard variables.
1001
0
          honorStandard = false;
1002
0
          break;
1003
0
        case cmPolicies::NEW:
1004
          // NEW behavior is to honor the language standard variables.
1005
          // We already initialized honorStandard to true.
1006
0
          break;
1007
0
      }
1008
0
    }
1009
1010
0
    std::vector<std::string> warnCMP0067Variables;
1011
1012
0
    if (honorStandard || warnCMP0067) {
1013
0
      static std::array<std::string, 6> const possibleLangs{
1014
0
        { "C", "CXX", "CUDA", "HIP", "OBJC", "OBJCXX" }
1015
0
      };
1016
0
      static std::array<cm::string_view, 3> const langPropSuffixes{
1017
0
        { "_STANDARD"_s, "_STANDARD_REQUIRED"_s, "_EXTENSIONS"_s }
1018
0
      };
1019
0
      for (std::string const& lang : possibleLangs) {
1020
0
        if (testLangs.find(lang) == testLangs.end()) {
1021
0
          continue;
1022
0
        }
1023
0
        for (cm::string_view propSuffix : langPropSuffixes) {
1024
0
          std::string langProp = cmStrCat(lang, propSuffix);
1025
0
          if (!arguments.LangProps.count(langProp)) {
1026
0
            std::string langPropVar = cmStrCat("CMAKE_"_s, langProp);
1027
0
            std::string value = this->Makefile->GetSafeDefinition(langPropVar);
1028
0
            if (warnCMP0067 && !value.empty()) {
1029
0
              value.clear();
1030
0
              warnCMP0067Variables.emplace_back(langPropVar);
1031
0
            }
1032
0
            if (!value.empty()) {
1033
0
              arguments.LangProps[langProp] = value;
1034
0
            }
1035
0
          }
1036
0
        }
1037
0
      }
1038
0
    }
1039
1040
0
    if (!warnCMP0067Variables.empty()) {
1041
0
      std::ostringstream w;
1042
      /* clang-format off */
1043
0
      w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0067) << "\n"
1044
0
        "For compatibility with older versions of CMake, try_compile "
1045
0
        "is not honoring language standard variables in the test project:\n"
1046
0
        ;
1047
      /* clang-format on */
1048
0
      for (std::string const& vi : warnCMP0067Variables) {
1049
0
        w << "  " << vi << "\n";
1050
0
      }
1051
0
      this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
1052
0
    }
1053
1054
0
    for (auto const& p : arguments.LangProps) {
1055
0
      if (p.second.empty()) {
1056
0
        continue;
1057
0
      }
1058
0
      fprintf(fout, "set_property(TARGET %s PROPERTY %s %s)\n",
1059
0
              targetName.c_str(),
1060
0
              cmScriptGenerator::Quote(p.first).str().c_str(),
1061
0
              cmScriptGenerator::Quote(p.second).str().c_str());
1062
0
    }
1063
1064
0
    if (!arguments.LinkOptions.empty()) {
1065
0
      std::vector<std::string> options;
1066
0
      options.reserve(arguments.LinkOptions.size());
1067
0
      for (auto const& option : arguments.LinkOptions) {
1068
0
        options.emplace_back(cmScriptGenerator::Quote(option));
1069
0
      }
1070
1071
0
      if (targetType == cmStateEnums::STATIC_LIBRARY) {
1072
0
        fprintf(fout,
1073
0
                "set_property(TARGET %s PROPERTY STATIC_LIBRARY_OPTIONS %s)\n",
1074
0
                targetName.c_str(), cmJoin(options, " ").c_str());
1075
0
      } else {
1076
0
        fprintf(fout, "target_link_options(%s PRIVATE %s)\n",
1077
0
                targetName.c_str(), cmJoin(options, " ").c_str());
1078
0
      }
1079
0
    }
1080
1081
0
    if (arguments.LinkerLanguage) {
1082
0
      std::string LinkerLanguage = *arguments.LinkerLanguage;
1083
0
      if (testLangs.find(LinkerLanguage) == testLangs.end()) {
1084
0
        this->Makefile->IssueMessage(
1085
0
          MessageType::FATAL_ERROR,
1086
0
          "Linker language '" + LinkerLanguage +
1087
0
            "' must be enabled in project(LANGUAGES).");
1088
0
      }
1089
1090
0
      fprintf(fout, "set_property(TARGET %s PROPERTY LINKER_LANGUAGE %s)\n",
1091
0
              targetName.c_str(), LinkerLanguage.c_str());
1092
0
    }
1093
1094
0
    if (arguments.LinkLibraries) {
1095
0
      std::string libsToLink = " ";
1096
0
      for (std::string const& i : *arguments.LinkLibraries) {
1097
0
        libsToLink += cmStrCat('"', cmTrimWhitespace(i), "\" ");
1098
0
      }
1099
0
      fprintf(fout, "target_link_libraries(%s %s)\n", targetName.c_str(),
1100
0
              libsToLink.c_str());
1101
0
    } else {
1102
0
      fprintf(fout, "target_link_libraries(%s ${LINK_LIBRARIES})\n",
1103
0
              targetName.c_str());
1104
0
    }
1105
0
    fclose(fout);
1106
0
  }
1107
1108
  // Forward a set of variables to the inner project cache.
1109
0
  if ((this->SrcFileSignature ||
1110
0
       this->Makefile->GetPolicyStatus(cmPolicies::CMP0137) ==
1111
0
         cmPolicies::NEW) &&
1112
0
      !this->Makefile->IsOn("CMAKE_TRY_COMPILE_NO_PLATFORM_VARIABLES")) {
1113
0
    std::set<std::string> vars;
1114
0
    for (cm::string_view l : kLanguageNames) {
1115
0
      vars.emplace(cmStrCat("CMAKE_", l, "_COMPILER_EXTERNAL_TOOLCHAIN"));
1116
0
      vars.emplace(cmStrCat("CMAKE_", l, "_COMPILER_TARGET"));
1117
0
    }
1118
0
    vars.insert(kCMAKE_CUDA_ARCHITECTURES);
1119
0
    vars.insert(kCMAKE_CUDA_RUNTIME_LIBRARY);
1120
0
    vars.insert(kCMAKE_CXX_SCAN_FOR_MODULES);
1121
0
    vars.insert(kCMAKE_ENABLE_EXPORTS);
1122
0
    vars.insert(kCMAKE_EXECUTABLE_ENABLE_EXPORTS);
1123
0
    vars.insert(kCMAKE_SHARED_LIBRARY_ENABLE_EXPORTS);
1124
0
    vars.insert(kCMAKE_HIP_ARCHITECTURES);
1125
0
    vars.insert(kCMAKE_HIP_PLATFORM);
1126
0
    vars.insert(kCMAKE_HIP_RUNTIME_LIBRARY);
1127
0
    vars.insert(kCMAKE_ISPC_INSTRUCTION_SETS);
1128
0
    vars.insert(kCMAKE_ISPC_HEADER_SUFFIX);
1129
0
    vars.insert(kCMAKE_LINK_SEARCH_END_STATIC);
1130
0
    vars.insert(kCMAKE_LINK_SEARCH_START_STATIC);
1131
0
    vars.insert(kCMAKE_OSX_ARCHITECTURES);
1132
0
    vars.insert(kCMAKE_OSX_DEPLOYMENT_TARGET);
1133
0
    vars.insert(kCMAKE_OSX_SYSROOT);
1134
0
    vars.insert(kCMAKE_APPLE_ARCH_SYSROOTS);
1135
0
    vars.insert(kCMAKE_POSITION_INDEPENDENT_CODE);
1136
0
    vars.insert(kCMAKE_SYSROOT);
1137
0
    vars.insert(kCMAKE_SYSROOT_COMPILE);
1138
0
    vars.insert(kCMAKE_SYSROOT_LINK);
1139
0
    vars.insert(kCMAKE_WARN_DEPRECATED);
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
}