Coverage Report

Created: 2026-10-28 06:38

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