Coverage Report

Created: 2026-10-28 06:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/CMake/Source/cmExportCommand.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 "cmExportCommand.h"
4
5
#include <map>
6
#include <ostream>
7
#include <utility>
8
9
#include <cm/memory>
10
#include <cm/optional>
11
#include <cmext/algorithm>
12
#include <cmext/string_view>
13
14
#include "cmsys/RegularExpression.hxx"
15
16
#include "cmArgumentParser.h"
17
#include "cmArgumentParserTypes.h"
18
#include "cmBuildSbomGenerator.h"
19
#include "cmCryptoHash.h"
20
#include "cmDiagnosticContext.h"
21
#include "cmDiagnostics.h"
22
#include "cmExecutionStatus.h"
23
#include "cmExperimental.h"
24
#include "cmExportBuildAndroidMKGenerator.h"
25
#include "cmExportBuildCMakeConfigGenerator.h"
26
#include "cmExportBuildFileGenerator.h"
27
#include "cmExportBuildPackageInfoGenerator.h"
28
#include "cmExportSet.h"
29
#include "cmGeneratedFileStream.h"
30
#include "cmGlobalGenerator.h"
31
#include "cmMakefile.h"
32
#include "cmMessageType.h"
33
#include "cmPackageInfoArguments.h"
34
#include "cmPolicies.h"
35
#include "cmRange.h"
36
#include "cmSbomArguments.h"
37
#include "cmStringAlgorithms.h"
38
#include "cmSubcommandTable.h"
39
#include "cmSystemTools.h"
40
#include "cmTarget.h"
41
#include "cmTargetTypes.h"
42
#include "cmValue.h"
43
44
#if defined(__HAIKU__)
45
#  include <FindDirectory.h>
46
#  include <StorageDefs.h>
47
#endif
48
49
#if defined(_WIN32) && !defined(__CYGWIN__)
50
#  include <windows.h>
51
#endif
52
53
static void StorePackageRegistry(cmMakefile& mf, std::string const& package,
54
                                 char const* content, char const* hash);
55
56
static cm::optional<cmExportSet*> GetExportSet(std::string const& name,
57
                                               cmGlobalGenerator* generator,
58
                                               cmExecutionStatus& status)
59
0
{
60
0
  cmExportSetMap& setMap = generator->GetExportSets();
61
0
  auto const it = setMap.find(name);
62
0
  if (it == setMap.end()) {
63
0
    status.SetError(cmStrCat("Export set \""_s, name, "\" not found."_s));
64
0
    return cm::nullopt;
65
0
  }
66
0
  return &it->second;
67
0
}
68
69
static void AddExportGenerator(
70
  cmMakefile& makefile, cmGlobalGenerator* globalGenerator,
71
  std::unique_ptr<cmExportBuildFileGenerator> exportGenerator,
72
  std::string const& fileName, cmExportSet* exportSet,
73
  std::string const& cxxModulesDirectory)
74
0
{
75
0
  exportGenerator->SetExportFile(fileName.c_str());
76
0
  exportGenerator->SetCxxModuleDirectory(cxxModulesDirectory);
77
0
  if (exportSet) {
78
0
    exportGenerator->SetExportSet(exportSet);
79
0
  }
80
0
  std::vector<std::string> configurationTypes =
81
0
    makefile.GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
82
83
0
  for (std::string const& ct : configurationTypes) {
84
0
    exportGenerator->AddConfiguration(ct);
85
0
  }
86
0
  if (exportSet) {
87
0
    globalGenerator->AddBuildExportExportSet(exportGenerator.get());
88
0
  }
89
0
  makefile.AddExportBuildFileGenerator(std::move(exportGenerator));
90
0
}
91
92
static bool ValidateExportableTarget(std::string const& name,
93
                                     cmGlobalGenerator* gg,
94
                                     cmExecutionStatus& status)
95
0
{
96
0
  cmTarget const* target = gg->FindTarget(name);
97
0
  if (!target) {
98
0
    status.SetError(cmStrCat("given target \"", name,
99
0
                             "\" which is not built by this project."));
100
0
    return false;
101
0
  }
102
0
  if (target->GetType() == cm::TargetType::UTILITY) {
103
0
    status.SetError(cmStrCat("given custom target \"", name,
104
0
                             "\" which may not be exported."));
105
0
    return false;
106
0
  }
107
0
  return true;
108
0
}
109
110
static bool HandleTargetsMode(std::vector<std::string> const& args,
111
                              cmExecutionStatus& status)
