File: cmExportSbomGenerator.cxx

package info (click to toggle)
cmake 4.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 158,704 kB
  • sloc: ansic: 406,077; cpp: 309,512; sh: 4,233; python: 3,696; yacc: 3,109; lex: 1,279; f90: 538; asm: 471; lisp: 375; java: 310; cs: 270; fortran: 239; objc: 215; perl: 213; xml: 198; makefile: 110; javascript: 83; pascal: 63; tcl: 55; php: 25; ruby: 22; sed: 2
file content (386 lines) | stat: -rw-r--r-- 12,625 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file LICENSE.rst or https://cmake.org/licensing for details.  */
#include "cmExportSbomGenerator.h"

#include <array>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include <cm/optional>
#include <cmext/algorithm>

#include "cmArgumentParserTypes.h"
#include "cmFindPackageStack.h"
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmList.h"
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmSbomArguments.h"
#include "cmSbomObject.h"
#include "cmSpdx.h"
#include "cmSpdxSerializer.h"
#include "cmStateTypes.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmValue.h"

cmSpdxPackage::PurposeId GetPurpose(cmStateEnums::TargetType type)
{
  switch (type) {
    case cmStateEnums::TargetType::EXECUTABLE:
      return cmSpdxPackage::PurposeId::APPLICATION;
    case cmStateEnums::TargetType::STATIC_LIBRARY:
    case cmStateEnums::TargetType::SHARED_LIBRARY:
    case cmStateEnums::TargetType::MODULE_LIBRARY:
    case cmStateEnums::TargetType::OBJECT_LIBRARY:
    case cmStateEnums::TargetType::INTERFACE_LIBRARY:
      return cmSpdxPackage::PurposeId::LIBRARY;
    case cmStateEnums::TargetType::UTILITY:
      return cmSpdxPackage::PurposeId::SOURCE;
    case cmStateEnums::TargetType::GLOBAL_TARGET:
    case cmStateEnums::TargetType::UNKNOWN_LIBRARY:
    default:
      return cmSpdxPackage::PurposeId::ARCHIVE;
  }
}

cmExportSbomGenerator::cmExportSbomGenerator(cmSbomArguments args)
  : PackageName(std::move(args.PackageName))
  , PackageVersion(std::move(args.Version))
  , PackageDescription(std::move(args.Description))
  , PackageWebsite(std::move(args.Website))
  , PackageLicense(std::move(args.License))
  , PackageFormat(args.GetFormat())
{
}

bool cmExportSbomGenerator::GenerateImportFile(std::ostream& os)
{
  return this->GenerateMainFile(os);
}

void cmExportSbomGenerator::WriteSbom(cmSbomDocument& doc,
                                      std::ostream& os) const
{
  switch (this->PackageFormat) {
    case cmSbomArguments::SbomFormat::SPDX_3_0_JSON:
      cmSpdxSerializer{}.WriteSbom(os, cmSbomObject(doc));
      break;
    case cmSbomArguments::SbomFormat::NONE:
      break;
  }
}

bool cmExportSbomGenerator::AddPackageInformation(
  cmSpdxPackage& artifact, std::string const& name,
  cmPackageInformation const& package) const
{
  if (name.empty()) {
    return false;
  }

  cmSpdxOrganization org;
  org.SpdxId = cmStrCat("urn:", name, "#Organization");
  org.Name = name;
  org.CreationInfo = artifact.CreationInfo;
  artifact.OriginatedBy.emplace_back(std::move(org));

  if (package.Description) {
    artifact.Description = *package.Description;
  }

  if (package.Version) {
    artifact.PackageVersion = *package.Version;
  }

  if (package.PackageUrl) {
    artifact.PackageUrl = *package.PackageUrl;
  }

  if (package.License) {
    artifact.CopyrightText = *package.License;
  }

  artifact.BuiltTime = cmSystemTools::GetCurrentDateTime("%FT%TZ");
  cmSpdxExternalRef externalRef;
  externalRef.Locator = cmStrCat("cmake:find_package(", name, ")");
  externalRef.ExternalRefType = "buildSystem";
  return true;
}

cmSpdxCreationInfo cmExportSbomGenerator::GenerateCreationInfo() const
{
  cmSpdxCreationInfo ci;
  ci.SpdxId = "_:Build#CreationInfo";
  ci.Created = cmSystemTools::GetCurrentDateTime("%FT%TZ");
  ci.CreatedBy = { "https://gitlab.kitware.com/cmake/cmake" };
  ci.Comment = "This SBOM was generated from the CMakeLists.txt File";
  ci.SpecVersion = "3.0.1";
  return ci;
}

