blob: 633a0fd450249bcfee3f5de3fcfa29fdafa5db94 [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 Williamsc124f4f2015-09-15 14:41:29 -05009
Andrew Geisslerd25ed322020-06-27 00:28:28 -050010def sstate_rundepfilter(siggen, fn, recipename, task, dep, depname, dataCaches):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050011 # Return True if we should keep the dependency, False to drop it
12 def isNative(x):
13 return x.endswith("-native")
14 def isCross(x):
15 return "-cross-" in x
16 def isNativeSDK(x):
17 return x.startswith("nativesdk-")
Andrew Geisslerd25ed322020-06-27 00:28:28 -050018 def isKernel(mc, fn):
19 inherits = " ".join(dataCaches[mc].inherits[fn])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020 return inherits.find("/module-base.bbclass") != -1 or inherits.find("/linux-kernel-base.bbclass") != -1
Andrew Geisslerd25ed322020-06-27 00:28:28 -050021 def isPackageGroup(mc, fn):
22 inherits = " ".join(dataCaches[mc].inherits[fn])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050023 return "/packagegroup.bbclass" in inherits
Andrew Geisslerd25ed322020-06-27 00:28:28 -050024 def isAllArch(mc, fn):
25 inherits = " ".join(dataCaches[mc].inherits[fn])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050026 return "/allarch.bbclass" in inherits
Andrew Geisslerd25ed322020-06-27 00:28:28 -050027 def isImage(mc, fn):
28 return "/image.bbclass" in " ".join(dataCaches[mc].inherits[fn])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029
Andrew Geisslerd25ed322020-06-27 00:28:28 -050030 depmc, _, deptaskname, depmcfn = bb.runqueue.split_tid_mcfn(dep)
31 mc, _ = bb.runqueue.split_mc(fn)
32
Patrick Williams7784c422022-11-17 07:29:11 -060033 # We can skip the rm_work task signature to avoid running the task
34 # when we remove some tasks from the dependencie chain
35 # i.e INHERIT:remove = "create-spdx" will trigger the do_rm_work
36 if task == "do_rm_work":
37 return False
38
Andrew Geisslerd25ed322020-06-27 00:28:28 -050039 # (Almost) always include our own inter-task dependencies (unless it comes
40 # from a mcdepends). The exception is the special
41 # do_kernel_configme->do_unpack_and_patch dependency from archiver.bbclass.
42 if recipename == depname and depmc == mc:
43 if task == "do_kernel_configme" and deptaskname == "do_unpack_and_patch":
Brad Bishop6e60e8b2018-02-01 10:27:11 -050044 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050045 return True
46
Patrick Williamsc124f4f2015-09-15 14:41:29 -050047 # Exclude well defined recipe->dependency
48 if "%s->%s" % (recipename, depname) in siggen.saferecipedeps:
49 return False
50
Brad Bishop316dfdd2018-06-25 12:45:53 -040051 # Check for special wildcard
52 if "*->%s" % depname in siggen.saferecipedeps and recipename != depname:
53 return False
54
Patrick Williamsc124f4f2015-09-15 14:41:29 -050055 # Don't change native/cross/nativesdk recipe dependencies any further
56 if isNative(recipename) or isCross(recipename) or isNativeSDK(recipename):
57 return True
58
59 # Only target packages beyond here
60
61 # allarch packagegroups are assumed to have well behaved names which don't change between architecures/tunes
Andrew Geisslerd25ed322020-06-27 00:28:28 -050062 if isPackageGroup(mc, fn) and isAllArch(mc, fn) and not isNative(depname):
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080063 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -050064
65 # Exclude well defined machine specific configurations which don't change ABI
Andrew Geisslerd25ed322020-06-27 00:28:28 -050066 if depname in siggen.abisaferecipes and not isImage(mc, fn):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050067 return False
68
69 # Kernel modules are well namespaced. We don't want to depend on the kernel's checksum
Patrick Williams213cb262021-08-07 19:21:33 -050070 # if we're just doing an RRECOMMENDS:xxx = "kernel-module-*", not least because the checksum
Patrick Williamsc124f4f2015-09-15 14:41:29 -050071 # is machine specific.
72 # Therefore if we're not a kernel or a module recipe (inheriting the kernel classes)
73 # and we reccomend a kernel-module, we exclude the dependency.
Andrew Geisslerd25ed322020-06-27 00:28:28 -050074 if dataCaches and isKernel(depmc, depmcfn) and not isKernel(mc, fn):
75 for pkg in dataCaches[mc].runrecs[fn]:
76 if " ".join(dataCaches[mc].runrecs[fn][pkg]).find("kernel-module-") != -1:
Patrick Williamsc124f4f2015-09-15 14:41:29 -050077 return False
78
79 # Default to keep dependencies
80 return True
81
82def sstate_lockedsigs(d):
83 sigs = {}
Brad Bishop6e60e8b2018-02-01 10:27:11 -050084 types = (d.getVar("SIGGEN_LOCKEDSIGS_TYPES") or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050085 for t in types:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050086 siggen_lockedsigs_var = "SIGGEN_LOCKEDSIGS_%s" % t
Brad Bishop6e60e8b2018-02-01 10:27:11 -050087 lockedsigs = (d.getVar(siggen_lockedsigs_var) or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -050088 for ls in lockedsigs:
89 pn, task, h = ls.split(":", 2)
90 if pn not in sigs:
91 sigs[pn] = {}
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050092 sigs[pn][task] = [h, siggen_lockedsigs_var]
Patrick Williamsc124f4f2015-09-15 14:41:29 -050093 return sigs
94
Brad Bishop00e122a2019-10-05 11:10:57 -040095class SignatureGeneratorOEBasicHashMixIn(object):
Andrew Geisslerd25ed322020-06-27 00:28:28 -050096 supports_multiconfig_datacaches = True
97
Patrick Williamsc124f4f2015-09-15 14:41:29 -050098 def init_rundepcheck(self, data):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050099 self.abisaferecipes = (data.getVar("SIGGEN_EXCLUDERECIPES_ABISAFE") or "").split()
100 self.saferecipedeps = (data.getVar("SIGGEN_EXCLUDE_SAFE_RECIPE_DEPS") or "").split()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500101 self.lockedsigs = sstate_lockedsigs(data)
102 self.lockedhashes = {}
103 self.lockedpnmap = {}
104 self.lockedhashfn = {}
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500105 self.machine = data.getVar("MACHINE")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500106 self.mismatch_msgs = []
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500107 self.unlockedrecipes = (data.getVar("SIGGEN_UNLOCKED_RECIPES") or
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500108 "").split()
109 self.unlockedrecipes = { k: "" for k in self.unlockedrecipes }
Andrew Geissler82c905d2020-04-13 13:39:40 -0500110 self._internal = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500111 pass
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500112
113 def tasks_resolved(self, virtmap, virtpnmap, dataCache):
114 # Translate virtual/xxx entries to PN values
115 newabisafe = []
116 for a in self.abisaferecipes:
117 if a in virtpnmap:
118 newabisafe.append(virtpnmap[a])
119 else:
120 newabisafe.append(a)
121 self.abisaferecipes = newabisafe
122 newsafedeps = []
123 for a in self.saferecipedeps:
124 a1, a2 = a.split("->")
125 if a1 in virtpnmap:
126 a1 = virtpnmap[a1]
127 if a2 in virtpnmap:
128 a2 = virtpnmap[a2]
129 newsafedeps.append(a1 + "->" + a2)
130 self.saferecipedeps = newsafedeps
131
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500132 def rundep_check(self, fn, recipename, task, dep, depname, dataCaches = None):
133 return sstate_rundepfilter(self, fn, recipename, task, dep, depname, dataCaches)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500134
135 def get_taskdata(self):
Brad Bishop00e122a2019-10-05 11:10:57 -0400136 return (self.lockedpnmap, self.lockedhashfn, self.lockedhashes) + super().get_taskdata()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500137
138 def set_taskdata(self, data):
Brad Bishop00e122a2019-10-05 11:10:57 -0400139 self.lockedpnmap, self.lockedhashfn, self.lockedhashes = data[:3]
140 super().set_taskdata(data[3:])
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500141
142 def dump_sigs(self, dataCache, options):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600143 sigfile = os.getcwd() + "/locked-sigs.inc"
144 bb.plain("Writing locked sigs to %s" % sigfile)
145 self.dump_lockedsigs(sigfile)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500146 return super(bb.siggen.SignatureGeneratorBasicHash, self).dump_sigs(dataCache, options)
147
Andrew Geissler82c905d2020-04-13 13:39:40 -0500148
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500149 def get_taskhash(self, tid, deps, dataCaches):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500150 if tid in self.lockedhashes:
151 if self.lockedhashes[tid]:
152 return self.lockedhashes[tid]
153 else:
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500154 return super().get_taskhash(tid, deps, dataCaches)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500155
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500156 h = super().get_taskhash(tid, deps, dataCaches)
Brad Bishop08902b02019-08-20 09:16:51 -0400157
158 (mc, _, task, fn) = bb.runqueue.split_tid_mcfn(tid)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500159
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500160 recipename = dataCaches[mc].pkg_fn[fn]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500161 self.lockedpnmap[fn] = recipename
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500162 self.lockedhashfn[fn] = dataCaches[mc].hashfn[fn]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500163
164 unlocked = False
165 if recipename in self.unlockedrecipes:
166 unlocked = True
167 else:
168 def recipename_from_dep(dep):
Andrew Geisslerd25ed322020-06-27 00:28:28 -0500169 (depmc, _, _, depfn) = bb.runqueue.split_tid_mcfn(dep)
170 return dataCaches[depmc].pkg_fn[depfn]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500171
172 # If any unlocked recipe is in the direct dependencies then the
173 # current recipe should be unlocked as well.
Brad Bishop08902b02019-08-20 09:16:51 -0400174 depnames = [ recipename_from_dep(x) for x in deps if mc == bb.runqueue.mc_from_tid(x)]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500175 if any(x in y for y in depnames for x in self.unlockedrecipes):
176 self.unlockedrecipes[recipename] = ''
177 unlocked = True
178
179 if not unlocked and recipename in self.lockedsigs:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500180 if task in self.lockedsigs[recipename]:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500181 h_locked = self.lockedsigs[recipename][task][0]
182 var = self.lockedsigs[recipename][task][1]
Brad Bishop08902b02019-08-20 09:16:51 -0400183 self.lockedhashes[tid] = h_locked
Andrew Geissler82c905d2020-04-13 13:39:40 -0500184 self._internal = True
185 unihash = self.get_unihash(tid)
186 self._internal = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500187 #bb.warn("Using %s %s %s" % (recipename, task, h))
188
Brad Bishop00e122a2019-10-05 11:10:57 -0400189 if h != h_locked and h_locked != unihash:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500190 self.mismatch_msgs.append('The %s:%s sig is computed to be %s, but the sig is locked to %s in %s'
191 % (recipename, task, h, h_locked, var))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500192
193 return h_locked
Andrew Geissler82c905d2020-04-13 13:39:40 -0500194
195 self.lockedhashes[tid] = False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500196 #bb.warn("%s %s %s" % (recipename, task, h))
197 return h
198
Andrew Geissler82c905d2020-04-13 13:39:40 -0500199 def get_stampfile_hash(self, tid):
200 if tid in self.lockedhashes and self.lockedhashes[tid]:
201 return self.lockedhashes[tid]
202 return super().get_stampfile_hash(tid)
203
Brad Bishop00e122a2019-10-05 11:10:57 -0400204 def get_unihash(self, tid):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500205 if tid in self.lockedhashes and self.lockedhashes[tid] and not self._internal:
Brad Bishop00e122a2019-10-05 11:10:57 -0400206 return self.lockedhashes[tid]
207 return super().get_unihash(tid)
208
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500209 def dump_sigtask(self, fn, task, stampbase, runtime):
Brad Bishop08902b02019-08-20 09:16:51 -0400210 tid = fn + ":" + task
Andrew Geissler82c905d2020-04-13 13:39:40 -0500211 if tid in self.lockedhashes and self.lockedhashes[tid]:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500212 return
213 super(bb.siggen.SignatureGeneratorBasicHash, self).dump_sigtask(fn, task, stampbase, runtime)
214
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600215 def dump_lockedsigs(self, sigfile, taskfilter=None):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500216 types = {}
Brad Bishop08902b02019-08-20 09:16:51 -0400217 for tid in self.runtaskdeps:
Patrick Williams2a254922023-08-11 09:48:11 -0500218 # Bitbake changed this to a tuple in newer versions
219 if isinstance(tid, tuple):
220 tid = tid[1]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500221 if taskfilter:
Brad Bishop08902b02019-08-20 09:16:51 -0400222 if not tid in taskfilter:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500223 continue
Brad Bishop08902b02019-08-20 09:16:51 -0400224 fn = bb.runqueue.fn_from_tid(tid)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500225 t = self.lockedhashfn[fn].split(" ")[1].split(":")[5]
226 t = 't-' + t.replace('_', '-')
227 if t not in types:
228 types[t] = []
Brad Bishop08902b02019-08-20 09:16:51 -0400229 types[t].append(tid)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500230
231 with open(sigfile, "w") as f:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500232 l = sorted(types)
233 for t in l:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500234 f.write('SIGGEN_LOCKEDSIGS_%s = "\\\n' % t)
235 types[t].sort()
Brad Bishop08902b02019-08-20 09:16:51 -0400236 sortedtid = sorted(types[t], key=lambda tid: self.lockedpnmap[bb.runqueue.fn_from_tid(tid)])
237 for tid in sortedtid:
238 (_, _, task, fn) = bb.runqueue.split_tid_mcfn(tid)
239 if tid not in self.taskhash:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500240 continue
Brad Bishop00e122a2019-10-05 11:10:57 -0400241 f.write(" " + self.lockedpnmap[fn] + ":" + task + ":" + self.get_unihash(tid) + " \\\n")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500242 f.write(' "\n')
Patrick Williams213cb262021-08-07 19:21:33 -0500243 f.write('SIGGEN_LOCKEDSIGS_TYPES:%s = "%s"' % (self.machine, " ".join(l)))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500244
Andrew Geissler09036742021-06-25 14:25:14 -0500245 def dump_siglist(self, sigfile, path_prefix_strip=None):
246 def strip_fn(fn):
247 nonlocal path_prefix_strip
248 if not path_prefix_strip:
249 return fn
250
251 fn_exp = fn.split(":")
252 if fn_exp[-1].startswith(path_prefix_strip):
253 fn_exp[-1] = fn_exp[-1][len(path_prefix_strip):]
254
255 return ":".join(fn_exp)
256
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500257 with open(sigfile, "w") as f:
258 tasks = []
259 for taskitem in self.taskhash:
Brad Bishop08902b02019-08-20 09:16:51 -0400260 (fn, task) = taskitem.rsplit(":", 1)
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500261 pn = self.lockedpnmap[fn]
Andrew Geissler09036742021-06-25 14:25:14 -0500262 tasks.append((pn, task, strip_fn(fn), self.taskhash[taskitem]))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500263 for (pn, task, fn, taskhash) in sorted(tasks):
Brad Bishop08902b02019-08-20 09:16:51 -0400264 f.write('%s:%s %s %s\n' % (pn, task, fn, taskhash))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500265
Brad Bishop08902b02019-08-20 09:16:51 -0400266 def checkhashes(self, sq_data, missed, found, d):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500267 warn_msgs = []
268 error_msgs = []
269 sstate_missing_msgs = []
270
Brad Bishop08902b02019-08-20 09:16:51 -0400271 for tid in sq_data['hash']:
272 if tid not in found:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500273 for pn in self.lockedsigs:
Brad Bishop08902b02019-08-20 09:16:51 -0400274 taskname = bb.runqueue.taskname_from_tid(tid)
275 if sq_data['hash'][tid] in iter(self.lockedsigs[pn].values()):
276 if taskname == 'do_shared_workdir':
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500277 continue
278 sstate_missing_msgs.append("Locked sig is set for %s:%s (%s) yet not in sstate cache?"
Brad Bishop08902b02019-08-20 09:16:51 -0400279 % (pn, taskname, sq_data['hash'][tid]))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500280
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500281 checklevel = d.getVar("SIGGEN_LOCKEDSIGS_TASKSIG_CHECK")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500282 if checklevel == 'warn':
283 warn_msgs += self.mismatch_msgs
284 elif checklevel == 'error':
285 error_msgs += self.mismatch_msgs
286
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500287 checklevel = d.getVar("SIGGEN_LOCKEDSIGS_SSTATE_EXISTS_CHECK")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500288 if checklevel == 'warn':
289 warn_msgs += sstate_missing_msgs
290 elif checklevel == 'error':
291 error_msgs += sstate_missing_msgs
292
293 if warn_msgs:
294 bb.warn("\n".join(warn_msgs))
295 if error_msgs:
296 bb.fatal("\n".join(error_msgs))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500297
Brad Bishop00e122a2019-10-05 11:10:57 -0400298class SignatureGeneratorOEBasicHash(SignatureGeneratorOEBasicHashMixIn, bb.siggen.SignatureGeneratorBasicHash):
299 name = "OEBasicHash"
300
301class SignatureGeneratorOEEquivHash(SignatureGeneratorOEBasicHashMixIn, bb.siggen.SignatureGeneratorUniHashMixIn, bb.siggen.SignatureGeneratorBasicHash):
Brad Bishop19323692019-04-05 15:28:33 -0400302 name = "OEEquivHash"
303
304 def init_rundepcheck(self, data):
305 super().init_rundepcheck(data)
Brad Bishopa34c0302019-09-23 22:34:48 -0400306 self.server = data.getVar('BB_HASHSERVE')
Brad Bishop08902b02019-08-20 09:16:51 -0400307 if not self.server:
Brad Bishopa34c0302019-09-23 22:34:48 -0400308 bb.fatal("OEEquivHash requires BB_HASHSERVE to be set")
Brad Bishop19323692019-04-05 15:28:33 -0400309 self.method = data.getVar('SSTATE_HASHEQUIV_METHOD')
Brad Bishop08902b02019-08-20 09:16:51 -0400310 if not self.method:
311 bb.fatal("OEEquivHash requires SSTATE_HASHEQUIV_METHOD to be set")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500312
313# Insert these classes into siggen's namespace so it can see and select them
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500314bb.siggen.SignatureGeneratorOEBasicHash = SignatureGeneratorOEBasicHash
Brad Bishop19323692019-04-05 15:28:33 -0400315bb.siggen.SignatureGeneratorOEEquivHash = SignatureGeneratorOEEquivHash
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500316
317
318def find_siginfo(pn, taskname, taskhashlist, d):
319 """ Find signature data files for comparison purposes """
320
321 import fnmatch
322 import glob
323
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500324 if not taskname:
325 # We have to derive pn and taskname
326 key = pn
Patrick Williams2a254922023-08-11 09:48:11 -0500327 if key.startswith("mc:"):
328 # mc:<mc>:<pn>:<task>
329 _, _, pn, taskname = key.split(':', 3)
330 else:
331 # <pn>:<task>
332 pn, taskname = key.split(':', 1)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500333
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500334 hashfiles = {}
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500335 filedates = {}
336
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500337 def get_hashval(siginfo):
338 if siginfo.endswith('.siginfo'):
339 return siginfo.rpartition(':')[2].partition('_')[0]
340 else:
341 return siginfo.rpartition('.')[2]
342
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500343 # First search in stamps dir
344 localdata = d.createCopy()
345 localdata.setVar('MULTIMACH_TARGET_SYS', '*')
346 localdata.setVar('PN', pn)
347 localdata.setVar('PV', '*')
348 localdata.setVar('PR', '*')
349 localdata.setVar('EXTENDPE', '')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500350 stamp = localdata.getVar('STAMP')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500351 if pn.startswith("gcc-source"):
352 # gcc-source shared workdir is a special case :(
353 stamp = localdata.expand("${STAMPS_DIR}/work-shared/gcc-${PV}-${PR}")
354
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500355 filespec = '%s.%s.sigdata.*' % (stamp, taskname)
356 foundall = False
357 import glob
358 for fullpath in glob.glob(filespec):
359 match = False
360 if taskhashlist:
361 for taskhash in taskhashlist:
362 if fullpath.endswith('.%s' % taskhash):
363 hashfiles[taskhash] = fullpath
364 if len(hashfiles) == len(taskhashlist):
365 foundall = True
366 break
367 else:
368 try:
369 filedates[fullpath] = os.stat(fullpath).st_mtime
370 except OSError:
371 continue
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500372 hashval = get_hashval(fullpath)
373 hashfiles[hashval] = fullpath
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500374
375 if not taskhashlist or (len(filedates) < 2 and not foundall):
376 # That didn't work, look in sstate-cache
Brad Bishop19323692019-04-05 15:28:33 -0400377 hashes = taskhashlist or ['?' * 64]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500378 localdata = bb.data.createCopy(d)
379 for hashval in hashes:
380 localdata.setVar('PACKAGE_ARCH', '*')
381 localdata.setVar('TARGET_VENDOR', '*')
382 localdata.setVar('TARGET_OS', '*')
383 localdata.setVar('PN', pn)
384 localdata.setVar('PV', '*')
385 localdata.setVar('PR', '*')
386 localdata.setVar('BB_TASKHASH', hashval)
Patrick Williams03907ee2022-05-01 06:28:52 -0500387 localdata.setVar('SSTATE_CURRTASK', taskname[3:])
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500388 swspec = localdata.getVar('SSTATE_SWSPEC')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500389 if taskname in ['do_fetch', 'do_unpack', 'do_patch', 'do_populate_lic', 'do_preconfigure'] and swspec:
390 localdata.setVar('SSTATE_PKGSPEC', '${SSTATE_SWSPEC}')
391 elif pn.endswith('-native') or "-cross-" in pn or "-crosssdk-" in pn:
392 localdata.setVar('SSTATE_EXTRAPATH', "${NATIVELSBSTRING}/")
Patrick Williams03907ee2022-05-01 06:28:52 -0500393 filespec = '%s.siginfo' % localdata.getVar('SSTATE_PKG')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500394
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500395 matchedfiles = glob.glob(filespec)
396 for fullpath in matchedfiles:
397 actual_hashval = get_hashval(fullpath)
398 if actual_hashval in hashfiles:
399 continue
400 hashfiles[hashval] = fullpath
401 if not taskhashlist:
402 try:
403 filedates[fullpath] = os.stat(fullpath).st_mtime
404 except:
405 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500406
407 if taskhashlist:
408 return hashfiles
409 else:
410 return filedates
411
412bb.siggen.find_siginfo = find_siginfo
413
414
415def sstate_get_manifest_filename(task, d):
416 """
417 Return the sstate manifest file path for a particular task.
418 Also returns the datastore that can be used to query related variables.
419 """
420 d2 = d.createCopy()
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500421 extrainf = d.getVarFlag("do_" + task, 'stamp-extra-info')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500422 if extrainf:
423 d2.setVar("SSTATE_MANMACH", extrainf)
424 return (d2.expand("${SSTATE_MANFILEPREFIX}.%s" % task), d2)
Brad Bishop316dfdd2018-06-25 12:45:53 -0400425
426def find_sstate_manifest(taskdata, taskdata2, taskname, d, multilibcache):
427 d2 = d
428 variant = ''
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800429 curr_variant = ''
430 if d.getVar("BBEXTENDCURR") == "multilib":
431 curr_variant = d.getVar("BBEXTENDVARIANT")
432 if "virtclass-multilib" not in d.getVar("OVERRIDES"):
433 curr_variant = "invalid"
Brad Bishop316dfdd2018-06-25 12:45:53 -0400434 if taskdata2.startswith("virtual:multilib"):
435 variant = taskdata2.split(":")[2]
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800436 if curr_variant != variant:
Brad Bishop316dfdd2018-06-25 12:45:53 -0400437 if variant not in multilibcache:
438 multilibcache[variant] = oe.utils.get_multilib_datastore(variant, d)
439 d2 = multilibcache[variant]
440
441 if taskdata.endswith("-native"):
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600442 pkgarchs = ["${BUILD_ARCH}", "${BUILD_ARCH}_${ORIGNATIVELSBSTRING}"]
Brad Bishop316dfdd2018-06-25 12:45:53 -0400443 elif taskdata.startswith("nativesdk-"):
444 pkgarchs = ["${SDK_ARCH}_${SDK_OS}", "allarch"]
445 elif "-cross-canadian" in taskdata:
446 pkgarchs = ["${SDK_ARCH}_${SDK_ARCH}-${SDKPKGSUFFIX}"]
447 elif "-cross-" in taskdata:
Andrew Geissler9aee5002022-03-30 16:27:02 +0000448 pkgarchs = ["${BUILD_ARCH}"]
Brad Bishop316dfdd2018-06-25 12:45:53 -0400449 elif "-crosssdk" in taskdata:
450 pkgarchs = ["${BUILD_ARCH}_${SDK_ARCH}_${SDK_OS}"]
451 else:
452 pkgarchs = ['${MACHINE_ARCH}']
453 pkgarchs = pkgarchs + list(reversed(d2.getVar("PACKAGE_EXTRA_ARCHS").split()))
454 pkgarchs.append('allarch')
455 pkgarchs.append('${SDK_ARCH}_${SDK_ARCH}-${SDKPKGSUFFIX}')
456
Andrew Geissler517393d2023-01-13 08:55:19 -0600457 searched_manifests = []
458
Brad Bishop316dfdd2018-06-25 12:45:53 -0400459 for pkgarch in pkgarchs:
460 manifest = d2.expand("${SSTATE_MANIFESTS}/manifest-%s-%s.%s" % (pkgarch, taskdata, taskname))
461 if os.path.exists(manifest):
462 return manifest, d2
Andrew Geissler517393d2023-01-13 08:55:19 -0600463 searched_manifests.append(manifest)
464 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"
465 % (taskdata, taskname, variant, d2.expand(", ".join(pkgarchs)),"\n ".join(searched_manifests)))
Brad Bishop316dfdd2018-06-25 12:45:53 -0400466 return None, d2
467
Brad Bishop19323692019-04-05 15:28:33 -0400468def OEOuthashBasic(path, sigfile, task, d):
469 """
470 Basic output hash function
471
472 Calculates the output hash of a task by hashing all output file metadata,
473 and file contents.
474 """
475 import hashlib
476 import stat
477 import pwd
478 import grp
Patrick Williams93c203f2021-10-06 16:15:23 -0500479 import re
480 import fnmatch
Brad Bishop19323692019-04-05 15:28:33 -0400481
482 def update_hash(s):
483 s = s.encode('utf-8')
484 h.update(s)
485 if sigfile:
486 sigfile.write(s)
487
488 h = hashlib.sha256()
489 prev_dir = os.getcwd()
Patrick Williams93c203f2021-10-06 16:15:23 -0500490 corebase = d.getVar("COREBASE")
491 tmpdir = d.getVar("TMPDIR")
Brad Bishop19323692019-04-05 15:28:33 -0400492 include_owners = os.environ.get('PSEUDO_DISABLED') == '0'
Andrew Geisslerf0343792020-11-18 10:42:21 -0600493 if "package_write_" in task or task == "package_qa":
494 include_owners = False
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600495 include_timestamps = False
Andrew Geissler5199d832021-09-24 16:47:35 -0500496 include_root = True
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600497 if task == "package":
Andrew Geisslereff27472021-10-29 15:35:00 -0500498 include_timestamps = True
Andrew Geissler5199d832021-09-24 16:47:35 -0500499 include_root = False
Andrew Geissler595f6302022-01-24 19:11:47 +0000500 hash_version = d.getVar('HASHEQUIV_HASH_VERSION')
501 extra_sigdata = d.getVar("HASHEQUIV_EXTRA_SIGDATA")
Brad Bishop19323692019-04-05 15:28:33 -0400502
Patrick Williams93c203f2021-10-06 16:15:23 -0500503 filemaps = {}
504 for m in (d.getVar('SSTATE_HASHEQUIV_FILEMAP') or '').split():
505 entry = m.split(":")
506 if len(entry) != 3 or entry[0] != task:
507 continue
508 filemaps.setdefault(entry[1], [])
509 filemaps[entry[1]].append(entry[2])
510
Brad Bishop19323692019-04-05 15:28:33 -0400511 try:
512 os.chdir(path)
Patrick Williams93c203f2021-10-06 16:15:23 -0500513 basepath = os.path.normpath(path)
Brad Bishop19323692019-04-05 15:28:33 -0400514
515 update_hash("OEOuthashBasic\n")
Andrew Geissler595f6302022-01-24 19:11:47 +0000516 if hash_version:
517 update_hash(hash_version + "\n")
518
519 if extra_sigdata:
520 update_hash(extra_sigdata + "\n")
Brad Bishop19323692019-04-05 15:28:33 -0400521
522 # It is only currently useful to get equivalent hashes for things that
523 # can be restored from sstate. Since the sstate object is named using
524 # SSTATE_PKGSPEC and the task name, those should be included in the
525 # output hash calculation.
526 update_hash("SSTATE_PKGSPEC=%s\n" % d.getVar('SSTATE_PKGSPEC'))
527 update_hash("task=%s\n" % task)
528
529 for root, dirs, files in os.walk('.', topdown=True):
530 # Sort directories to ensure consistent ordering when recursing
531 dirs.sort()
532 files.sort()
533
534 def process(path):
535 s = os.lstat(path)
536
537 if stat.S_ISDIR(s.st_mode):
538 update_hash('d')
539 elif stat.S_ISCHR(s.st_mode):
540 update_hash('c')
541 elif stat.S_ISBLK(s.st_mode):
542 update_hash('b')
543 elif stat.S_ISSOCK(s.st_mode):
544 update_hash('s')
545 elif stat.S_ISLNK(s.st_mode):
546 update_hash('l')
547 elif stat.S_ISFIFO(s.st_mode):
548 update_hash('p')
549 else:
550 update_hash('-')
551
552 def add_perm(mask, on, off='-'):
553 if mask & s.st_mode:
554 update_hash(on)
555 else:
556 update_hash(off)
557
558 add_perm(stat.S_IRUSR, 'r')
559 add_perm(stat.S_IWUSR, 'w')
560 if stat.S_ISUID & s.st_mode:
561 add_perm(stat.S_IXUSR, 's', 'S')
562 else:
563 add_perm(stat.S_IXUSR, 'x')
564
Brad Bishop19323692019-04-05 15:28:33 -0400565 if include_owners:
Andrew Geisslereff27472021-10-29 15:35:00 -0500566 # Group/other permissions are only relevant in pseudo context
567 add_perm(stat.S_IRGRP, 'r')
568 add_perm(stat.S_IWGRP, 'w')
569 if stat.S_ISGID & s.st_mode:
570 add_perm(stat.S_IXGRP, 's', 'S')
571 else:
572 add_perm(stat.S_IXGRP, 'x')
573
574 add_perm(stat.S_IROTH, 'r')
575 add_perm(stat.S_IWOTH, 'w')
576 if stat.S_ISVTX & s.st_mode:
577 update_hash('t')
578 else:
579 add_perm(stat.S_IXOTH, 'x')
580
Andrew Geissler82c905d2020-04-13 13:39:40 -0500581 try:
582 update_hash(" %10s" % pwd.getpwuid(s.st_uid).pw_name)
583 update_hash(" %10s" % grp.getgrgid(s.st_gid).gr_name)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600584 except KeyError as e:
Andrew Geissler82c905d2020-04-13 13:39:40 -0500585 bb.warn("KeyError in %s" % path)
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600586 msg = ("KeyError: %s\nPath %s is owned by uid %d, gid %d, which doesn't match "
587 "any user/group on target. This may be due to host contamination." % (e, path, s.st_uid, s.st_gid))
588 raise Exception(msg).with_traceback(e.__traceback__)
Brad Bishop19323692019-04-05 15:28:33 -0400589
Andrew Geissler6ce62a22020-11-30 19:58:47 -0600590 if include_timestamps:
591 update_hash(" %10d" % s.st_mtime)
592
Brad Bishop19323692019-04-05 15:28:33 -0400593 update_hash(" ")
594 if stat.S_ISBLK(s.st_mode) or stat.S_ISCHR(s.st_mode):
595 update_hash("%9s" % ("%d.%d" % (os.major(s.st_rdev), os.minor(s.st_rdev))))
596 else:
597 update_hash(" " * 9)
598
Patrick Williams93c203f2021-10-06 16:15:23 -0500599 filterfile = False
600 for entry in filemaps:
601 if fnmatch.fnmatch(path, entry):
602 filterfile = True
603
Brad Bishop19323692019-04-05 15:28:33 -0400604 update_hash(" ")
Patrick Williams93c203f2021-10-06 16:15:23 -0500605 if stat.S_ISREG(s.st_mode) and not filterfile:
Brad Bishop19323692019-04-05 15:28:33 -0400606 update_hash("%10d" % s.st_size)
607 else:
608 update_hash(" " * 10)
609
610 update_hash(" ")
611 fh = hashlib.sha256()
612 if stat.S_ISREG(s.st_mode):
613 # Hash file contents
Patrick Williams93c203f2021-10-06 16:15:23 -0500614 if filterfile:
615 # Need to ignore paths in crossscripts and postinst-useradd files.
616 with open(path, 'rb') as d:
617 chunk = d.read()
618 chunk = chunk.replace(bytes(basepath, encoding='utf8'), b'')
619 for entry in filemaps:
620 if not fnmatch.fnmatch(path, entry):
621 continue
622 for r in filemaps[entry]:
623 if r.startswith("regex-"):
624 chunk = re.sub(bytes(r[6:], encoding='utf8'), b'', chunk)
625 else:
626 chunk = chunk.replace(bytes(r, encoding='utf8'), b'')
Brad Bishop19323692019-04-05 15:28:33 -0400627 fh.update(chunk)
Patrick Williams93c203f2021-10-06 16:15:23 -0500628 else:
629 with open(path, 'rb') as d:
630 for chunk in iter(lambda: d.read(4096), b""):
631 fh.update(chunk)
Brad Bishop19323692019-04-05 15:28:33 -0400632 update_hash(fh.hexdigest())
633 else:
634 update_hash(" " * len(fh.hexdigest()))
635
636 update_hash(" %s" % path)
637
638 if stat.S_ISLNK(s.st_mode):
639 update_hash(" -> %s" % os.readlink(path))
640
641 update_hash("\n")
642
643 # Process this directory and all its child files
Andrew Geissler5199d832021-09-24 16:47:35 -0500644 if include_root or root != ".":
645 process(root)
Brad Bishop19323692019-04-05 15:28:33 -0400646 for f in files:
647 if f == 'fixmepath':
648 continue
649 process(os.path.join(root, f))
Andrew Geissler6aa7eec2023-03-03 12:41:14 -0600650
651 for dir in dirs:
652 if os.path.islink(os.path.join(root, dir)):
653 process(os.path.join(root, dir))
Brad Bishop19323692019-04-05 15:28:33 -0400654 finally:
655 os.chdir(prev_dir)
656
657 return h.hexdigest()
658
Brad Bishop316dfdd2018-06-25 12:45:53 -0400659