112
0
{
113
0
  struct Arguments
114
0
  {
115
0
    cm::optional<ArgumentParser::MaybeEmpty<std::vector<std::string>>> Targets;
116
0
    ArgumentParser::NonEmpty<std::string> ExportSetName;
117
0
    ArgumentParser::NonEmpty<std::string> Namespace;
118
0
    ArgumentParser::NonEmpty<std::string> Filename;
119
0
    ArgumentParser::NonEmpty<std::string> CxxModulesDirectory;
120
0
    ArgumentParser::NonEmpty<std::string> AndroidMKFile;
121
122
0
    bool Append = false;
123
0
    bool ExportOld = false;
124
0
  };
125
126
0
  auto parser =
127
0
    cmArgumentParser<Arguments>{}
128
0
      .Bind("NAMESPACE"_s, &Arguments::Namespace)
129
0
      .Bind("FILE"_s, &Arguments::Filename)
130
0
      .Bind("CXX_MODULES_DIRECTORY"_s, &Arguments::CxxModulesDirectory)
131
0
      .Bind("TARGETS"_s, &Arguments::Targets)
132
0
      .Bind("APPEND"_s, &Arguments::Append)
133
0
      .Bind("ANDROID_MK"_s, &Arguments::AndroidMKFile)
134
0
      .Bind("EXPORT_LINK_INTERFACE_LIBRARIES"_s, &Arguments::ExportOld);
135
136
0
  std::vector<std::string> unknownArgs;
137
0
  Arguments arguments = parser.Parse(args, &unknownArgs);
138
139
0
  if (!unknownArgs.empty()) {
140
0
    status.SetError(
141
0
      cmStrCat("Unknown argument: \"", unknownArgs.front(), "\"."));
142
0
    return false;
143
0
  }
144
145
0
  std::string fname;
146
0
  bool android = false;
147
0
  if (!arguments.AndroidMKFile.empty()) {
148
0
    fname = arguments.AndroidMKFile;
149
0
    android = true;
150
0
  } else if (arguments.Filename.empty()) {
151
0
    fname = arguments.ExportSetName + ".cmake";
152
0
  } else {
153
    // Make sure the file has a .cmake extension.
154
0
    if (!cmHasSuffix(arguments.Filename, ".cmake"_s)) {
155
0
      status.SetError(
156
0
        cmStrCat("FILE option given filename \"", arguments.Filename,
157
0
                 "\" which does not have an extension of \".cmake\".\n"));
158
0
      return false;
159
0
    }
160
0
    fname = arguments.Filename;
161
0
  }
162
163
0
  cmMakefile& mf = status.GetMakefile();
164
165
  // Get the file to write.
166
0
  if (cmSystemTools::FileIsFullPath(fname)) {
167
0
    if (!mf.CanIWriteThisFile(fname)) {
168
0
      status.SetError(cmStrCat("FILE option given filename \"", fname,
169
0
                               "\" which is in the source tree.\n"));
170
0
      return false;
171
0
    }
172
0
  } else {
173
    // Interpret relative paths with respect to the current build dir.
174
0
    std::string const& dir = mf.GetCurrentBinaryDirectory();
175
0
    fname = cmStrCat(dir, '/', std::move(fname));
176
0
  }
177
178
0
  std::vector<cmExportBuildFileGenerator::TargetExport> targets;
179
0
  cmGlobalGenerator* gg = mf.GetGlobalGenerator();
180
181
0
  for (std::string const& currentTarget : *arguments.Targets) {
182
0
    if (!ValidateExportableTarget(currentTarget, gg, status)) {
183
0
      return false;
184
0
    }
185
0
    targets.emplace_back(currentTarget, std::string{});
186
0
  }
187
0
  if (arguments.Append) {
188
0
    if (cmExportBuildFileGenerator* ebfg = gg->GetExportedTargetsFile(fname)) {
189
0
      ebfg->AppendTargets(targets);
190
0
      return true;
191
0
    }
192
0
  }
193
194
  // if cmExportBuildFileGenerator is already defined for the file
195
  // and APPEND is not specified, if CMP0103 is OLD ignore previous definition
196
  // else raise an error
197
0
  if (gg->GetExportedTargetsFile(fname)) {
198
0
    switch (mf.GetPolicyStatus(cmPolicies::CMP0103)) {
199
0
      case cmPolicies::WARN:
200
0
        mf.IssuePolicyWarning(
201
0
          cmPolicies::CMP0103, {},
202
0
          cmStrCat("export() command already specified for the file\n  ",
203
0
                   arguments.Filename, "\nDid you miss 'APPEND' keyword?"));
204
0
        CM_FALLTHROUGH;
205
0
      case cmPolicies::OLD:
206
0
        break;
207
0
      default:
208
0
        status.SetError(cmStrCat("command already specified for the file\n  ",
209
0
                                 arguments.Filename,
210
0
                                 "\nDid you miss 'APPEND' keyword?"));
211
0
        return false;
212
0
    }
213
0
  }
214
215
0
  cmDiagnosticContext context = cmExportBuildFileGenerator::CaptureContext(mf);
216
0
  std::unique_ptr<cmExportBuildFileGenerator> ebfg = nullptr;
217
0
  if (android) {
218
0
    auto ebag =
219
0
      cm::make_unique<cmExportBuildAndroidMKGenerator>(std::move(context));
220
0
    ebag->SetNamespace(arguments.Namespace);
221
0
    ebag->SetAppendMode(arguments.Append);
222
0
    ebfg = std::move(ebag);
223
0
  } else {
224
0
    auto ebcg =
225
0
      cm::make_unique<cmExportBuildCMakeConfigGenerator>(std::move(context));
226
0
    ebcg->SetNamespace(arguments.Namespace);
227
0
    ebcg->SetAppendMode(arguments.Append);
228
0
    ebcg->SetExportOld(arguments.ExportOld);
229
0
    ebfg = std::move(ebcg);
230
0
  }
231
232
0
  ebfg->SetExportFile(fname.c_str());
233
0
  ebfg->SetCxxModuleDirectory(arguments.CxxModulesDirectory);
234
0
  ebfg->SetTargets(targets);
235
0
  std::vector<std::string> configurationTypes =
236
0
    mf.GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
237
238
0
  for (std::string const& ct : configurationTypes) {
239
0
    ebfg->AddConfiguration(ct);
240
0
  }
241
0
  gg->AddBuildExportSet(ebfg.get());
242
0
  mf.AddExportBuildFileGenerator(std::move(ebfg));
243
244
0
  return true;
245
0
}
246
247
static bool HandleExportMode(std::vector<std::string> const& args,
248
                             cmExecutionStatus& status)
