blob: 10deba638fe6662d44d0f78553f2025a6b438624 [file] [log] [blame]
Andrew Geissler5199d832021-09-24 16:47:35 -05001#
2# SPDX-License-Identifier: GPL-2.0-only
3#
4
5DEPLOY_DIR_SPDX ??= "${DEPLOY_DIR}/spdx/${MACHINE}"
6
7# The product name that the CVE database uses. Defaults to BPN, but may need to
8# be overriden per recipe (for example tiff.bb sets CVE_PRODUCT=libtiff).
9CVE_PRODUCT ??= "${BPN}"
10CVE_VERSION ??= "${PV}"
11
12SPDXDIR ??= "${WORKDIR}/spdx"
13SPDXDEPLOY = "${SPDXDIR}/deploy"
14SPDXWORK = "${SPDXDIR}/work"
15
Patrick Williams93c203f2021-10-06 16:15:23 -050016SPDX_TOOL_NAME ??= "oe-spdx-creator"
17SPDX_TOOL_VERSION ??= "1.0"
18
Andrew Geissler5199d832021-09-24 16:47:35 -050019SPDXRUNTIMEDEPLOY = "${SPDXDIR}/runtime-deploy"
20
21SPDX_INCLUDE_SOURCES ??= "0"
22SPDX_INCLUDE_PACKAGED ??= "0"
23SPDX_ARCHIVE_SOURCES ??= "0"
24SPDX_ARCHIVE_PACKAGED ??= "0"
25
26SPDX_UUID_NAMESPACE ??= "sbom.openembedded.org"
27SPDX_NAMESPACE_PREFIX ??= "http://spdx.org/spdxdoc"
Andrew Geissler615f2f12022-07-15 14:00:58 -050028SPDX_PRETTY ??= "0"
Andrew Geissler5199d832021-09-24 16:47:35 -050029
30SPDX_LICENSES ??= "${COREBASE}/meta/files/spdx-licenses.json"
31
Andrew Geissler595f6302022-01-24 19:11:47 +000032SPDX_ORG ??= "OpenEmbedded ()"
Andrew Geissler7e0e3c02022-02-25 20:34:39 +000033SPDX_SUPPLIER ??= "Organization: ${SPDX_ORG}"
34SPDX_SUPPLIER[doc] = "The SPDX PackageSupplier field for SPDX packages created from \
35 this recipe. For SPDX documents create using this class during the build, this \
36 is the contact information for the person or organization who is doing the \
37 build."
Andrew Geissler595f6302022-01-24 19:11:47 +000038
Andrew Geissler7e0e3c02022-02-25 20:34:39 +000039def extract_licenses(filename):
40 import re
41
Andrew Geissler9aee5002022-03-30 16:27:02 +000042 lic_regex = re.compile(rb'^\W*SPDX-License-Identifier:\s*([ \w\d.()+-]+?)(?:\s+\W*)?$', re.MULTILINE)
Andrew Geissler7e0e3c02022-02-25 20:34:39 +000043
44 try:
45 with open(filename, 'rb') as f:
46 size = min(15000, os.stat(filename).st_size)
47 txt = f.read(size)
48 licenses = re.findall(lic_regex, txt)
49 if licenses:
50 ascii_licenses = [lic.decode('ascii') for lic in licenses]
51 return ascii_licenses
52 except Exception as e:
53 bb.warn(f"Exception reading {filename}: {e}")
54 return None
55
Andrew Geissler5199d832021-09-24 16:47:35 -050056def get_doc_namespace(d, doc):
57 import uuid
58 namespace_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, d.getVar("SPDX_UUID_NAMESPACE"))
59 return "%s/%s-%s" % (d.getVar("SPDX_NAMESPACE_PREFIX"), doc.name, str(uuid.uuid5(namespace_uuid, doc.name)))
60
Andrew Geisslereff27472021-10-29 15:35:00 -050061def create_annotation(d, comment):
62 from datetime import datetime, timezone
63
64 creation_time = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
65 annotation = oe.spdx.SPDXAnnotation()
66 annotation.annotationDate = creation_time
67 annotation.annotationType = "OTHER"
68 annotation.annotator = "Tool: %s - %s" % (d.getVar("SPDX_TOOL_NAME"), d.getVar("SPDX_TOOL_VERSION"))
69 annotation.comment = comment
70 return annotation
71
Patrick Williams93c203f2021-10-06 16:15:23 -050072def recipe_spdx_is_native(d, recipe):
73 return any(a.annotationType == "OTHER" and
74 a.annotator == "Tool: %s - %s" % (d.getVar("SPDX_TOOL_NAME"), d.getVar("SPDX_TOOL_VERSION")) and
75 a.comment == "isNative" for a in recipe.annotations)
Andrew Geissler5199d832021-09-24 16:47:35 -050076
Andrew Geissler595f6302022-01-24 19:11:47 +000077def is_work_shared_spdx(d):
78 return bb.data.inherits_class('kernel', d) or ('work-shared' in d.getVar('WORKDIR'))
Andrew Geissler5199d832021-09-24 16:47:35 -050079
Andrew Geissler615f2f12022-07-15 14:00:58 -050080def get_json_indent(d):
81 if d.getVar("SPDX_PRETTY") == "1":
82 return 2
83 return None
84
Andrew Geissler5199d832021-09-24 16:47:35 -050085python() {
86 import json
87 if d.getVar("SPDX_LICENSE_DATA"):
88 return
89
90 with open(d.getVar("SPDX_LICENSES"), "r") as f:
91 data = json.load(f)
92 # Transform the license array to a dictionary
93 data["licenses"] = {l["licenseId"]: l for l in data["licenses"]}
94 d.setVar("SPDX_LICENSE_DATA", data)
95}
96
97def convert_license_to_spdx(lic, document, d, existing={}):
98 from pathlib import Path
99 import oe.spdx
100
Andrew Geissler5199d832021-09-24 16:47:35 -0500101 license_data = d.getVar("SPDX_LICENSE_DATA")
102 extracted = {}
103
104 def add_extracted_license(ident, name):
105 nonlocal document
106
107 if name in extracted:
108 return
109
110 extracted_info = oe.spdx.SPDXExtractedLicensingInfo()
111 extracted_info.name = name
112 extracted_info.licenseId = ident
113 extracted_info.extractedText = None
114
115 if name == "PD":
116 # Special-case this.
117 extracted_info.extractedText = "Software released to the public domain"
Andrew Geissler9aee5002022-03-30 16:27:02 +0000118 else:
119 # Seach for the license in COMMON_LICENSE_DIR and LICENSE_PATH
Andrew Geissler595f6302022-01-24 19:11:47 +0000120 for directory in [d.getVar('COMMON_LICENSE_DIR')] + (d.getVar('LICENSE_PATH') or '').split():
Andrew Geissler5199d832021-09-24 16:47:35 -0500121 try:
122 with (Path(directory) / name).open(errors="replace") as f:
123 extracted_info.extractedText = f.read()
124 break
125 except FileNotFoundError:
126 pass
127 if extracted_info.extractedText is None:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000128 # If it's not SPDX or PD, then NO_GENERIC_LICENSE must be set
129 filename = d.getVarFlag('NO_GENERIC_LICENSE', name)
130 if filename:
131 filename = d.expand("${S}/" + filename)
132 with open(filename, errors="replace") as f:
133 extracted_info.extractedText = f.read()
134 else:
135 bb.error("Cannot find any text for license %s" % name)
Andrew Geissler5199d832021-09-24 16:47:35 -0500136
137 extracted[name] = extracted_info
138 document.hasExtractedLicensingInfos.append(extracted_info)
139
140 def convert(l):
141 if l == "(" or l == ")":
142 return l
143
144 if l == "&":
145 return "AND"
146
147 if l == "|":
148 return "OR"
149
150 if l == "CLOSED":
151 return "NONE"
152
153 spdx_license = d.getVarFlag("SPDXLICENSEMAP", l) or l
154 if spdx_license in license_data["licenses"]:
155 return spdx_license
156
157 try:
158 spdx_license = existing[l]
159 except KeyError:
160 spdx_license = "LicenseRef-" + l
161 add_extracted_license(spdx_license, l)
162
163 return spdx_license
164
165 lic_split = lic.replace("(", " ( ").replace(")", " ) ").split()
166
167 return ' '.join(convert(l) for l in lic_split)
168
Andrew Geissler5199d832021-09-24 16:47:35 -0500169def process_sources(d):
170 pn = d.getVar('PN')
171 assume_provided = (d.getVar("ASSUME_PROVIDED") or "").split()
172 if pn in assume_provided:
173 for p in d.getVar("PROVIDES").split():
174 if p != pn:
175 pn = p
176 break
177
178 # glibc-locale: do_fetch, do_unpack and do_patch tasks have been deleted,
179 # so avoid archiving source here.
180 if pn.startswith('glibc-locale'):
181 return False
182 if d.getVar('PN') == "libtool-cross":
183 return False
184 if d.getVar('PN') == "libgcc-initial":
185 return False
186 if d.getVar('PN') == "shadow-sysroot":
187 return False
188
189 # We just archive gcc-source for all the gcc related recipes
190 if d.getVar('BPN') in ['gcc', 'libgcc']:
191 bb.debug(1, 'spdx: There is bug in scan of %s is, do nothing' % pn)
192 return False
193
194 return True
195
196
197def add_package_files(d, doc, spdx_pkg, topdir, get_spdxid, get_types, *, archive=None, ignore_dirs=[], ignore_top_level_dirs=[]):
198 from pathlib import Path
199 import oe.spdx
200 import hashlib
201
202 source_date_epoch = d.getVar("SOURCE_DATE_EPOCH")
203 if source_date_epoch:
204 source_date_epoch = int(source_date_epoch)
205
206 sha1s = []
207 spdx_files = []
208
209 file_counter = 1
210 for subdir, dirs, files in os.walk(topdir):
211 dirs[:] = [d for d in dirs if d not in ignore_dirs]
212 if subdir == str(topdir):
213 dirs[:] = [d for d in dirs if d not in ignore_top_level_dirs]
214
215 for file in files:
216 filepath = Path(subdir) / file
217 filename = str(filepath.relative_to(topdir))
218
219 if filepath.is_file() and not filepath.is_symlink():
220 spdx_file = oe.spdx.SPDXFile()
221 spdx_file.SPDXID = get_spdxid(file_counter)
222 for t in get_types(filepath):
223 spdx_file.fileTypes.append(t)
224 spdx_file.fileName = filename
225
226 if archive is not None:
227 with filepath.open("rb") as f:
228 info = archive.gettarinfo(fileobj=f)
229 info.name = filename
230 info.uid = 0
231 info.gid = 0
232 info.uname = "root"
233 info.gname = "root"
234
235 if source_date_epoch is not None and info.mtime > source_date_epoch:
236 info.mtime = source_date_epoch
237
238 archive.addfile(info, f)
239
240 sha1 = bb.utils.sha1_file(filepath)
241 sha1s.append(sha1)
242 spdx_file.checksums.append(oe.spdx.SPDXChecksum(
243 algorithm="SHA1",
244 checksumValue=sha1,
245 ))
246 spdx_file.checksums.append(oe.spdx.SPDXChecksum(
247 algorithm="SHA256",
248 checksumValue=bb.utils.sha256_file(filepath),
249 ))
250
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000251 if "SOURCE" in spdx_file.fileTypes:
252 extracted_lics = extract_licenses(filepath)
253 if extracted_lics:
254 spdx_file.licenseInfoInFiles = extracted_lics
255
Andrew Geissler5199d832021-09-24 16:47:35 -0500256 doc.files.append(spdx_file)
257 doc.add_relationship(spdx_pkg, "CONTAINS", spdx_file)
258 spdx_pkg.hasFiles.append(spdx_file.SPDXID)
259
260 spdx_files.append(spdx_file)
261
262 file_counter += 1
263
264 sha1s.sort()
265 verifier = hashlib.sha1()
266 for v in sha1s:
267 verifier.update(v.encode("utf-8"))
268 spdx_pkg.packageVerificationCode.packageVerificationCodeValue = verifier.hexdigest()
269
270 return spdx_files
271
272
273def add_package_sources_from_debug(d, package_doc, spdx_package, package, package_files, sources):
274 from pathlib import Path
275 import hashlib
276 import oe.packagedata
277 import oe.spdx
278
279 debug_search_paths = [
280 Path(d.getVar('PKGD')),
281 Path(d.getVar('STAGING_DIR_TARGET')),
282 Path(d.getVar('STAGING_DIR_NATIVE')),
Andrew Geissler595f6302022-01-24 19:11:47 +0000283 Path(d.getVar('STAGING_KERNEL_DIR')),
Andrew Geissler5199d832021-09-24 16:47:35 -0500284 ]
285
286 pkg_data = oe.packagedata.read_subpkgdata_extended(package, d)
287
288 if pkg_data is None:
289 return
290
291 for file_path, file_data in pkg_data["files_info"].items():
292 if not "debugsrc" in file_data:
293 continue
294
295 for pkg_file in package_files:
296 if file_path.lstrip("/") == pkg_file.fileName.lstrip("/"):
297 break
298 else:
299 bb.fatal("No package file found for %s" % str(file_path))
300 continue
301
302 for debugsrc in file_data["debugsrc"]:
303 ref_id = "NOASSERTION"
304 for search in debug_search_paths:
Andrew Geissler595f6302022-01-24 19:11:47 +0000305 if debugsrc.startswith("/usr/src/kernel"):
306 debugsrc_path = search / debugsrc.replace('/usr/src/kernel/', '')
307 else:
308 debugsrc_path = search / debugsrc.lstrip("/")
Andrew Geissler5199d832021-09-24 16:47:35 -0500309 if not debugsrc_path.exists():
310 continue
311
312 file_sha256 = bb.utils.sha256_file(debugsrc_path)
313
314 if file_sha256 in sources:
315 source_file = sources[file_sha256]
316
317 doc_ref = package_doc.find_external_document_ref(source_file.doc.documentNamespace)
318 if doc_ref is None:
319 doc_ref = oe.spdx.SPDXExternalDocumentRef()
320 doc_ref.externalDocumentId = "DocumentRef-dependency-" + source_file.doc.name
321 doc_ref.spdxDocument = source_file.doc.documentNamespace
322 doc_ref.checksum.algorithm = "SHA1"
323 doc_ref.checksum.checksumValue = source_file.doc_sha1
324 package_doc.externalDocumentRefs.append(doc_ref)
325
326 ref_id = "%s:%s" % (doc_ref.externalDocumentId, source_file.file.SPDXID)
327 else:
328 bb.debug(1, "Debug source %s with SHA256 %s not found in any dependency" % (str(debugsrc_path), file_sha256))
329 break
330 else:
331 bb.debug(1, "Debug source %s not found" % debugsrc)
332
333 package_doc.add_relationship(pkg_file, "GENERATED_FROM", ref_id, comment=debugsrc)
334
335def collect_dep_recipes(d, doc, spdx_recipe):
336 from pathlib import Path
337 import oe.sbom
338 import oe.spdx
339
340 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
341
342 dep_recipes = []
343 taskdepdata = d.getVar("BB_TASKDEPDATA", False)
344 deps = sorted(set(
345 dep[0] for dep in taskdepdata.values() if
346 dep[1] == "do_create_spdx" and dep[0] != d.getVar("PN")
347 ))
348 for dep_pn in deps:
349 dep_recipe_path = deploy_dir_spdx / "recipes" / ("recipe-%s.spdx.json" % dep_pn)
350
351 spdx_dep_doc, spdx_dep_sha1 = oe.sbom.read_doc(dep_recipe_path)
352
353 for pkg in spdx_dep_doc.packages:
354 if pkg.name == dep_pn:
355 spdx_dep_recipe = pkg
356 break
357 else:
358 continue
359
360 dep_recipes.append(oe.sbom.DepRecipe(spdx_dep_doc, spdx_dep_sha1, spdx_dep_recipe))
361
362 dep_recipe_ref = oe.spdx.SPDXExternalDocumentRef()
363 dep_recipe_ref.externalDocumentId = "DocumentRef-dependency-" + spdx_dep_doc.name
364 dep_recipe_ref.spdxDocument = spdx_dep_doc.documentNamespace
365 dep_recipe_ref.checksum.algorithm = "SHA1"
366 dep_recipe_ref.checksum.checksumValue = spdx_dep_sha1
367
368 doc.externalDocumentRefs.append(dep_recipe_ref)
369
370 doc.add_relationship(
371 "%s:%s" % (dep_recipe_ref.externalDocumentId, spdx_dep_recipe.SPDXID),
372 "BUILD_DEPENDENCY_OF",
373 spdx_recipe
374 )
375
376 return dep_recipes
377
378collect_dep_recipes[vardepsexclude] += "BB_TASKDEPDATA"
379
380
381def collect_dep_sources(d, dep_recipes):
382 import oe.sbom
383
384 sources = {}
385 for dep in dep_recipes:
Patrick Williams93c203f2021-10-06 16:15:23 -0500386 # Don't collect sources from native recipes as they
387 # match non-native sources also.
388 if recipe_spdx_is_native(d, dep.recipe):
389 continue
Andrew Geissler5199d832021-09-24 16:47:35 -0500390 recipe_files = set(dep.recipe.hasFiles)
391
392 for spdx_file in dep.doc.files:
393 if spdx_file.SPDXID not in recipe_files:
394 continue
395
396 if "SOURCE" in spdx_file.fileTypes:
397 for checksum in spdx_file.checksums:
398 if checksum.algorithm == "SHA256":
399 sources[checksum.checksumValue] = oe.sbom.DepSource(dep.doc, dep.doc_sha1, dep.recipe, spdx_file)
400 break
401
402 return sources
403
404
405python do_create_spdx() {
406 from datetime import datetime, timezone
407 import oe.sbom
408 import oe.spdx
409 import uuid
410 from pathlib import Path
411 from contextlib import contextmanager
412 import oe.cve_check
413
414 @contextmanager
415 def optional_tarfile(name, guard, mode="w"):
416 import tarfile
417 import bb.compress.zstd
418
419 num_threads = int(d.getVar("BB_NUMBER_THREADS"))
420
421 if guard:
422 name.parent.mkdir(parents=True, exist_ok=True)
423 with bb.compress.zstd.open(name, mode=mode + "b", num_threads=num_threads) as f:
424 with tarfile.open(fileobj=f, mode=mode + "|") as tf:
425 yield tf
426 else:
427 yield None
428
429
430 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
431 spdx_workdir = Path(d.getVar("SPDXWORK"))
432 include_packaged = d.getVar("SPDX_INCLUDE_PACKAGED") == "1"
433 include_sources = d.getVar("SPDX_INCLUDE_SOURCES") == "1"
434 archive_sources = d.getVar("SPDX_ARCHIVE_SOURCES") == "1"
435 archive_packaged = d.getVar("SPDX_ARCHIVE_PACKAGED") == "1"
Andrew Geissler5199d832021-09-24 16:47:35 -0500436
437 creation_time = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
438
439 doc = oe.spdx.SPDXDocument()
440
441 doc.name = "recipe-" + d.getVar("PN")
442 doc.documentNamespace = get_doc_namespace(d, doc)
443 doc.creationInfo.created = creation_time
444 doc.creationInfo.comment = "This document was created by analyzing recipe files during the build."
445 doc.creationInfo.licenseListVersion = d.getVar("SPDX_LICENSE_DATA")["licenseListVersion"]
446 doc.creationInfo.creators.append("Tool: OpenEmbedded Core create-spdx.bbclass")
Andrew Geissler595f6302022-01-24 19:11:47 +0000447 doc.creationInfo.creators.append("Organization: %s" % d.getVar("SPDX_ORG"))
Andrew Geissler5199d832021-09-24 16:47:35 -0500448 doc.creationInfo.creators.append("Person: N/A ()")
449
450 recipe = oe.spdx.SPDXPackage()
451 recipe.name = d.getVar("PN")
452 recipe.versionInfo = d.getVar("PV")
453 recipe.SPDXID = oe.sbom.get_recipe_spdxid(d)
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500454 recipe.supplier = d.getVar("SPDX_SUPPLIER")
Andrew Geisslereff27472021-10-29 15:35:00 -0500455 if bb.data.inherits_class("native", d) or bb.data.inherits_class("cross", d):
456 recipe.annotations.append(create_annotation(d, "isNative"))
Andrew Geissler5199d832021-09-24 16:47:35 -0500457
458 for s in d.getVar('SRC_URI').split():
459 if not s.startswith("file://"):
460 recipe.downloadLocation = s
461 break
462 else:
463 recipe.downloadLocation = "NOASSERTION"
464
465 homepage = d.getVar("HOMEPAGE")
466 if homepage:
467 recipe.homepage = homepage
468
469 license = d.getVar("LICENSE")
470 if license:
471 recipe.licenseDeclared = convert_license_to_spdx(license, doc, d)
472
473 summary = d.getVar("SUMMARY")
474 if summary:
475 recipe.summary = summary
476
477 description = d.getVar("DESCRIPTION")
478 if description:
479 recipe.description = description
480
481 # Some CVEs may be patched during the build process without incrementing the version number,
482 # so querying for CVEs based on the CPE id can lead to false positives. To account for this,
483 # save the CVEs fixed by patches to source information field in the SPDX.
484 patched_cves = oe.cve_check.get_patched_cves(d)
485 patched_cves = list(patched_cves)
486 patched_cves = ' '.join(patched_cves)
487 if patched_cves:
488 recipe.sourceInfo = "CVEs fixed: " + patched_cves
489
490 cpe_ids = oe.cve_check.get_cpe_ids(d.getVar("CVE_PRODUCT"), d.getVar("CVE_VERSION"))
491 if cpe_ids:
492 for cpe_id in cpe_ids:
493 cpe = oe.spdx.SPDXExternalReference()
494 cpe.referenceCategory = "SECURITY"
495 cpe.referenceType = "http://spdx.org/rdf/references/cpe23Type"
496 cpe.referenceLocator = cpe_id
497 recipe.externalRefs.append(cpe)
498
499 doc.packages.append(recipe)
500 doc.add_relationship(doc, "DESCRIBES", recipe)
501
502 if process_sources(d) and include_sources:
503 recipe_archive = deploy_dir_spdx / "recipes" / (doc.name + ".tar.zst")
504 with optional_tarfile(recipe_archive, archive_sources) as archive:
505 spdx_get_src(d)
506
507 add_package_files(
508 d,
509 doc,
510 recipe,
511 spdx_workdir,
512 lambda file_counter: "SPDXRef-SourceFile-%s-%d" % (d.getVar("PN"), file_counter),
513 lambda filepath: ["SOURCE"],
514 ignore_dirs=[".git"],
515 ignore_top_level_dirs=["temp"],
516 archive=archive,
517 )
518
519 if archive is not None:
520 recipe.packageFileName = str(recipe_archive.name)
521
522 dep_recipes = collect_dep_recipes(d, doc, recipe)
523
Andrew Geissler615f2f12022-07-15 14:00:58 -0500524 doc_sha1 = oe.sbom.write_doc(d, doc, "recipes", indent=get_json_indent(d))
Andrew Geissler5199d832021-09-24 16:47:35 -0500525 dep_recipes.append(oe.sbom.DepRecipe(doc, doc_sha1, recipe))
526
527 recipe_ref = oe.spdx.SPDXExternalDocumentRef()
528 recipe_ref.externalDocumentId = "DocumentRef-recipe-" + recipe.name
529 recipe_ref.spdxDocument = doc.documentNamespace
530 recipe_ref.checksum.algorithm = "SHA1"
531 recipe_ref.checksum.checksumValue = doc_sha1
532
533 sources = collect_dep_sources(d, dep_recipes)
534 found_licenses = {license.name:recipe_ref.externalDocumentId + ":" + license.licenseId for license in doc.hasExtractedLicensingInfos}
535
Patrick Williams93c203f2021-10-06 16:15:23 -0500536 if not recipe_spdx_is_native(d, recipe):
Andrew Geissler5199d832021-09-24 16:47:35 -0500537 bb.build.exec_func("read_subpackage_metadata", d)
538
539 pkgdest = Path(d.getVar("PKGDEST"))
540 for package in d.getVar("PACKAGES").split():
541 if not oe.packagedata.packaged(package, d):
542 continue
543
544 package_doc = oe.spdx.SPDXDocument()
545 pkg_name = d.getVar("PKG:%s" % package) or package
546 package_doc.name = pkg_name
547 package_doc.documentNamespace = get_doc_namespace(d, package_doc)
548 package_doc.creationInfo.created = creation_time
549 package_doc.creationInfo.comment = "This document was created by analyzing packages created during the build."
550 package_doc.creationInfo.licenseListVersion = d.getVar("SPDX_LICENSE_DATA")["licenseListVersion"]
551 package_doc.creationInfo.creators.append("Tool: OpenEmbedded Core create-spdx.bbclass")
Andrew Geissler595f6302022-01-24 19:11:47 +0000552 package_doc.creationInfo.creators.append("Organization: %s" % d.getVar("SPDX_ORG"))
Andrew Geissler5199d832021-09-24 16:47:35 -0500553 package_doc.creationInfo.creators.append("Person: N/A ()")
554 package_doc.externalDocumentRefs.append(recipe_ref)
555
556 package_license = d.getVar("LICENSE:%s" % package) or d.getVar("LICENSE")
557
558 spdx_package = oe.spdx.SPDXPackage()
559
560 spdx_package.SPDXID = oe.sbom.get_package_spdxid(pkg_name)
561 spdx_package.name = pkg_name
562 spdx_package.versionInfo = d.getVar("PV")
563 spdx_package.licenseDeclared = convert_license_to_spdx(package_license, package_doc, d, found_licenses)
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500564 spdx_package.supplier = d.getVar("SPDX_SUPPLIER")
Andrew Geissler5199d832021-09-24 16:47:35 -0500565
566 package_doc.packages.append(spdx_package)
567
568 package_doc.add_relationship(spdx_package, "GENERATED_FROM", "%s:%s" % (recipe_ref.externalDocumentId, recipe.SPDXID))
569 package_doc.add_relationship(package_doc, "DESCRIBES", spdx_package)
570
571 package_archive = deploy_dir_spdx / "packages" / (package_doc.name + ".tar.zst")
572 with optional_tarfile(package_archive, archive_packaged) as archive:
573 package_files = add_package_files(
574 d,
575 package_doc,
576 spdx_package,
577 pkgdest / package,
578 lambda file_counter: oe.sbom.get_packaged_file_spdxid(pkg_name, file_counter),
579 lambda filepath: ["BINARY"],
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500580 ignore_top_level_dirs=['CONTROL', 'DEBIAN'],
Andrew Geissler5199d832021-09-24 16:47:35 -0500581 archive=archive,
582 )
583
584 if archive is not None:
585 spdx_package.packageFileName = str(package_archive.name)
586
587 add_package_sources_from_debug(d, package_doc, spdx_package, package, package_files, sources)
588
Andrew Geissler615f2f12022-07-15 14:00:58 -0500589 oe.sbom.write_doc(d, package_doc, "packages", indent=get_json_indent(d))
Andrew Geissler5199d832021-09-24 16:47:35 -0500590}
591# NOTE: depending on do_unpack is a hack that is necessary to get it's dependencies for archive the source
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000592addtask do_create_spdx after do_package do_packagedata do_unpack before do_populate_sdk do_build do_rm_work
Andrew Geissler5199d832021-09-24 16:47:35 -0500593
594SSTATETASKS += "do_create_spdx"
595do_create_spdx[sstate-inputdirs] = "${SPDXDEPLOY}"
596do_create_spdx[sstate-outputdirs] = "${DEPLOY_DIR_SPDX}"
597
598python do_create_spdx_setscene () {
599 sstate_setscene(d)
600}
601addtask do_create_spdx_setscene
602
Andrew Geissler9aee5002022-03-30 16:27:02 +0000603do_create_spdx[dirs] = "${SPDXWORK}"
Andrew Geissler5199d832021-09-24 16:47:35 -0500604do_create_spdx[cleandirs] = "${SPDXDEPLOY} ${SPDXWORK}"
605do_create_spdx[depends] += "${PATCHDEPENDENCY}"
606do_create_spdx[deptask] = "do_create_spdx"
607
608def collect_package_providers(d):
609 from pathlib import Path
610 import oe.sbom
611 import oe.spdx
612 import json
613
614 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
615
616 providers = {}
617
618 taskdepdata = d.getVar("BB_TASKDEPDATA", False)
619 deps = sorted(set(
620 dep[0] for dep in taskdepdata.values() if dep[0] != d.getVar("PN")
621 ))
622 deps.append(d.getVar("PN"))
623
624 for dep_pn in deps:
625 recipe_data = oe.packagedata.read_pkgdata(dep_pn, d)
626
627 for pkg in recipe_data.get("PACKAGES", "").split():
628
629 pkg_data = oe.packagedata.read_subpkgdata_dict(pkg, d)
630 rprovides = set(n for n, _ in bb.utils.explode_dep_versions2(pkg_data.get("RPROVIDES", "")).items())
631 rprovides.add(pkg)
632
633 for r in rprovides:
634 providers[r] = pkg
635
636 return providers
637
638collect_package_providers[vardepsexclude] += "BB_TASKDEPDATA"
639
640python do_create_runtime_spdx() {
641 from datetime import datetime, timezone
642 import oe.sbom
643 import oe.spdx
644 import oe.packagedata
645 from pathlib import Path
646
647 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
648 spdx_deploy = Path(d.getVar("SPDXRUNTIMEDEPLOY"))
Andrew Geisslereff27472021-10-29 15:35:00 -0500649 is_native = bb.data.inherits_class("native", d) or bb.data.inherits_class("cross", d)
Andrew Geissler5199d832021-09-24 16:47:35 -0500650
651 creation_time = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
652
653 providers = collect_package_providers(d)
654
655 if not is_native:
656 bb.build.exec_func("read_subpackage_metadata", d)
657
658 dep_package_cache = {}
659
660 pkgdest = Path(d.getVar("PKGDEST"))
661 for package in d.getVar("PACKAGES").split():
662 localdata = bb.data.createCopy(d)
663 pkg_name = d.getVar("PKG:%s" % package) or package
664 localdata.setVar("PKG", pkg_name)
665 localdata.setVar('OVERRIDES', d.getVar("OVERRIDES", False) + ":" + package)
666
667 if not oe.packagedata.packaged(package, localdata):
668 continue
669
670 pkg_spdx_path = deploy_dir_spdx / "packages" / (pkg_name + ".spdx.json")
671
672 package_doc, package_doc_sha1 = oe.sbom.read_doc(pkg_spdx_path)
673
674 for p in package_doc.packages:
675 if p.name == pkg_name:
676 spdx_package = p
677 break
678 else:
679 bb.fatal("Package '%s' not found in %s" % (pkg_name, pkg_spdx_path))
680
681 runtime_doc = oe.spdx.SPDXDocument()
682 runtime_doc.name = "runtime-" + pkg_name
683 runtime_doc.documentNamespace = get_doc_namespace(localdata, runtime_doc)
684 runtime_doc.creationInfo.created = creation_time
685 runtime_doc.creationInfo.comment = "This document was created by analyzing package runtime dependencies."
686 runtime_doc.creationInfo.licenseListVersion = d.getVar("SPDX_LICENSE_DATA")["licenseListVersion"]
687 runtime_doc.creationInfo.creators.append("Tool: OpenEmbedded Core create-spdx.bbclass")
Andrew Geissler595f6302022-01-24 19:11:47 +0000688 runtime_doc.creationInfo.creators.append("Organization: %s" % d.getVar("SPDX_ORG"))
Andrew Geissler5199d832021-09-24 16:47:35 -0500689 runtime_doc.creationInfo.creators.append("Person: N/A ()")
690
691 package_ref = oe.spdx.SPDXExternalDocumentRef()
692 package_ref.externalDocumentId = "DocumentRef-package-" + package
693 package_ref.spdxDocument = package_doc.documentNamespace
694 package_ref.checksum.algorithm = "SHA1"
695 package_ref.checksum.checksumValue = package_doc_sha1
696
697 runtime_doc.externalDocumentRefs.append(package_ref)
698
699 runtime_doc.add_relationship(
700 runtime_doc.SPDXID,
701 "AMENDS",
702 "%s:%s" % (package_ref.externalDocumentId, package_doc.SPDXID)
703 )
704
705 deps = bb.utils.explode_dep_versions2(localdata.getVar("RDEPENDS") or "")
706 seen_deps = set()
707 for dep, _ in deps.items():
708 if dep in seen_deps:
709 continue
710
Andrew Geissler595f6302022-01-24 19:11:47 +0000711 if dep not in providers:
712 continue
713
Andrew Geissler5199d832021-09-24 16:47:35 -0500714 dep = providers[dep]
715
716 if not oe.packagedata.packaged(dep, localdata):
717 continue
718
719 dep_pkg_data = oe.packagedata.read_subpkgdata_dict(dep, d)
720 dep_pkg = dep_pkg_data["PKG"]
721
722 if dep in dep_package_cache:
723 (dep_spdx_package, dep_package_ref) = dep_package_cache[dep]
724 else:
725 dep_path = deploy_dir_spdx / "packages" / ("%s.spdx.json" % dep_pkg)
726
727 spdx_dep_doc, spdx_dep_sha1 = oe.sbom.read_doc(dep_path)
728
729 for pkg in spdx_dep_doc.packages:
730 if pkg.name == dep_pkg:
731 dep_spdx_package = pkg
732 break
733 else:
734 bb.fatal("Package '%s' not found in %s" % (dep_pkg, dep_path))
735
736 dep_package_ref = oe.spdx.SPDXExternalDocumentRef()
737 dep_package_ref.externalDocumentId = "DocumentRef-runtime-dependency-" + spdx_dep_doc.name
738 dep_package_ref.spdxDocument = spdx_dep_doc.documentNamespace
739 dep_package_ref.checksum.algorithm = "SHA1"
740 dep_package_ref.checksum.checksumValue = spdx_dep_sha1
741
742 dep_package_cache[dep] = (dep_spdx_package, dep_package_ref)
743
744 runtime_doc.externalDocumentRefs.append(dep_package_ref)
745
746 runtime_doc.add_relationship(
747 "%s:%s" % (dep_package_ref.externalDocumentId, dep_spdx_package.SPDXID),
748 "RUNTIME_DEPENDENCY_OF",
749 "%s:%s" % (package_ref.externalDocumentId, spdx_package.SPDXID)
750 )
751 seen_deps.add(dep)
752
Andrew Geissler615f2f12022-07-15 14:00:58 -0500753 oe.sbom.write_doc(d, runtime_doc, "runtime", spdx_deploy, indent=get_json_indent(d))
Andrew Geissler5199d832021-09-24 16:47:35 -0500754}
755
756addtask do_create_runtime_spdx after do_create_spdx before do_build do_rm_work
757SSTATETASKS += "do_create_runtime_spdx"
758do_create_runtime_spdx[sstate-inputdirs] = "${SPDXRUNTIMEDEPLOY}"
759do_create_runtime_spdx[sstate-outputdirs] = "${DEPLOY_DIR_SPDX}"
760
761python do_create_runtime_spdx_setscene () {
762 sstate_setscene(d)
763}
764addtask do_create_runtime_spdx_setscene
765
766do_create_runtime_spdx[dirs] = "${SPDXRUNTIMEDEPLOY}"
767do_create_runtime_spdx[cleandirs] = "${SPDXRUNTIMEDEPLOY}"
768do_create_runtime_spdx[rdeptask] = "do_create_spdx"
769
770def spdx_get_src(d):
771 """
772 save patched source of the recipe in SPDX_WORKDIR.
773 """
774 import shutil
775 spdx_workdir = d.getVar('SPDXWORK')
776 spdx_sysroot_native = d.getVar('STAGING_DIR_NATIVE')
777 pn = d.getVar('PN')
778
779 workdir = d.getVar("WORKDIR")
780
781 try:
782 # The kernel class functions require it to be on work-shared, so we dont change WORKDIR
Andrew Geissler595f6302022-01-24 19:11:47 +0000783 if not is_work_shared_spdx(d):
Andrew Geissler5199d832021-09-24 16:47:35 -0500784 # Change the WORKDIR to make do_unpack do_patch run in another dir.
785 d.setVar('WORKDIR', spdx_workdir)
786 # Restore the original path to recipe's native sysroot (it's relative to WORKDIR).
787 d.setVar('STAGING_DIR_NATIVE', spdx_sysroot_native)
788
789 # The changed 'WORKDIR' also caused 'B' changed, create dir 'B' for the
790 # possibly requiring of the following tasks (such as some recipes's
791 # do_patch required 'B' existed).
792 bb.utils.mkdirhier(d.getVar('B'))
793
794 bb.build.exec_func('do_unpack', d)
795 # Copy source of kernel to spdx_workdir
Andrew Geissler595f6302022-01-24 19:11:47 +0000796 if is_work_shared_spdx(d):
Andrew Geissler5199d832021-09-24 16:47:35 -0500797 d.setVar('WORKDIR', spdx_workdir)
798 d.setVar('STAGING_DIR_NATIVE', spdx_sysroot_native)
799 src_dir = spdx_workdir + "/" + d.getVar('PN')+ "-" + d.getVar('PV') + "-" + d.getVar('PR')
800 bb.utils.mkdirhier(src_dir)
801 if bb.data.inherits_class('kernel',d):
802 share_src = d.getVar('STAGING_KERNEL_DIR')
803 cmd_copy_share = "cp -rf " + share_src + "/* " + src_dir + "/"
804 cmd_copy_kernel_result = os.popen(cmd_copy_share).read()
805 bb.note("cmd_copy_kernel_result = " + cmd_copy_kernel_result)
806
807 git_path = src_dir + "/.git"
808 if os.path.exists(git_path):
809 shutils.rmtree(git_path)
810
811 # Make sure gcc and kernel sources are patched only once
Andrew Geissler595f6302022-01-24 19:11:47 +0000812 if not (d.getVar('SRC_URI') == "" or is_work_shared_spdx(d)):
Andrew Geissler5199d832021-09-24 16:47:35 -0500813 bb.build.exec_func('do_patch', d)
814
815 # Some userland has no source.
816 if not os.path.exists( spdx_workdir ):
817 bb.utils.mkdirhier(spdx_workdir)
818 finally:
819 d.setVar("WORKDIR", workdir)
820
821do_rootfs[recrdeptask] += "do_create_spdx do_create_runtime_spdx"
822
823ROOTFS_POSTUNINSTALL_COMMAND =+ "image_combine_spdx ; "
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000824
825do_populate_sdk[recrdeptask] += "do_create_spdx do_create_runtime_spdx"
826POPULATE_SDK_POST_HOST_COMMAND:append:task-populate-sdk = " sdk_host_combine_spdx; "
827POPULATE_SDK_POST_TARGET_COMMAND:append:task-populate-sdk = " sdk_target_combine_spdx; "
828
Andrew Geissler5199d832021-09-24 16:47:35 -0500829python image_combine_spdx() {
830 import os
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000831 import oe.sbom
832 from pathlib import Path
833 from oe.rootfs import image_list_installed_packages
834
835 image_name = d.getVar("IMAGE_NAME")
836 image_link_name = d.getVar("IMAGE_LINK_NAME")
837 imgdeploydir = Path(d.getVar("IMGDEPLOYDIR"))
838 img_spdxid = oe.sbom.get_image_spdxid(image_name)
839 packages = image_list_installed_packages(d)
840
841 combine_spdx(d, image_name, imgdeploydir, img_spdxid, packages)
842
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000843 def make_image_link(target_path, suffix):
844 if image_link_name:
845 link = imgdeploydir / (image_link_name + suffix)
Patrick Williams03907ee2022-05-01 06:28:52 -0500846 if link != target_path:
847 link.symlink_to(os.path.relpath(target_path, link.parent))
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000848
Patrick Williams03907ee2022-05-01 06:28:52 -0500849 image_spdx_path = imgdeploydir / (image_name + ".spdx.json")
850 make_image_link(image_spdx_path, ".spdx.json")
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000851 spdx_tar_path = imgdeploydir / (image_name + ".spdx.tar.zst")
852 make_image_link(spdx_tar_path, ".spdx.tar.zst")
853 spdx_index_path = imgdeploydir / (image_name + ".spdx.index.json")
854 make_image_link(spdx_index_path, ".spdx.index.json")
855}
856
857python sdk_host_combine_spdx() {
858 sdk_combine_spdx(d, "host")
859}
860
861python sdk_target_combine_spdx() {
862 sdk_combine_spdx(d, "target")
863}
864
865def sdk_combine_spdx(d, sdk_type):
866 import oe.sbom
867 from pathlib import Path
868 from oe.sdk import sdk_list_installed_packages
869
870 sdk_name = d.getVar("SDK_NAME") + "-" + sdk_type
871 sdk_deploydir = Path(d.getVar("SDKDEPLOYDIR"))
872 sdk_spdxid = oe.sbom.get_sdk_spdxid(sdk_name)
873 sdk_packages = sdk_list_installed_packages(d, sdk_type == "target")
874 combine_spdx(d, sdk_name, sdk_deploydir, sdk_spdxid, sdk_packages)
875
876def combine_spdx(d, rootfs_name, rootfs_deploydir, rootfs_spdxid, packages):
877 import os
Andrew Geissler5199d832021-09-24 16:47:35 -0500878 import oe.spdx
879 import oe.sbom
880 import io
881 import json
Andrew Geissler5199d832021-09-24 16:47:35 -0500882 from datetime import timezone, datetime
883 from pathlib import Path
884 import tarfile
885 import bb.compress.zstd
886
887 creation_time = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
Andrew Geissler5199d832021-09-24 16:47:35 -0500888 deploy_dir_spdx = Path(d.getVar("DEPLOY_DIR_SPDX"))
Andrew Geissler5199d832021-09-24 16:47:35 -0500889 source_date_epoch = d.getVar("SOURCE_DATE_EPOCH")
890
891 doc = oe.spdx.SPDXDocument()
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000892 doc.name = rootfs_name
Andrew Geissler5199d832021-09-24 16:47:35 -0500893 doc.documentNamespace = get_doc_namespace(d, doc)
894 doc.creationInfo.created = creation_time
895 doc.creationInfo.comment = "This document was created by analyzing the source of the Yocto recipe during the build."
896 doc.creationInfo.licenseListVersion = d.getVar("SPDX_LICENSE_DATA")["licenseListVersion"]
897 doc.creationInfo.creators.append("Tool: OpenEmbedded Core create-spdx.bbclass")
Andrew Geissler595f6302022-01-24 19:11:47 +0000898 doc.creationInfo.creators.append("Organization: %s" % d.getVar("SPDX_ORG"))
Andrew Geissler5199d832021-09-24 16:47:35 -0500899 doc.creationInfo.creators.append("Person: N/A ()")
900
901 image = oe.spdx.SPDXPackage()
902 image.name = d.getVar("PN")
903 image.versionInfo = d.getVar("PV")
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000904 image.SPDXID = rootfs_spdxid
Patrick Williamsdb4c27e2022-08-05 08:10:29 -0500905 image.supplier = d.getVar("SPDX_SUPPLIER")
Andrew Geissler5199d832021-09-24 16:47:35 -0500906
907 doc.packages.append(image)
908
Andrew Geissler5199d832021-09-24 16:47:35 -0500909 for name in sorted(packages.keys()):
910 pkg_spdx_path = deploy_dir_spdx / "packages" / (name + ".spdx.json")
911 pkg_doc, pkg_doc_sha1 = oe.sbom.read_doc(pkg_spdx_path)
912
913 for p in pkg_doc.packages:
914 if p.name == name:
915 pkg_ref = oe.spdx.SPDXExternalDocumentRef()
916 pkg_ref.externalDocumentId = "DocumentRef-%s" % pkg_doc.name
917 pkg_ref.spdxDocument = pkg_doc.documentNamespace
918 pkg_ref.checksum.algorithm = "SHA1"
919 pkg_ref.checksum.checksumValue = pkg_doc_sha1
920
921 doc.externalDocumentRefs.append(pkg_ref)
922 doc.add_relationship(image, "CONTAINS", "%s:%s" % (pkg_ref.externalDocumentId, p.SPDXID))
923 break
924 else:
925 bb.fatal("Unable to find package with name '%s' in SPDX file %s" % (name, pkg_spdx_path))
926
927 runtime_spdx_path = deploy_dir_spdx / "runtime" / ("runtime-" + name + ".spdx.json")
928 runtime_doc, runtime_doc_sha1 = oe.sbom.read_doc(runtime_spdx_path)
929
930 runtime_ref = oe.spdx.SPDXExternalDocumentRef()
931 runtime_ref.externalDocumentId = "DocumentRef-%s" % runtime_doc.name
932 runtime_ref.spdxDocument = runtime_doc.documentNamespace
933 runtime_ref.checksum.algorithm = "SHA1"
934 runtime_ref.checksum.checksumValue = runtime_doc_sha1
935
936 # "OTHER" isn't ideal here, but I can't find a relationship that makes sense
937 doc.externalDocumentRefs.append(runtime_ref)
938 doc.add_relationship(
939 image,
940 "OTHER",
941 "%s:%s" % (runtime_ref.externalDocumentId, runtime_doc.SPDXID),
942 comment="Runtime dependencies for %s" % name
943 )
944
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000945 image_spdx_path = rootfs_deploydir / (rootfs_name + ".spdx.json")
Andrew Geissler5199d832021-09-24 16:47:35 -0500946
947 with image_spdx_path.open("wb") as f:
Andrew Geissler615f2f12022-07-15 14:00:58 -0500948 doc.to_json(f, sort_keys=True, indent=get_json_indent(d))
Andrew Geissler5199d832021-09-24 16:47:35 -0500949
Andrew Geissler5199d832021-09-24 16:47:35 -0500950 num_threads = int(d.getVar("BB_NUMBER_THREADS"))
951
952 visited_docs = set()
953
954 index = {"documents": []}
955
Andrew Geissler7e0e3c02022-02-25 20:34:39 +0000956 spdx_tar_path = rootfs_deploydir / (rootfs_name + ".spdx.tar.zst")
Andrew Geissler5199d832021-09-24 16:47:35 -0500957 with bb.compress.zstd.open(spdx_tar_path, "w", num_threads=num_threads) as f:
958 with tarfile.open(fileobj=f, mode="w|") as tar:
959 def collect_spdx_document(path):
960 nonlocal tar
961 nonlocal deploy_dir_spdx
962 nonlocal source_date_epoch
963 nonlocal index
964
965 if path in visited_docs:
966 return
967
968 visited_docs.add(path)
969
970 with path.open("rb") as f:
971 doc, sha1 = oe.sbom.read_doc(f)
972 f.seek(0)
973
974 if doc.documentNamespace in visited_docs:
975 return
976
977 bb.note("Adding SPDX document %s" % path)
978 visited_docs.add(doc.documentNamespace)
979 info = tar.gettarinfo(fileobj=f)
980
981 info.name = doc.name + ".spdx.json"
982 info.uid = 0
983 info.gid = 0
984 info.uname = "root"
985 info.gname = "root"
986
987 if source_date_epoch is not None and info.mtime > int(source_date_epoch):
988 info.mtime = int(source_date_epoch)
989
990 tar.addfile(info, f)
991
992 index["documents"].append({
993 "filename": info.name,
994 "documentNamespace": doc.documentNamespace,
995 "sha1": sha1,
996 })
997
998 for ref in doc.externalDocumentRefs:
999 ref_path = deploy_dir_spdx / "by-namespace" / ref.spdxDocument.replace("/", "_")
1000 collect_spdx_document(ref_path)
1001
1002 collect_spdx_document(image_spdx_path)
1003
1004 index["documents"].sort(key=lambda x: x["filename"])
1005
Andrew Geissler615f2f12022-07-15 14:00:58 -05001006 index_str = io.BytesIO(json.dumps(
1007 index,
1008 sort_keys=True,
1009 indent=get_json_indent(d),
1010 ).encode("utf-8"))
Andrew Geissler5199d832021-09-24 16:47:35 -05001011
1012 info = tarfile.TarInfo()
1013 info.name = "index.json"
1014 info.size = len(index_str.getvalue())
1015 info.uid = 0
1016 info.gid = 0
1017 info.uname = "root"
1018 info.gname = "root"
1019
1020 tar.addfile(info, fileobj=index_str)
1021
Andrew Geissler7e0e3c02022-02-25 20:34:39 +00001022 spdx_index_path = rootfs_deploydir / (rootfs_name + ".spdx.index.json")
Andrew Geissler5199d832021-09-24 16:47:35 -05001023 with spdx_index_path.open("w") as f:
Andrew Geissler615f2f12022-07-15 14:00:58 -05001024 json.dump(index, f, sort_keys=True, indent=get_json_indent(d))