Coverage Report

Created: 2026-07-30 06:52

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