249
0
{
250
0
  struct ExportArguments : public ArgumentParser::ParseResult
251
0
  {
252
0
    ArgumentParser::NonEmpty<std::string> ExportSetName;
253
0
    ArgumentParser::MaybeEmpty<std::string> Namespace;
254
0
    ArgumentParser::NonEmpty<std::string> Filename;
255
0
    ArgumentParser::NonEmpty<std::string> CxxModulesDirectory;
256
0
    bool ExportPackageDependencies = false;
257
0
  };
258
259
0
  auto parser =
260
0
    cmArgumentParser<ExportArguments>{}
261
0
      .Bind("EXPORT"_s, &ExportArguments::ExportSetName)
262
0
      .Bind("NAMESPACE"_s, &ExportArguments::Namespace)
263
0
      .Bind("FILE"_s, &ExportArguments::Filename)
264
0
      .Bind("CXX_MODULES_DIRECTORY"_s, &ExportArguments::CxxModulesDirectory);
265
266
0
  if (cmExperimental::HasSupportEnabled(
267
0
        status.GetMakefile(),
268
0
        cmExperimental::Feature::ExportPackageDependencies)) {
269
0
    parser.Bind("EXPORT_PACKAGE_DEPENDENCIES"_s,
270
0
                &ExportArguments::ExportPackageDependencies);
271
0
  }
272
273
0
  std::vector<std::string> unknownArgs;
274
0
  ExportArguments arguments = parser.Parse(args, &unknownArgs);
275
276
0
  cmMakefile& mf = status.GetMakefile();
277
0
  cmGlobalGenerator* gg = mf.GetGlobalGenerator();
278
279
0
  if (!arguments.Check(args[0], &unknownArgs, status)) {
280
0
    cmPolicies::PolicyStatus const p =
281
0
      status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0208);
282
0
    if (!unknownArgs.empty() || p == cmPolicies::NEW) {
283
0
      return false;
284
0
    }
285
0
    if (p == cmPolicies::WARN) {
286
0
      status.GetMakefile().IssueDiagnostic(
287
0
        cmDiagnostics::CMD_AUTHOR, cmStrCat("export "_s, status.GetError()));
288
0
      status.GetMakefile().IssuePolicyWarning(cmPolicies::CMP0208);
289
0
    }
290
0
  }