cmSpdxDocument cmExportSbomGenerator::GenerateSbom(
  cmSpdxCreationInfo const* ci) const
{
  cmSpdxDocument proj;
  proj.Name = PackageName;
  proj.SpdxId = cmStrCat("urn:", PackageName, "#SPDXDocument");
  proj.ProfileConformance = { "core", "software" };
  proj.CreationInfo = ci;

  if (!this->PackageDescription.empty()) {
    proj.Description = this->PackageDescription;
  }

  if (!this->PackageLicense.empty()) {
    proj.DataLicense = this->PackageLicense;
  }

  return proj;
}

cmSpdxPackage cmExportSbomGenerator::GenerateImportTarget(
  cmSpdxCreationInfo const* ci, cmGeneratorTarget const* target) const
{
  cmSpdxPackage package;
  package.SpdxId = cmStrCat("urn:", target->GetName(), "#Package");
  package.Name = target->GetName();
  package.PrimaryPurpose = GetPurpose(target->GetType());
  package.CreationInfo = ci;

  if (!this->PackageVersion.empty()) {
    package.PackageVersion = this->PackageVersion;
  }

  if (!this->PackageWebsite.empty()) {
    package.Homepage = this->PackageWebsite;
  }

  if (!this->PackageUrl.empty()) {
    package.DownloadLocation = this->PackageUrl;
  }

  return package;
}

void cmExportSbomGenerator::GenerateLinkProperties(
  cmSbomDocument& doc, cmSpdxDocument* project, cmSpdxCreationInfo const* ci,
  std::string const& libraries, TargetProperties const& current,
  std::vector<TargetProperties> const& allTargets) const
{
  auto itProp = current.Properties.find(libraries);
  if (itProp == current.Properties.end()) {
    return;
  }

  std::map<std::string, std::vector<std::string>> allowList = { { "LINK_ONLY",
                                                                  {} } };
  std::string interfaceLinkLibraries;
  if (!cmGeneratorExpression::ForbidGeneratorExpressions(
        current.Target, itProp->first, itProp->second, interfaceLinkLibraries,
        allowList)) {
    return;
  }

  auto makeRel = [&](char const* id, char const* desc) {
    cmSpdxRelationship r;
    r.SpdxId = cmStrCat("urn:", id, "#Relationship");
    r.RelationshipType = cmSpdxRelationship::RelationshipTypeId::DEPENDS_ON;
    r.Description = desc;
    r.From = current.Package;
    r.CreationInfo = ci;
    return r;
  };

  auto linkLibraries = makeRel("Static", "Linked Libraries");
  auto linkRequires = makeRel("Dynamic", "Required Runtime Libraries");
  auto buildRequires = makeRel("Shared", "Required Build-Time Libraries");

  auto addArtifact =
    [&](std::string const& name) -> std::pair<bool, cmSpdxPackage const*> {
    auto it = this->LinkTargets.find(name);
    if (it != this->LinkTargets.end()) {
      LinkInfo const& linkInfo = it->second;
      if (linkInfo.Package.empty()) {
        for (auto const& t : allTargets) {
          if (t.Target->GetName() == linkInfo.Component) {
            return { true, t.Package };
          }
        }
      }
      std::string pkgName =
        cmStrCat(linkInfo.Package, ":", linkInfo.Component);
      cmSpdxPackage pkg;
      pkg.Name = pkgName;
      pkg.SpdxId = cmStrCat("urn:", pkgName, "#Package");
      pkg.CreationInfo = ci;
      if (!linkInfo.Package.empty()) {
        auto const& pkgIt = this->Requirements.find(linkInfo.Package);
        if (pkgIt != this->Requirements.end() &&
            pkgIt->second.Components.count(linkInfo.Component) > 0) {
          this->AddPackageInformation(pkg, pkgIt->first, pkgIt->second);
        }
      }
      return { true, insert_back(project->Elements, std::move(pkg)) };
    }

    cmSpdxPackage pkg;
    pkg.SpdxId = cmStrCat("urn:", name, "#Package");
    pkg.Name = name;
    pkg.CreationInfo = ci;
    return { false, insert_back(project->Elements, std::move(pkg)) };
  };

  auto handleDependencies = [&](std::vector<std::string> const& names,
                                cmSpdxRelationship& internalDeps,
                                cmSpdxRelationship& externalDeps) {
    for (auto const& n : names) {
      auto res = addArtifact(n);
      if (!res.second) {
        continue;
      }

      if (res.first) {
        internalDeps.To.push_back(res.second);
      } else {
        externalDeps.To.push_back(res.second);
      }
    }
  };

  handleDependencies(allowList["LINK_ONLY"], linkLibraries, linkRequires);
  handleDependencies(cmList{ interfaceLinkLibraries }, linkLibraries,
                     buildRequires);

  if (!linkLibraries.To.empty()) {
    insert_back(doc.Graph, std::move(linkLibraries));
  }
  if (!linkRequires.To.empty()) {
    insert_back(doc.Graph, std::move(linkRequires));
  }
  if (!buildRequires.To.empty()) {
    insert_back(doc.Graph, std::move(buildRequires));
  }
}

