blob: a46e5502ab3a5ff0706239ad618cf11aa78049b4 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Patrick Williams92b42cb2022-09-03 06:53:57 -05002# Copyright OpenEmbedded Contributors
3#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: GPL-2.0-only
5#
Patrick Williamsc124f4f2015-09-15 14:41:29 -05006import bb.siggen
Andrew Geisslerd25ed322020-06-27 00:28:28 -05007import bb.runqueue
Brad Bishop316dfdd2018-06-25 12:45:53 -04008import oe
Patrick Williams03514f12024-04-05 07:04:11 -05009import netrc
Patrick Williamsc124f4f2015-09-15 14:41:29 -050010
Andrew Geisslerd25ed322020-06-27 00:28:28 -050011def sstate_rundepfilter(siggen, fn, recipename, task, dep, depname, dataCaches):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050012 # Return True if we should keep the dependency, False to drop it
13 def isNative(x):
14 return x.endswith("-native")
15 def isCross(x):
16 return "-cross-" in x
17 def isNativeSDK(x):
18 return x.startswith("nativesdk-")
Andrew Geisslerd25ed322020-06-27 00:28:28 -050019 def isKernel(mc, fn):
20 inherits = " ".join(dataCaches[mc].inherits[fn])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050021 return inherits.find("/module-base.bbclass") != -1 or inherits.find("/linux-kernel-base.bbclass") != -1
Andrew Geisslerd25ed322020-06-27 00:28:28 -050022 def isPackageGroup(mc, fn):
23 inherits = " ".join(dataCaches[mc].inherits[fn])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050024 return "/packagegroup.bbclass" in inherits
Andrew Geisslerd25ed322020-06-27 00:28:28 -050025 def isAllArch(mc, fn):
26 inherits = " ".join(dataCaches[mc].inherits[fn])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050027 return "/allarch.bbclass" in inherits
Andrew Geisslerd25ed322020-06-27 00:28:28 -050028 def isImage(mc, fn):
29 return "/image.bbclass" in " ".join(dataCaches[mc].inherits[fn])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050030
Andrew Geisslerd25ed322020-06-27 00:28:28 -050031 depmc, _, deptaskname, depmcfn = bb.runqueue.split_tid_mcfn(dep)
32 mc, _ = bb.runqueue.split_mc(fn)
33
Patrick Williams7784c422022-11-17 07:29:11 -060034 # We can skip the rm_work task signature to avoid running the task
35 # when we remove some tasks from the dependencie chain
36 # i.e INHERIT:remove = "create-spdx" will trigger the do_rm_work
37 if task == "do_rm_work":
38 return False
39
Andrew Geisslerd25ed322020-06-27 00:28:28 -050040 # (Almost) always include our own inter-task dependencies (unless it comes
41 # from a mcdepends). The exception is the special
42 # do_kernel_configme->do_unpack_and_patch dependency from archiver.bbclass.
43 if recipename == depname and depmc == mc:
44 if task == "do_kernel_configme" and deptaskname == "do_unpack_and_patch":
Brad Bishop6e60e8b2018-02-01 10:27:11 -050045 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050046 return True
47
Patrick Williamsc124f4f2015-09-15 14:41:29 -050048 # Exclude well defined recipe->dependency
49 if "%s->%s" % (recipename, depname) in siggen.saferecipedeps:
50 return False
51
Brad Bishop316dfdd2018-06-25 12:45:53 -040052 # Check for special wildcard
53 if "*->%s" % depname in siggen.saferecipedeps and recipename != depname:
54 return False
55
Patrick Williamsc124f4f2015-09-15 14:41:29 -050056 # Don't change native/cross/nativesdk recipe dependencies any further
57 if isNative(recipename) or isCross(recipename) or isNativeSDK(recipename):
58 return True
59
60 # Only target packages beyond here
61
62 # allarch packagegroups are assumed to have well behaved names which don't change between architecures/tunes
Andrew Geisslerd25ed322020-06-27 00:28:28 -050063 if isPackageGroup(mc, fn) and isAllArch(mc, fn) and not isNative(depname):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080064 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050065
66 # Exclude well defined machine specific configurations which don't change ABI
Andrew Geisslerd25ed322020-06-27 00:28:28 -050067 if depname in siggen.abisaferecipes and not isImage(mc, fn):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050068 return False
69
70 # Kernel modules are well namespaced. We don't want to depend on the kernel's checksum
Patrick Williams213cb262021-08-07 19:21:33 -050071 # if we're just doing an RRECOMMENDS:xxx = "kernel-module-*", not least because the checksum
Patrick Williamsc124f4f2015-09-15 14:41:29 -050072 # is machine specific.
73 # Therefore if we're not a kernel or a module recipe (inheriting the kernel classes)
74 # and we reccomend a kernel-module, we exclude the dependency.
Andrew Geisslerd25ed322020-06-27 00:28:28 -050075 if dataCaches and isKernel(depmc, depmcfn) and not isKernel(mc, fn):
76 for pkg in dataCaches[mc].runrecs[fn]:
77 if " ".join(dataCaches[mc].runrecs[fn][pkg]).find("kernel-module-") != -1:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050078 return False
79
80 # Default to keep dependencies
81 return True
82
83def sstate_lockedsigs(d):
84 sigs = {}
Brad Bishop6e60e8b2018-02-01 10:27:11 -050085 types = (d.getVar("SIGGEN_LOCKEDSIGS_TYPES") or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050086 for t in types:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050087 siggen_lockedsigs_var = "SIGGEN_LOCKEDSIGS_%s" % t
Brad Bishop6e60e8b2018-02-01 10:27:11 -050088 lockedsigs = (d.getVar(siggen_lockedsigs_var) or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050089 for ls in lockedsigs:
90 pn, task, h = ls.split(":", 2)
91 if pn not in sigs:
92 sigs[pn] = {}
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050093 sigs[pn][task] = [h, siggen_lockedsigs_var]
Patrick Williamsc124f4f2015-09-15 14:41:29 -050094 return sigs
95
Brad Bishop00e122a2019-10-05 11:10:57 -040096class SignatureGeneratorOEBasicHashMixIn(object):
Andrew Geisslerd25ed322020-06-27 00:28:28 -050097 supports_multiconfig_datacaches = True
98
Patrick Williamsc124f4f2015-09-15 14:41:29 -050099 def init_rundepcheck(self, data):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500100 self.abisaferecipes = (data.getVar("SIGGEN_EXCLUDERECIPES_ABISAFE") or "").split()
101 self.saferecipedeps = (data.getVar("SIGGEN_EXCLUDE_SAFE_RECIPE_DEPS") or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500102 self.lockedsigs = sstate_lockedsigs(data)
103 self.lockedhashes = {}
104 self.lockedpnmap = {}
105 self.lockedhashfn = {}
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500106 self.machine = data.getVar("MACHINE")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500107 self.mismatch_msgs = []
Andrew Geissler20137392023-10-12 04:59:14 -0600108 self.mismatch_number = 0
109 self.lockedsigs_msgs = ""
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500110 self.unlockedrecipes = (data.getVar("SIGGEN_UNLOCKED_RECIPES") or
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500111 "").split()
112 self.unlockedrecipes = { k: "" for k in self.unlockedrecipes }
Andrew Geissler82c905d2020-04-13 13:39:40 -0500113 self._internal = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500114 pass
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500115
116 def tasks_resolved(self, virtmap, virtpnmap, dataCache):
117 # Translate virtual/xxx entries to PN values
118 newabisafe = []
119 for a in self.abisaferecipes:
120 if a in virtpnmap:
121 newabisafe.append(virtpnmap[a])
122 else:
123 newabisafe.append(a)
124 self.abisaferecipes = newabisafe
125 newsafedeps = []
126 for a in self.saferecipedeps:
127 a1, a2 = a.split("->")
128 if a1 in virtpnmap:
129 a1 = virtpnmap[a1]
130 if a2 in virtpnmap:
131 a2 = virtpnmap[a2]
132 newsafedeps.append(a1 + "->" + a2)
133 self.saferecipedeps = newsafedeps
134
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500135 def rundep_check(self, fn, recipename, task, dep, depname, dataCaches = None):
136 return sstate_rundepfilter(self, fn, recipename, task, dep, depname, dataCaches)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500137
138 def get_taskdata(self):
Brad Bishop00e122a2019-10-05 11:10:57 -0400139 return (self.lockedpnmap, self.lockedhashfn, self.lockedhashes) + super().get_taskdata()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500140
141 def set_taskdata(self, data):
Brad Bishop00e122a2019-10-05 11:10:57 -0400142 self.lockedpnmap, self.lockedhashfn, self.lockedhashes = data[:3]
143 super().set_taskdata(data[3:])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500144
145 def dump_sigs(self, dataCache, options):
Patrick Williamsac13d5f2023-11-24 18:59:46 -0600146 if 'lockedsigs' in options:
147 sigfile = os.getcwd() + "/locked-sigs.inc"
148 bb.plain("Writing locked sigs to %s" % sigfile)
149 self.dump_lockedsigs(sigfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500150 return super(bb.siggen.SignatureGeneratorBasicHash, self).dump_sigs(dataCache, options)
151
Andrew Geissler82c905d2020-04-13 13:39:40 -0500152
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500153 def get_taskhash(self, tid, deps, dataCaches):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500154 if tid in self.lockedhashes:
155 if self.lockedhashes[tid]:
156 return self.lockedhashes[tid]
157 else:
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500158 return super().get_taskhash(tid, deps, dataCaches)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500159
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500160 h = super().get_taskhash(tid, deps, dataCaches)
Brad Bishop08902b02019-08-20 09:16:51 -0400161
162 (mc, _, task, fn) = bb.runqueue.split_tid_mcfn(tid)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500163
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500164 recipename = dataCaches[mc].pkg_fn[fn]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500165 self.lockedpnmap[fn] = recipename
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500166 self.lockedhashfn[fn] = dataCaches[mc].hashfn[fn]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500167
168 unlocked = False
169 if recipename in self.unlockedrecipes:
170 unlocked = True
171 else:
172 def recipename_from_dep(dep):
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500173 (depmc, _, _, depfn) = bb.runqueue.split_tid_mcfn(dep)
174 return dataCaches[depmc].pkg_fn[depfn]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500175
176 # If any unlocked recipe is in the direct dependencies then the
177 # current recipe should be unlocked as well.
Brad Bishop08902b02019-08-20 09:16:51 -0400178 depnames = [ recipename_from_dep(x) for x in deps if mc == bb.runqueue.mc_from_tid(x)]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500179 if any(x in y for y in depnames for x in self.unlockedrecipes):
180 self.unlockedrecipes[recipename] = ''
181 unlocked = True
182
183 if not unlocked and recipename in self.lockedsigs:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500184 if task in self.lockedsigs[recipename]:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500185 h_locked = self.lockedsigs[recipename][task][0]
186 var = self.lockedsigs[recipename][task][1]
Brad Bishop08902b02019-08-20 09:16:51 -0400187 self.lockedhashes[tid] = h_locked
Andrew Geissler82c905d2020-04-13 13:39:40 -0500188 self._internal = True
189 unihash = self.get_unihash(tid)
190 self._internal = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500191 #bb.warn("Using %s %s %s" % (recipename, task, h))
192
Brad Bishop00e122a2019-10-05 11:10:57 -0400193 if h != h_locked and h_locked != unihash:
Andrew Geissler20137392023-10-12 04:59:14 -0600194 self.mismatch_number += 1
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500195 self.mismatch_msgs.append('The %s:%s sig is computed to be %s, but the sig is locked to %s in %s'
196 % (recipename, task, h, h_locked, var))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500197
198 return h_locked
Andrew Geissler82c905d2020-04-13 13:39:40 -0500199
200 self.lockedhashes[tid] = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500201 #bb.warn("%s %s %s" % (recipename, task, h))
202 return h
203
Andrew Geissler82c905d2020-04-13 13:39:40 -0500204 def get_stampfile_hash(self, tid):
205 if tid in self.lockedhashes and self.lockedhashes[tid]:
206 return self.lockedhashes[tid]
207 return super().get_stampfile_hash(tid)
208
Patrick Williams73bd93f2024-02-20 08:07:48 -0600209 def get_cached_unihash(self, tid):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500210 if tid in self.lockedhashes and self.lockedhashes[tid] and not self._internal:
Brad Bishop00e122a2019-10-05 11:10:57 -0400211 return self.lockedhashes[tid]
Patrick Williams73bd93f2024-02-20 08:07:48 -0600212 return super().get_cached_unihash(tid)
Brad Bishop00e122a2019-10-05 11:10:57 -0400213
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500214 def dump_sigtask(self, fn, task, stampbase, runtime):
Brad Bishop08902b02019-08-20 09:16:51 -0400215 tid = fn + ":" + task
Andrew Geissler82c905d2020-04-13 13:39:40 -0500216 if tid in self.lockedhashes and self.lockedhashes[tid]:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500217 return
218 super(bb.siggen.SignatureGeneratorBasicHash, self).dump_sigtask(fn, task, stampbase, runtime)
219
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600220 def dump_lockedsigs(self, sigfile, taskfilter=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500221 types = {}
Brad Bishop08902b02019-08-20 09:16:51 -0400222 for tid in self.runtaskdeps:
Patrick Williams2a254922023-08-11 09:48:11 -0500223 # Bitbake changed this to a tuple in newer versions
224 if isinstance(tid, tuple):
225 tid = tid[1]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500226 if taskfilter:
Brad Bishop08902b02019-08-20 09:16:51 -0400227 if not tid in taskfilter:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500228 continue
Brad Bishop08902b02019-08-20 09:16:51 -0400229 fn = bb.runqueue.fn_from_tid(tid)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500230 t = self.lockedhashfn[fn].split(" ")[1].split(":")[5]
231 t = 't-' + t.replace('_', '-')
232 if t not in types:
233 types[t] = []
Brad Bishop08902b02019-08-20 09:16:51 -0400234 types[t].append(tid)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500235
236 with open(sigfile, "w") as f:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500237 l = sorted(types)
238 for t in l:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500239 f.write('SIGGEN_LOCKEDSIGS_%s = "\\\n' % t)
240 types[t].sort()
Brad Bishop08902b02019-08-20 09:16:51 -0400241 sortedtid = sorted(types[t], key=lambda tid: self.lockedpnmap[bb.runqueue.fn_from_tid(tid)])
242 for tid in sortedtid:
243 (_, _, task, fn) = bb.runqueue.split_tid_mcfn(tid)
244 if tid not in self.taskhash:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500245 continue
Brad Bishop00e122a2019-10-05 11:10:57 -0400246 f.write(" " + self.lockedpnmap[fn] + ":" + task + ":" + self.get_unihash(tid) + " \\\n")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500247 f.write(' "\n')
Patrick Williams213cb262021-08-07 19:21:33 -0500248 f.write('SIGGEN_LOCKEDSIGS_TYPES:%s = "%s"' % (self.machine, " ".join(l)))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500249
Andrew Geissler09036742021-06-25 14:25:14 -0500250 def dump_siglist(self, sigfile, path_prefix_strip=None):
251 def strip_fn(fn):
252 nonlocal path_prefix_strip
253 if not path_prefix_strip:
254 return fn
255
256 fn_exp = fn.split(":")
257 if fn_exp[-1].startswith(path_prefix_strip):
258 fn_exp[-1] = fn_exp[-1][len(path_prefix_strip):]
259
260 return ":".join(fn_exp)
261
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500262 with open(sigfile, "w") as f:
263 tasks = []
264 for taskitem in self.taskhash:
Brad Bishop08902b02019-08-20 09:16:51 -0400265 (fn, task) = taskitem.rsplit(":", 1)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500266 pn = self.lockedpnmap[fn]
Andrew Geissler09036742021-06-25 14:25:14 -0500267 tasks.append((pn, task, strip_fn(fn), self.taskhash[taskitem]))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500268 for (pn, task, fn, taskhash) in sorted(tasks):
Brad Bishop08902b02019-08-20 09:16:51 -0400269 f.write('%s:%s %s %s\n' % (pn, task, fn, taskhash))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500270
Brad Bishop08902b02019-08-20 09:16:51 -0400271 def checkhashes(self, sq_data, missed, found, d):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500272 warn_msgs = []
273 error_msgs = []
274 sstate_missing_msgs = []
Andrew Geissler20137392023-10-12 04:59:14 -0600275 info_msgs = None
276
277 if self.lockedsigs:
278 if len(self.lockedsigs) > 10:
279 self.lockedsigs_msgs = "There are %s recipes with locked tasks (%s task(s) have non matching signature)" % (len(self.lockedsigs), self.mismatch_number)
280 else:
281 self.lockedsigs_msgs = "The following recipes have locked tasks:"
282 for pn in self.lockedsigs:
283 self.lockedsigs_msgs += " %s" % (pn)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500284
Brad Bishop08902b02019-08-20 09:16:51 -0400285 for tid in sq_data['hash']:
286 if tid not in found:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500287 for pn in self.lockedsigs:
Brad Bishop08902b02019-08-20 09:16:51 -0400288 taskname = bb.runqueue.taskname_from_tid(tid)
289 if sq_data['hash'][tid] in iter(self.lockedsigs[pn].values()):
290 if taskname == 'do_shared_workdir':
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500291 continue
292 sstate_missing_msgs.append("Locked sig is set for %s:%s (%s) yet not in sstate cache?"
Brad Bishop08902b02019-08-20 09:16:51 -0400293 % (pn, taskname, sq_data['hash'][tid]))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500294
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500295 checklevel = d.getVar("SIGGEN_LOCKEDSIGS_TASKSIG_CHECK")
Andrew Geissler20137392023-10-12 04:59:14 -0600296 if checklevel == 'info':
297 info_msgs = self.lockedsigs_msgs
298 if checklevel == 'warn' or checklevel == 'info':
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500299 warn_msgs += self.mismatch_msgs
300 elif checklevel == 'error':
301 error_msgs += self.mismatch_msgs
302
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500303 checklevel = d.getVar("SIGGEN_LOCKEDSIGS_SSTATE_EXISTS_CHECK")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500304 if checklevel == 'warn':
305 warn_msgs += sstate_missing_msgs
306 elif checklevel == 'error':
307 error_msgs += sstate_missing_msgs
308
Andrew Geissler20137392023-10-12 04:59:14 -0600309 if info_msgs:
310 bb.note(info_msgs)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500311 if warn_msgs:
312 bb.warn("\n".join(warn_msgs))
313 if error_msgs:
314 bb.fatal("\n".join(error_msgs))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500315
Brad Bishop00e122a2019-10-05 11:10:57 -0400316class SignatureGeneratorOEBasicHash(SignatureGeneratorOEBasicHashMixIn, bb.siggen.SignatureGeneratorBasicHash):
317 name = "OEBasicHash"
318
319class SignatureGeneratorOEEquivHash(SignatureGeneratorOEBasicHashMixIn, bb.siggen.SignatureGeneratorUniHashMixIn, bb.siggen.SignatureGeneratorBasicHash):
Brad Bishop19323692019-04-05 15:28:33 -0400320 name = "OEEquivHash"
321
322 def init_rundepcheck(self, data):
323 super().init_rundepcheck(data)
Brad Bishopa34c0302019-09-23 22:34:48 -0400324 self.server = data.getVar('BB_HASHSERVE')
Brad Bishop08902b02019-08-20 09:16:51 -0400325 if not self.server:
Brad Bishopa34c0302019-09-23 22:34:48 -0400326 bb.fatal("OEEquivHash requires BB_HASHSERVE to be set")
Brad Bishop19323692019-04-05 15:28:33 -0400327 self.method = data.getVar('SSTATE_HASHEQUIV_METHOD')
Brad Bishop08902b02019-08-20 09:16:51 -0400328 if not self.method:
329 bb.fatal("OEEquivHash requires SSTATE_HASHEQUIV_METHOD to be set")
Patrick Williams73bd93f2024-02-20 08:07:48 -0600330 self.max_parallel = int(data.getVar('BB_HASHSERVE_MAX_PARALLEL') or 1)
Patrick Williams03514f12024-04-05 07:04:11 -0500331 self.username = data.getVar("BB_HASHSERVE_USERNAME")
332 self.password = data.getVar("BB_HASHSERVE_PASSWORD")
333 if not self.username or not self.password:
334 try:
335 n = netrc.netrc()
336 auth = n.authenticators(self.server)
337 if auth is not None:
338 self.username, _, self.password = auth
339 except FileNotFoundError:
340 pass
341 except netrc.NetrcParseError as e:
342 bb.warn("Error parsing %s:%s: %s" % (e.filename, str(e.lineno), e.msg))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500343
344# Insert these classes into siggen's namespace so it can see and select them
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500345bb.siggen.SignatureGeneratorOEBasicHash = SignatureGeneratorOEBasicHash
Brad Bishop19323692019-04-05 15:28:33 -0400346bb.siggen.SignatureGeneratorOEEquivHash = SignatureGeneratorOEEquivHash
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500347
348
349def find_siginfo(pn, taskname, taskhashlist, d):
350 """ Find signature data files for comparison purposes """
351
352 import fnmatch
353 import glob
354
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500355 if not taskname:
356 # We have to derive pn and taskname
357 key = pn
Patrick Williams2a254922023-08-11 09:48:11 -0500358 if key.startswith("mc:"):
359 # mc:<mc>:<pn>:<task>
360 _, _, pn, taskname = key.split(':', 3)
361 else:
362 # <pn>:<task>
363 pn, taskname = key.split(':', 1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500364
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500365 hashfiles = {}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500366
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500367 def get_hashval(siginfo):
368 if siginfo.endswith('.siginfo'):
369 return siginfo.rpartition(':')[2].partition('_')[0]
370 else:
371 return siginfo.rpartition('.')[2]
372
Patrick Williams169d7bc2024-01-05 11:33:25 -0600373 def get_time(fullpath):
374 return os.stat(fullpath).st_mtime
375
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500376 # First search in stamps dir
377 localdata = d.createCopy()
378 localdata.setVar('MULTIMACH_TARGET_SYS', '*')
379 localdata.setVar('PN', pn)
380 localdata.setVar('PV', '*')
381 localdata.setVar('PR', '*')
382 localdata.setVar('EXTENDPE', '')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500383 stamp = localdata.getVar('STAMP')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500384 if pn.startswith("gcc-source"):
385 # gcc-source shared workdir is a special case :(
386 stamp = localdata.expand("${STAMPS_DIR}/work-shared/gcc-${PV}-${PR}")
387
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500388 filespec = '%s.%s.sigdata.*' % (stamp, taskname)
389 foundall = False
390 import glob
Patrick Williams169d7bc2024-01-05 11:33:25 -0600391 bb.debug(1, "Calling glob.glob on {}".format(filespec))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500392 for fullpath in glob.glob(filespec):
393 match = False
394 if taskhashlist:
395 for taskhash in taskhashlist:
396 if fullpath.endswith('.%s' % taskhash):
Patrick Williams169d7bc2024-01-05 11:33:25 -0600397 hashfiles[taskhash] = {'path':fullpath, 'sstate':False, 'time':get_time(fullpath)}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500398 if len(hashfiles) == len(taskhashlist):
399 foundall = True
400 break
401 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500402 hashval = get_hashval(fullpath)
Patrick Williams169d7bc2024-01-05 11:33:25 -0600403 hashfiles[hashval] = {'path':fullpath, 'sstate':False, 'time':get_time(fullpath)}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500404
Patrick Williams169d7bc2024-01-05 11:33:25 -0600405 if not taskhashlist or (len(hashfiles) < 2 and not foundall):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500406 # That didn't work, look in sstate-cache
Brad Bishop19323692019-04-05 15:28:33 -0400407 hashes = taskhashlist or ['?' * 64]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500408 localdata = bb.data.createCopy(d)
409 for hashval in hashes:
410 localdata.setVar('PACKAGE_ARCH', '*')
411 localdata.setVar('TARGET_VENDOR', '*')
412 localdata.setVar('TARGET_OS', '*')
413 localdata.setVar('PN', pn)
Patrick Williams169d7bc2024-01-05 11:33:25 -0600414 # gcc-source is a special case, same as with local stamps above
415 if pn.startswith("gcc-source"):
416 localdata.setVar('PN', "gcc")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500417 localdata.setVar('PV', '*')
418 localdata.setVar('PR', '*')
419 localdata.setVar('BB_TASKHASH', hashval)
Patrick Williams03907ee2022-05-01 06:28:52 -0500420 localdata.setVar('SSTATE_CURRTASK', taskname[3:])
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500421 swspec = localdata.getVar('SSTATE_SWSPEC')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500422 if taskname in ['do_fetch', 'do_unpack', 'do_patch', 'do_populate_lic', 'do_preconfigure'] and swspec:
423 localdata.setVar('SSTATE_PKGSPEC', '${SSTATE_SWSPEC}')
424 elif pn.endswith('-native') or "-cross-" in pn or "-crosssdk-" in pn:
425 localdata.setVar('SSTATE_EXTRAPATH', "${NATIVELSBSTRING}/")
Patrick Williams03907ee2022-05-01 06:28:52 -0500426 filespec = '%s.siginfo' % localdata.getVar('SSTATE_PKG')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500427
Patrick Williams169d7bc2024-01-05 11:33:25 -0600428 bb.debug(1, "Calling glob.glob on {}".format(filespec))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500429 matchedfiles = glob.glob(filespec)
430 for fullpath in matchedfiles:
431 actual_hashval = get_hashval(fullpath)
432 if actual_hashval in hashfiles:
433 continue
Patrick Williams2f814a62024-04-16 16:28:03 -0500434 hashfiles[actual_hashval] = {'path':fullpath, 'sstate':True, 'time':get_time(fullpath)}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500435
Patrick Williams169d7bc2024-01-05 11:33:25 -0600436 return hashfiles
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500437
438bb.siggen.find_siginfo = find_siginfo
Patrick Williams169d7bc2024-01-05 11:33:25 -0600439bb.siggen.find_siginfo_version = 2
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500440
441
442def sstate_get_manifest_filename(task, d):
443 """
444 Return the sstate manifest file path for a particular task.
445 Also returns the datastore that can be used to query related variables.
446 """
447 d2 = d.createCopy()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500448 extrainf = d.getVarFlag("do_" + task, 'stamp-extra-info')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500449 if extrainf:
450 d2.setVar("SSTATE_MANMACH", extrainf)
451 return (d2.expand("${SSTATE_MANFILEPREFIX}.%s" % task), d2)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400452
453def find_sstate_manifest(taskdata, taskdata2, taskname, d, multilibcache):
454 d2 = d
455 variant = ''
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800456 curr_variant = ''
457 if d.getVar("BBEXTENDCURR") == "multilib":
458 curr_variant = d.getVar("BBEXTENDVARIANT")
459 if "virtclass-multilib" not in d.getVar("OVERRIDES"):
460 curr_variant = "invalid"
Brad Bishop316dfdd2018-06-25 12:45:53 -0400461 if taskdata2.startswith("virtual:multilib"):
462 variant = taskdata2.split(":")[2]
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800463 if curr_variant != variant:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400464 if variant not in multilibcache:
465 multilibcache[variant] = oe.utils.get_multilib_datastore(variant, d)
466 d2 = multilibcache[variant]
467
468 if taskdata.endswith("-native"):
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600469 pkgarchs = ["${BUILD_ARCH}", "${BUILD_ARCH}_${ORIGNATIVELSBSTRING}"]
Brad Bishop316dfdd2018-06-25 12:45:53 -0400470 elif taskdata.startswith("nativesdk-"):
471 pkgarchs = ["${SDK_ARCH}_${SDK_OS}", "allarch"]
472 elif "-cross-canadian" in taskdata:
473 pkgarchs = ["${SDK_ARCH}_${SDK_ARCH}-${SDKPKGSUFFIX}"]
474 elif "-cross-" in taskdata:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000475 pkgarchs = ["${BUILD_ARCH}"]
Brad Bishop316dfdd2018-06-25 12:45:53 -0400476 elif "-crosssdk" in taskdata:
477 pkgarchs = ["${BUILD_ARCH}_${SDK_ARCH}_${SDK_OS}"]
478 else:
479 pkgarchs = ['${MACHINE_ARCH}']
480 pkgarchs = pkgarchs + list(reversed(d2.getVar("PACKAGE_EXTRA_ARCHS").split()))
481 pkgarchs.append('allarch')
482 pkgarchs.append('${SDK_ARCH}_${SDK_ARCH}-${SDKPKGSUFFIX}')
483
Andrew Geissler517393d2023-01-13 08:55:19 -0600484 searched_manifests = []
485
Brad Bishop316dfdd2018-06-25 12:45:53 -0400486 for pkgarch in pkgarchs:
487 manifest = d2.expand("${SSTATE_MANIFESTS}/manifest-%s-%s.%s" % (pkgarch, taskdata, taskname))
488 if os.path.exists(manifest):
489 return manifest, d2
Andrew Geissler517393d2023-01-13 08:55:19 -0600490 searched_manifests.append(manifest)
491 bb.fatal("The sstate manifest for task '%s:%s' (multilib variant '%s') could not be found.\nThe pkgarchs considered were: %s.\nBut none of these manifests exists:\n %s"
492 % (taskdata, taskname, variant, d2.expand(", ".join(pkgarchs)),"\n ".join(searched_manifests)))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400493 return None, d2
494
Brad Bishop19323692019-04-05 15:28:33 -0400495def OEOuthashBasic(path, sigfile, task, d):
496 """
497 Basic output hash function
498
499 Calculates the output hash of a task by hashing all output file metadata,
500 and file contents.
501 """
502 import hashlib
503 import stat
504 import pwd
505 import grp
Patrick Williams93c203f2021-10-06 16:15:23 -0500506 import re
507 import fnmatch
Brad Bishop19323692019-04-05 15:28:33 -0400508
509 def update_hash(s):
510 s = s.encode('utf-8')
511 h.update(s)
512 if sigfile:
513 sigfile.write(s)
514
515 h = hashlib.sha256()
516 prev_dir = os.getcwd()
Patrick Williams93c203f2021-10-06 16:15:23 -0500517 corebase = d.getVar("COREBASE")
518 tmpdir = d.getVar("TMPDIR")
Brad Bishop19323692019-04-05 15:28:33 -0400519 include_owners = os.environ.get('PSEUDO_DISABLED') == '0'
Andrew Geisslerf0343792020-11-18 10:42:21 -0600520 if "package_write_" in task or task == "package_qa":
521 include_owners = False
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600522 include_timestamps = False
Andrew Geissler5199d832021-09-24 16:47:35 -0500523 include_root = True
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600524 if task == "package":
Andrew Geisslereff27472021-10-29 15:35:00 -0500525 include_timestamps = True
Andrew Geissler5199d832021-09-24 16:47:35 -0500526 include_root = False
Andrew Geissler595f6302022-01-24 19:11:47 +0000527 hash_version = d.getVar('HASHEQUIV_HASH_VERSION')
528 extra_sigdata = d.getVar("HASHEQUIV_EXTRA_SIGDATA")
Brad Bishop19323692019-04-05 15:28:33 -0400529
Patrick Williams93c203f2021-10-06 16:15:23 -0500530 filemaps = {}
531 for m in (d.getVar('SSTATE_HASHEQUIV_FILEMAP') or '').split():
532 entry = m.split(":")
533 if len(entry) != 3 or entry[0] != task:
534 continue
535 filemaps.setdefault(entry[1], [])
536 filemaps[entry[1]].append(entry[2])
537
Brad Bishop19323692019-04-05 15:28:33 -0400538 try:
539 os.chdir(path)
Patrick Williams93c203f2021-10-06 16:15:23 -0500540 basepath = os.path.normpath(path)
Brad Bishop19323692019-04-05 15:28:33 -0400541
542 update_hash("OEOuthashBasic\n")
Andrew Geissler595f6302022-01-24 19:11:47 +0000543 if hash_version:
544 update_hash(hash_version + "\n")
545
546 if extra_sigdata:
547 update_hash(extra_sigdata + "\n")
Brad Bishop19323692019-04-05 15:28:33 -0400548
549 # It is only currently useful to get equivalent hashes for things that
550 # can be restored from sstate. Since the sstate object is named using
551 # SSTATE_PKGSPEC and the task name, those should be included in the
552 # output hash calculation.
553 update_hash("SSTATE_PKGSPEC=%s\n" % d.getVar('SSTATE_PKGSPEC'))
554 update_hash("task=%s\n" % task)
555
556 for root, dirs, files in os.walk('.', topdown=True):
557 # Sort directories to ensure consistent ordering when recursing
558 dirs.sort()
559 files.sort()
560
561 def process(path):
562 s = os.lstat(path)
563
564 if stat.S_ISDIR(s.st_mode):
565 update_hash('d')
566 elif stat.S_ISCHR(s.st_mode):
567 update_hash('c')
568 elif stat.S_ISBLK(s.st_mode):
569 update_hash('b')
570 elif stat.S_ISSOCK(s.st_mode):
571 update_hash('s')
572 elif stat.S_ISLNK(s.st_mode):
573 update_hash('l')
574 elif stat.S_ISFIFO(s.st_mode):
575 update_hash('p')
576 else:
577 update_hash('-')
578
579 def add_perm(mask, on, off='-'):
580 if mask & s.st_mode:
581 update_hash(on)
582 else:
583 update_hash(off)
584
585 add_perm(stat.S_IRUSR, 'r')
586 add_perm(stat.S_IWUSR, 'w')
587 if stat.S_ISUID & s.st_mode:
588 add_perm(stat.S_IXUSR, 's', 'S')
589 else:
590 add_perm(stat.S_IXUSR, 'x')
591
Brad Bishop19323692019-04-05 15:28:33 -0400592 if include_owners:
Andrew Geisslereff27472021-10-29 15:35:00 -0500593 # Group/other permissions are only relevant in pseudo context
594 add_perm(stat.S_IRGRP, 'r')
595 add_perm(stat.S_IWGRP, 'w')
596 if stat.S_ISGID & s.st_mode:
597 add_perm(stat.S_IXGRP, 's', 'S')
598 else:
599 add_perm(stat.S_IXGRP, 'x')
600
601 add_perm(stat.S_IROTH, 'r')
602 add_perm(stat.S_IWOTH, 'w')
603 if stat.S_ISVTX & s.st_mode:
604 update_hash('t')
605 else:
606 add_perm(stat.S_IXOTH, 'x')
607
Andrew Geissler82c905d2020-04-13 13:39:40 -0500608 try:
609 update_hash(" %10s" % pwd.getpwuid(s.st_uid).pw_name)
610 update_hash(" %10s" % grp.getgrgid(s.st_gid).gr_name)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600611 except KeyError as e:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600612 msg = ("KeyError: %s\nPath %s is owned by uid %d, gid %d, which doesn't match "
Patrick Williamsac13d5f2023-11-24 18:59:46 -0600613 "any user/group on target. This may be due to host contamination." %
614 (e, os.path.abspath(path), s.st_uid, s.st_gid))
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600615 raise Exception(msg).with_traceback(e.__traceback__)
Brad Bishop19323692019-04-05 15:28:33 -0400616
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600617 if include_timestamps:
618 update_hash(" %10d" % s.st_mtime)
619
Brad Bishop19323692019-04-05 15:28:33 -0400620 update_hash(" ")
621 if stat.S_ISBLK(s.st_mode) or stat.S_ISCHR(s.st_mode):
622 update_hash("%9s" % ("%d.%d" % (os.major(s.st_rdev), os.minor(s.st_rdev))))
623 else:
624 update_hash(" " * 9)
625
Patrick Williams93c203f2021-10-06 16:15:23 -0500626 filterfile = False
627 for entry in filemaps:
628 if fnmatch.fnmatch(path, entry):
629 filterfile = True
630
Brad Bishop19323692019-04-05 15:28:33 -0400631 update_hash(" ")
Patrick Williams93c203f2021-10-06 16:15:23 -0500632 if stat.S_ISREG(s.st_mode) and not filterfile:
Brad Bishop19323692019-04-05 15:28:33 -0400633 update_hash("%10d" % s.st_size)
634 else:
635 update_hash(" " * 10)
636
637 update_hash(" ")
638 fh = hashlib.sha256()
639 if stat.S_ISREG(s.st_mode):
640 # Hash file contents
Patrick Williams93c203f2021-10-06 16:15:23 -0500641 if filterfile:
642 # Need to ignore paths in crossscripts and postinst-useradd files.
643 with open(path, 'rb') as d:
644 chunk = d.read()
645 chunk = chunk.replace(bytes(basepath, encoding='utf8'), b'')
646 for entry in filemaps:
647 if not fnmatch.fnmatch(path, entry):
648 continue
649 for r in filemaps[entry]:
650 if r.startswith("regex-"):
651 chunk = re.sub(bytes(r[6:], encoding='utf8'), b'', chunk)
652 else:
653 chunk = chunk.replace(bytes(r, encoding='utf8'), b'')
Brad Bishop19323692019-04-05 15:28:33 -0400654 fh.update(chunk)
Patrick Williams93c203f2021-10-06 16:15:23 -0500655 else:
656 with open(path, 'rb') as d:
657 for chunk in iter(lambda: d.read(4096), b""):
658 fh.update(chunk)
Brad Bishop19323692019-04-05 15:28:33 -0400659 update_hash(fh.hexdigest())
660 else:
661 update_hash(" " * len(fh.hexdigest()))
662
663 update_hash(" %s" % path)
664
665 if stat.S_ISLNK(s.st_mode):
666 update_hash(" -> %s" % os.readlink(path))
667
668 update_hash("\n")
669
670 # Process this directory and all its child files
Andrew Geissler5199d832021-09-24 16:47:35 -0500671 if include_root or root != ".":
672 process(root)
Brad Bishop19323692019-04-05 15:28:33 -0400673 for f in files:
674 if f == 'fixmepath':
675 continue
676 process(os.path.join(root, f))
Andrew Geissler6aa7eec2023-03-03 12:41:14 -0600677
678 for dir in dirs:
679 if os.path.islink(os.path.join(root, dir)):
680 process(os.path.join(root, dir))
Brad Bishop19323692019-04-05 15:28:33 -0400681 finally:
682 os.chdir(prev_dir)
683
684 return h.hexdigest()
685
Brad Bishop316dfdd2018-06-25 12:45:53 -0400686