291
292
0
  std::string fname;
293
0
  if (arguments.Filename.empty()) {
294
0
    fname = arguments.ExportSetName + ".cmake";
295
0
  } else {
296
0
    if (!cmHasSuffix(arguments.Filename, ".cmake"_s)) {
297
0
      status.SetError(
298
0
        cmStrCat("FILE option given filename \"", arguments.Filename,
299
0
                 "\" which does not have an extension of \".cmake\".\n"));
300
0
      return false;
301
0
    }
302
0
    fname = arguments.Filename;
303
0
  }
304
305
0
  if (cmSystemTools::FileIsFullPath(fname)) {
306
0
    if (!mf.CanIWriteThisFile(fname)) {
307
0
      status.SetError(cmStrCat("FILE option given filename \"", fname,
308
0
                               "\" which is in the source tree.\n"));
309
0
      return false;
310
0
    }
311
0
  } else {
312
    // Interpret relative paths with respect to the current build dir.
313
0
    std::string const& dir = mf.GetCurrentBinaryDirectory();
314
0
    fname = cmStrCat(dir, '/', std::move(fname));
315
0
  }
316
317
0
  cm::optional<cmExportSet*> const exportSet =
318
0
    GetExportSet(arguments.ExportSetName, gg, status);
319
0
  if (!exportSet) {
320
0
    return false;
321
0
  }
322
323
  // Set up export file generation.
324
0
  auto ebcg = cm::make_unique<cmExportBuildCMakeConfigGenerator>(
325
0
    cmExportBuildFileGenerator::CaptureContext(mf));
326
0
  ebcg->SetNamespace(arguments.Namespace);
327
0
  ebcg->SetExportPackageDependencies(arguments.ExportPackageDependencies);
328
329
0
  AddExportGenerator(mf, gg, std::move(ebcg), fname, *exportSet,
330
0
                     arguments.CxxModulesDirectory);
331
0
  return true;
332
0
}
333
334
template <typename ArgumentsType, typename GeneratorType>
335
static bool HandleSpecialExportMode(std::vector<std::string> const& args,
336
                                    cmExecutionStatus& status)