bool cmExportSbomGenerator::GenerateProperties(
  cmSbomDocument& doc, cmSpdxDocument* proj, cmSpdxCreationInfo const* ci,
  TargetProperties const& current,
  std::vector<TargetProperties> const& allTargets) const
{
  this->GenerateLinkProperties(doc, proj, ci, "LINK_LIBRARIES", current,
                               allTargets);
  this->GenerateLinkProperties(doc, proj, ci, "INTERFACE_LINK_LIBRARIES",
                               current, allTargets);
  return true;
}

bool cmExportSbomGenerator::PopulateLinkLibrariesProperty(
  cmGeneratorTarget const* target,
  cmGeneratorExpression::PreprocessContext preprocessRule,
  ImportPropertyMap& properties)
{
  static std::array<std::string, 3> const linkIfaceProps = {
    { "LINK_LIBRARIES", "LINK_LIBRARIES_DIRECT",
      "LINK_LIBRARIES_DIRECT_EXCLUDE" }
  };
  bool hadLINK_LIBRARIES = false;
  for (std::string const& linkIfaceProp : linkIfaceProps) {
    if (cmValue input = target->GetProperty(linkIfaceProp)) {
      std::string prepro =
        cmGeneratorExpression::Preprocess(*input, preprocessRule);
      if (!prepro.empty()) {
        this->ResolveTargetsInGeneratorExpressions(prepro, target,
                                                   ReplaceFreeTargets);
        properties[linkIfaceProp] = prepro;
        hadLINK_LIBRARIES = true;
      }
    }
  }
  return hadLINK_LIBRARIES;
}

bool cmExportSbomGenerator::NoteLinkedTarget(
  cmGeneratorTarget const* target, std::string const& linkedName,
  cmGeneratorTarget const* linkedTarget)
{
  if (cm::contains(this->ExportedTargets, linkedTarget)) {
    this->LinkTargets.emplace(linkedName,
                              LinkInfo{ "", linkedTarget->GetExportName() });
    return true;
  }

  if (linkedTarget->IsImported()) {
    using Package = cm::optional<std::pair<std::string, cmPackageInformation>>;
    auto pkgInfo = [](cmTarget* t) -> Package {
      cmFindPackageStack pkgStack = t->GetFindPackageStack();
      if (!pkgStack.Empty()) {
        return std::make_pair(pkgStack.Top().Name, pkgStack.Top().PackageInfo);
      }
      std::string const pkgName =
        t->GetSafeProperty("EXPORT_FIND_PACKAGE_NAME");
      if (pkgName.empty()) {
        return cm::nullopt;
      }
      cmPackageInformation package;
      return std::make_pair(pkgName, package);
    }(linkedTarget->Target);

    if (!pkgInfo) {
      target->Makefile->IssueMessage(
        MessageType::AUTHOR_WARNING,
        cmStrCat("Target \"", target->GetName(),
                 "\" references imported target \"", linkedName,
                 "\" which does not come from any known package."));
      return false;
    }

    std::string const& pkgName = pkgInfo->first;
    auto const& prefix = cmStrCat(pkgName, "::");
    std::string component;
    if (!cmHasPrefix(linkedName, prefix)) {
      component = linkedName;
    } else {
      component = linkedName.substr(prefix.length());
    }
    this->LinkTargets.emplace(linkedName, LinkInfo{ pkgName, component });
    cmPackageInformation& req =
      this->Requirements.insert(std::move(*pkgInfo)).first->second;
    req.Components.emplace(std::move(component));
    return true;
  }

  // Target belongs to another export from this build.
  auto const& exportInfo = this->FindExportInfo(linkedTarget);
  if (exportInfo.Namespaces.size() == 1 && exportInfo.Sets.size() == 1) {
    auto const& linkNamespace = *exportInfo.Namespaces.begin();
    if (!cmHasSuffix(linkNamespace, "::")) {
      target->Makefile->IssueMessage(
        MessageType::AUTHOR_WARNING,
        cmStrCat("Target \"", target->GetName(), "\" references target \"",
                 linkedName,
                 "\", which does not use the standard namespace separator. "
                 "This is not allowed."));
    }

    std::string pkgName{ linkNamespace.data(), linkNamespace.size() - 2 };
    std::string component = linkedTarget->GetExportName();
    if (pkgName == this->GetPackageName()) {
      this->LinkTargets.emplace(linkedName, LinkInfo{ "", component });
    } else {
      this->LinkTargets.emplace(linkedName, LinkInfo{ pkgName, component });
      this->Requirements[pkgName].Components.emplace(std::move(component));
    }
    return true;
  }

  // Target belongs to multiple namespaces or multiple export sets.
  // cmExportFileGenerator::HandleMissingTarget should have complained about
  // this already.
  return false;
}