337
0
{
338
0
  struct ExportArguments
339
0
    : public ArgumentsType
340
0
    , public ArgumentParser::ParseResult
341
0
  {
342
0
    ArgumentParser::NonEmpty<std::string> ExportSetName;
343
0
    ArgumentParser::NonEmpty<std::string> CxxModulesDirectory;
344
345
0
    using ArgumentsType::Check;
346
0
    using ArgumentParser::ParseResult::Check;
347
0
  };
348
349
0
  auto parser =
350
0
    cmArgumentParser<ExportArguments>{}
351
0
      .Bind("EXPORT"_s, &ExportArguments::ExportSetName)
352
0
      .Bind("CXX_MODULES_DIRECTORY"_s, &ExportArguments::CxxModulesDirectory);
353
0
  ArgumentsType::Bind(parser);
354
355
0
  std::vector<std::string> unknownArgs;
356
0
  ExportArguments arguments = parser.Parse(args, &unknownArgs);
357
358
0
  if (!arguments.Check(args[0], &unknownArgs, status)) {
359
0
    return false;
360
0
  }
361
362
0
  if (arguments.ExportSetName.empty()) {
363
0
    status.SetError(cmStrCat(args[0], " missing EXPORT."));
364
0
    return false;
365
0
  }
366
367
0
  if (!arguments.Check(status) || !arguments.SetMetadataFromProject(status)) {
368
0
    return false;
369
0
  }
370
371
0
  cmMakefile& mf = status.GetMakefile();
372
0
  cmGlobalGenerator* gg = mf.GetGlobalGenerator();
373
374
0
  std::string const& dir =
375
0
    arguments.GetDefaultDestination(mf.GetCurrentBinaryDirectory());
376
0
  std::string const fname = cmStrCat(dir, '/', arguments.GetPackageFileName());
377
378
0
  if (gg->GetExportedTargetsFile(fname)) {
379
0
    status.SetError(cmStrCat("command already specified for the file "_s,
380
0
                             cmSystemTools::GetFilenameNameView(fname), '.'));
381
0
    return false;
382
0
  }
383
384
  // Look up the export set
385
0
  cm::optional<cmExportSet*> const exportSet =
386
0
    GetExportSet(arguments.ExportSetName, gg, status);
387
0
  if (!exportSet) {
388
0
    return false;
389
0
  }
390
391
  // Create the export build generator
392
0
  auto ebpg = cm::make_unique<GeneratorType>(
393
0
    arguments, cmExportBuildFileGenerator::CaptureContext(mf));
394
0
  AddExportGenerator(mf, gg, std::move(ebpg), fname, *exportSet,
395
0
                     arguments.CxxModulesDirectory);
396
0
  return true;
397
0
}
398
399
static bool HandlePackageInfoMode(std::vector<std::string> const& args,
400
                                  cmExecutionStatus& status)
401
0
{
402
0
  using arg_t = cmPackageInfoArguments;
403
0
  using gen_t = cmExportBuildPackageInfoGenerator;
404
0
  return HandleSpecialExportMode<arg_t, gen_t>(args, status);
405
0
}
406
407
static bool HandleSbomMode(std::vector<std::string> const& args,
408
                           cmExecutionStatus& status)
409
0
{
410
0
  struct SbomExportArguments
411
0
    : public cmSbomArguments
412
0
    , public ArgumentParser::ParseResult
413
0
  {
414
0
    ArgumentParser::NonEmpty<std::vector<std::string>> ExportSetNames;
415
416
0
    using cmSbomArguments::Check;
417
0
    using ArgumentParser::ParseResult::Check;
418
0
  };
419
420
0
  auto parser = cmArgumentParser<SbomExportArguments>{};
421
0
  cmSbomArguments::Bind(parser);
422
0
  parser.Bind("EXPORTS"_s, &SbomExportArguments::ExportSetNames);
423
424
0
  std::vector<std::string> unknownArgs;
425
0
  SbomExportArguments arguments = parser.Parse(args, &unknownArgs);
426
427
0
  if (!arguments.Check(args[0], &unknownArgs, status)) {
428
0
    return false;
429
0
  }
430
431
0
  if (arguments.ExportSetNames.empty()) {
432
0
    status.SetError(cmStrCat(args[0], " missing EXPORTS."));
433
0
    return false;
434
0
  }
435
436
0
  if (!arguments.Check(status) || !arguments.SetMetadataFromProject(status)) {
437
0
    return false;
438
0
  }
439
440
0
  cmMakefile& mf = status.GetMakefile();
441
0
  cmGlobalGenerator* gg = mf.GetGlobalGenerator();
442
443
0
  std::string const dir =
444
0
    arguments.GetDefaultDestination(mf.GetCurrentBinaryDirectory());
445
0
  std::string const fpath = cmStrCat(dir, '/', arguments.GetPackageName());
446
447
0
  if (gg->IsBuildSbomFile(fpath)) {
448
0
    status.SetError(cmStrCat("SBOM command already specified for the file "_s,
449
0
                             cmSystemTools::GetFilenameNameView(fpath), '.'));
450
0
    return false;
451
0
  }
452
453
0
  std::vector<cmExportSet*> sets;
454
0
  sets.reserve(arguments.ExportSetNames.size());
455
0
  for (std::string const& name : arguments.ExportSetNames) {
456
0
    cm::optional<cmExportSet*> const exportSet =
457
0
      GetExportSet(name, gg, status);
458
0
    if (!exportSet) {
459
0
      return false;
460
0
    }
461
0
    sets.push_back(*exportSet);
462
0
  }
463
464
0
  auto builder = cm::make_unique<cmBuildSbomGenerator>(arguments, sets, fpath);
465
0
  cmBuildSbomGenerator* rawPtr = builder.get();
466
0
  mf.AddBuildSbomGenerator(std::move(builder));
467
0
  gg->AddBuildSbomGenerator(rawPtr);
468
0
  return true;
469
0
}
470
471
static bool HandleSetupMode(std::vector<std::string> const& args,
472
                            cmExecutionStatus& status)
473
0
{
474
0
  struct SetupArguments
475
0
  {
476
0
    ArgumentParser::NonEmpty<std::string> ExportSetName;
477
0
    ArgumentParser::NonEmpty<std::string> CxxModulesDirectory;
478
0
    ArgumentParser::MaybeEmpty<std::vector<std::vector<std::string>>>
479
0
      PackageDependencyArgs;
480
0
    ArgumentParser::MaybeEmpty<std::vector<std::vector<std::string>>>
481
0
      TargetArgs;
482
0
  };
483
484
0
  auto parser = cmArgumentParser<SetupArguments>{};
485
0
  parser.Bind("SETUP"_s, &SetupArguments::ExportSetName);
486
0
  if (cmExperimental::HasSupportEnabled(
487
0
        status.GetMakefile(),
488
0
        cmExperimental::Feature::ExportPackageDependencies)) {
489
0
    parser.Bind("PACKAGE_DEPENDENCY"_s,
490
0
                &SetupArguments::PackageDependencyArgs);
491
0
  }
492
0
  parser.Bind("TARGET"_s, &SetupArguments::TargetArgs);
493
494
0
  std::vector<std::string> unknownArgs;
495
0
  SetupArguments arguments = parser.Parse(args, &unknownArgs);
496
497
0
  if (!unknownArgs.empty()) {
498
0
    status.SetError(cmStrCat("SETUP given unknown argument: \"",
499
0
                             unknownArgs.front(), "\"."));
500
0
    return false;
501
0
  }
502
503
0
  cmMakefile& mf = status.GetMakefile();
504
0
  cmGlobalGenerator* gg = mf.GetGlobalGenerator();
505
506
0
  cmExportSetMap& setMap = gg->GetExportSets();
507
0
  auto& exportSet = setMap[arguments.ExportSetName];
508
509
0
  struct PackageDependencyArguments
510
0
  {
511
0
    std::string Enabled;
512
0
    ArgumentParser::MaybeEmpty<std::vector<std::string>> ExtraArgs;
513
0
  };
514
515
0
  auto packageDependencyParser =
516
0
    cmArgumentParser<PackageDependencyArguments>{}
517
0
      .Bind("ENABLED"_s, &PackageDependencyArguments::Enabled)
518
0
      .Bind("EXTRA_ARGS"_s, &PackageDependencyArguments::ExtraArgs);
519
520
0
  for (auto const& packageDependencyArgs : arguments.PackageDependencyArgs) {
521
0
    if (packageDependencyArgs.empty()) {
522
0
      continue;
523
0
    }
524
0
    PackageDependencyArguments const packageDependencyArguments =
525
0
      packageDependencyParser.Parse(
526
0
        cmMakeRange(packageDependencyArgs).advance(1), &unknownArgs);
527
528
0
    if (!unknownArgs.empty()) {
529
0
      status.SetError(cmStrCat("PACKAGE_DEPENDENCY given unknown argument: \"",
530
0
                               unknownArgs.front(), "\"."));
531
0
      return false;
532
0
    }
533
0
    auto& packageDependency =
534
0
      exportSet.GetPackageDependencyForSetup(packageDependencyArgs.front());
535
0
    if (!packageDependencyArguments.Enabled.empty()) {
536
0
      if (packageDependencyArguments.Enabled == "AUTO") {
537
0
        packageDependency.Enabled =
538
0
          cmExportSet::PackageDependencyExportEnabled::Auto;
539
0
      } else if (cmIsOff(packageDependencyArguments.Enabled)) {
540
0
        packageDependency.Enabled =
541
0
          cmExportSet::PackageDependencyExportEnabled::Off;
542
0
      } else if (cmIsOn(packageDependencyArguments.Enabled)) {
543
0
        packageDependency.Enabled =
544
0
          cmExportSet::PackageDependencyExportEnabled::On;
545
0
      } else {
546
0
        status.SetError(
547
0
          cmStrCat("Invalid enable setting for package dependency: \"",
548
0
                   packageDependencyArguments.Enabled, '"'));
549
0
        return false;
550
0
      }
551
0
    }
552
0
    cm::append(packageDependency.ExtraArguments,
553
0
               packageDependencyArguments.ExtraArgs);
554
0
  }
555
556
0
  struct TargetArguments
557
0
  {
558
0
    std::string XcFrameworkLocation;
559
0
  };
560
561
0
  auto targetParser = cmArgumentParser<TargetArguments>{}.Bind(
562
0
    "XCFRAMEWORK_LOCATION"_s, &TargetArguments::XcFrameworkLocation);
563
564
0
  for (auto const& targetArgs : arguments.TargetArgs) {
565
0
    if (targetArgs.empty()) {
566
0
      continue;
567
0
    }
568
0
    TargetArguments const targetArguments =
569
0
      targetParser.Parse(cmMakeRange(targetArgs).advance(1), &unknownArgs);
570
571
0
    if (!unknownArgs.empty()) {
572
0
      status.SetError(cmStrCat("TARGET given unknown argument: \"",
573
0
                               unknownArgs.front(), "\"."));
574
0
      return false;
575
0
    }
576
0
    exportSet.SetXcFrameworkLocation(targetArgs.front(),
577
0
                                     targetArguments.XcFrameworkLocation);
578
0
  }
579
0
  return true;
580
0
}
581
582
static bool HandlePackageMode(std::vector<std::string> const& args,
583
                              cmExecutionStatus& status)
584
0
{
585
  // Parse PACKAGE mode arguments.
586
0
  enum Doing
587
0
  {
588
0
    DoingNone,
589
0
    DoingPackage
590
0
  };
591
0
  Doing doing = DoingPackage;
592
0
  std::string package;
593
0
  for (unsigned int i = 1; i < args.size(); ++i) {
594
0
    if (doing == DoingPackage) {
595
0
      package = args[i];
596
0
      doing = DoingNone;
597
0
    } else {
598
0
      status.SetError("PACKAGE given unknown argument: " + args[i]);
599
0
      return false;
600
0
    }
601
0
  }
602
603
  // Verify the package name.
604
0
  if (package.empty()) {
605
0
    status.SetError("PACKAGE must be given a package name.");
606
0
    return false;
607
0
  }
608
0
  char const* packageExpr = "^[A-Za-z0-9_.-]+$";
609
0
  cmsys::RegularExpression packageRegex(packageExpr);
610
0
  if (!packageRegex.find(package)) {
611
0
    status.SetError(cmStrCat("PACKAGE given invalid package name \"", package,
612
0
                             "\".  Package names must match \"", packageExpr,
613
0
                             "\"."));
614
0
    return false;
615
0
  }
616
617
0
  cmMakefile& mf = status.GetMakefile();
618
619
  // CMP0090 decides both the default and what variable changes it.
620
0
  switch (mf.GetPolicyStatus(cmPolicies::CMP0090)) {
621
0
    case cmPolicies::WARN:
622
0
      CM_FALLTHROUGH;
623
0
    case cmPolicies::OLD:
624
      // Default is to export, but can be disabled.
625
0
      if (mf.IsOn("CMAKE_EXPORT_NO_PACKAGE_REGISTRY")) {
626
0
        return true;
627
0
      }
628
0
      break;
629
0
    case cmPolicies::NEW:
630
      // Default is to not export, but can be enabled.
631
0
      if (!mf.IsOn("CMAKE_EXPORT_PACKAGE_REGISTRY")) {
632
0
        return true;
633
0
      }
634
0
      break;
635
0
  }
636
637
  // We store the current build directory in the registry as a value
638
  // named by a hash of its own content.  This is deterministic and is
639
  // unique with high probability.
640
0
  std::string const& outDir = mf.GetCurrentBinaryDirectory();
641
0
  cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
642
0
  std::string hash = hasher.HashString(outDir);
643
0
  StorePackageRegistry(mf, package, outDir.c_str(), hash.c_str());
644
645
0
  return true;
646
0
}
647
648
#if defined(_WIN32) && !defined(__CYGWIN__)
649
650
static void ReportRegistryError(cmMakefile& mf, std::string const& msg,
651
                                std::string const& key, long err)
652
{
653
  std::string e = cmStrCat(msg, "\n  HKEY_CURRENT_USER\\", key, '\n');
654
  wchar_t winmsg[1024];
655
  if (FormatMessageW(
656
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err,
657
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), winmsg, 1024, 0) > 0) {
658
    e = cmStrCat(std::move(e), "Windows reported:\n  ",
659
                 cmsys::Encoding::ToNarrow(winmsg));
660
  }
661
  mf.IssueMessage(MessageType::WARNING, e);
662
}
663
664
static void StorePackageRegistry(cmMakefile& mf, std::string const& package,
665
                                 char const* content, char const* hash)
666
{
667
  std::string key = cmStrCat("Software\\Kitware\\CMake\\Packages\\", package);
668
  HKEY hKey;
669
  LONG err =
670
    RegCreateKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(key).c_str(), 0,
671
                    0, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, 0, &hKey, 0);
672
  if (err != ERROR_SUCCESS) {
673
    ReportRegistryError(mf, "Cannot create/open registry key", key, err);
674
    return;
675
  }
676
677
  std::wstring wcontent = cmsys::Encoding::ToWide(content);
678
  err =
679
    RegSetValueExW(hKey, cmsys::Encoding::ToWide(hash).c_str(), 0, REG_SZ,
680
                   (BYTE const*)wcontent.c_str(),
681
                   static_cast<DWORD>(wcontent.size() + 1) * sizeof(wchar_t));
682
  RegCloseKey(hKey);
683
  if (err != ERROR_SUCCESS) {
684
    ReportRegistryError(
685
      mf, cmStrCat("Cannot set registry value \"", hash, "\" under key"), key,
686
      err);
687
    return;
688
  }
689
}
690
#else
691
static void StorePackageRegistry(cmMakefile& mf, std::string const& package,
692
                                 char const* content, char const* hash)
693
0
{
694
#  if defined(__HAIKU__)
695
  char dir[B_PATH_NAME_LENGTH];
696
  if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) !=
697
      B_OK) {
698
    return;
699
  }
700
  std::string fname = cmStrCat(dir, "/cmake/packages/", package);
701
#  else
702
0
  std::string fname;
703
0
  if (!cmSystemTools::GetEnv("HOME", fname)) {
704
0
    return;
705
0
  }
706
0
  cmSystemTools::ConvertToUnixSlashes(fname);
707
0
  fname += "/.cmake/packages/";
708
0
  fname += package;
709
0
#  endif
710
0
  cmSystemTools::MakeDirectory(fname);
711
0
  fname += "/";
712
0
  fname += hash;
713
0
  if (!cmSystemTools::FileExists(fname)) {
714
0
    cmGeneratedFileStream entry(fname, true);
715
0
    if (entry) {
716
0
      entry << content << "\n";
717
0
    } else {
718
0
      mf.IssueMessage(MessageType::WARNING,
719
0
                      cmStrCat("Cannot create package registry file:\n"
720
0
                               "  ",
721
0
                               fname, '\n',
722
0
                               cmSystemTools::GetLastSystemError(), '\n'));
723
0
    }
724
0
  }
725
0
}
726
#endif
727
728
bool cmExportCommand(std::vector<std::string> const& args,
729
                     cmExecutionStatus& status)
730
0
{
731
0
  if (args.empty()) {
732
0
    return true;
733
0
  }
734
735
0
  static cmSubcommandTable const subcommand{
736
0
    { "TARGETS"_s, HandleTargetsMode },
737
0
    { "EXPORT"_s, HandleExportMode },
738
0
    { "SETUP"_s, HandleSetupMode },
739
0
    { "PACKAGE"_s, HandlePackageMode },
740
0
    { "PACKAGE_INFO"_s, HandlePackageInfoMode },
741
0
    { "SBOM"_s, HandleSbomMode },
742
0
  };
743
744
0
  return subcommand(args[0], args, status);
745
0
}