blob: 1dd20f85ebd455a52753d8c8dd53634db4fbb035 [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#
6
Andrew Geissler517393d2023-01-13 08:55:19 -06007import errno
8import fnmatch
9import itertools
10import os
Patrick Williams8e7b46e2023-05-01 14:19:06 -050011import shlex
Andrew Geissler517393d2023-01-13 08:55:19 -060012import re
13import glob
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080014import stat
15import mmap
16import subprocess
17
Andrew Geissler517393d2023-01-13 08:55:19 -060018import oe.cachedpath
19
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020def runstrip(arg):
21 # Function to strip a single file, called from split_and_strip_files below
22 # A working 'file' (one which works on the target architecture)
23 #
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080024 # The elftype is a bit pattern (explained in is_elf below) to tell
Patrick Williamsc124f4f2015-09-15 14:41:29 -050025 # us what type of file we're processing...
26 # 4 - executable
27 # 8 - shared library
28 # 16 - kernel module
29
Andrew Geissler595f6302022-01-24 19:11:47 +000030 if len(arg) == 3:
31 (file, elftype, strip) = arg
32 extra_strip_sections = ''
33 else:
34 (file, elftype, strip, extra_strip_sections) = arg
Patrick Williamsc124f4f2015-09-15 14:41:29 -050035
36 newmode = None
37 if not os.access(file, os.W_OK) or os.access(file, os.R_OK):
38 origmode = os.stat(file)[stat.ST_MODE]
39 newmode = origmode | stat.S_IWRITE | stat.S_IREAD
40 os.chmod(file, newmode)
41
Brad Bishop6e60e8b2018-02-01 10:27:11 -050042 stripcmd = [strip]
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080043 skip_strip = False
Patrick Williams8e7b46e2023-05-01 14:19:06 -050044 # kernel module
Patrick Williamsc124f4f2015-09-15 14:41:29 -050045 if elftype & 16:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080046 if is_kernel_module_signed(file):
47 bb.debug(1, "Skip strip on signed module %s" % file)
48 skip_strip = True
49 else:
50 stripcmd.extend(["--strip-debug", "--remove-section=.comment",
51 "--remove-section=.note", "--preserve-dates"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050052 # .so and shared library
53 elif ".so" in file and elftype & 8:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050054 stripcmd.extend(["--remove-section=.comment", "--remove-section=.note", "--strip-unneeded"])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050055 # shared or executable:
56 elif elftype & 8 or elftype & 4:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050057 stripcmd.extend(["--remove-section=.comment", "--remove-section=.note"])
Andrew Geissler595f6302022-01-24 19:11:47 +000058 if extra_strip_sections != '':
59 for section in extra_strip_sections.split():
60 stripcmd.extend(["--remove-section=" + section])
Patrick Williamsc124f4f2015-09-15 14:41:29 -050061
Brad Bishop6e60e8b2018-02-01 10:27:11 -050062 stripcmd.append(file)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050063 bb.debug(1, "runstrip: %s" % stripcmd)
64
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080065 if not skip_strip:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050066 output = subprocess.check_output(stripcmd, stderr=subprocess.STDOUT)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050067
68 if newmode:
69 os.chmod(file, origmode)
70
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080071# Detect .ko module by searching for "vermagic=" string
72def is_kernel_module(path):
73 with open(path) as f:
74 return mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ).find(b"vermagic=") >= 0
Patrick Williamsc124f4f2015-09-15 14:41:29 -050075
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080076# Detect if .ko module is signed
77def is_kernel_module_signed(path):
78 with open(path, "rb") as f:
79 f.seek(-28, 2)
80 module_tail = f.read()
81 return "Module signature appended" in "".join(chr(c) for c in bytearray(module_tail))
Patrick Williamsc124f4f2015-09-15 14:41:29 -050082
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080083# Return type (bits):
84# 0 - not elf
85# 1 - ELF
86# 2 - stripped
87# 4 - executable
88# 8 - shared library
89# 16 - kernel module
90def is_elf(path):
91 exec_type = 0
92 result = subprocess.check_output(["file", "-b", path], stderr=subprocess.STDOUT).decode("utf-8")
93
94 if "ELF" in result:
95 exec_type |= 1
96 if "not stripped" not in result:
97 exec_type |= 2
98 if "executable" in result:
99 exec_type |= 4
100 if "shared" in result:
101 exec_type |= 8
102 if "relocatable" in result:
103 if path.endswith(".ko") and path.find("/lib/modules/") != -1 and is_kernel_module(path):
104 exec_type |= 16
105 return (path, exec_type)
106
107def is_static_lib(path):
108 if path.endswith('.a') and not os.path.islink(path):
109 with open(path, 'rb') as fh:
110 # The magic must include the first slash to avoid
111 # matching golang static libraries
112 magic = b'!<arch>\x0a/'
113 start = fh.read(len(magic))
114 return start == magic
115 return False
116
Andrew Geissler220dafd2023-10-04 10:18:08 -0500117def strip_execs(pn, dstdir, strip_cmd, libdir, base_libdir, max_process, qa_already_stripped=False):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500118 """
119 Strip executable code (like executables, shared libraries) _in_place_
120 - Based on sysroot_strip in staging.bbclass
121 :param dstdir: directory in which to strip files
122 :param strip_cmd: Strip command (usually ${STRIP})
123 :param libdir: ${libdir} - strip .so files in this directory
124 :param base_libdir: ${base_libdir} - strip .so files in this directory
Andrew Geissler220dafd2023-10-04 10:18:08 -0500125 :param max_process: number of stripping processes started in parallel
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500126 :param qa_already_stripped: Set to True if already-stripped' in ${INSANE_SKIP}
127 This is for proper logging and messages only.
128 """
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800129 import stat, errno, oe.path, oe.utils
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500130
131 elffiles = {}
132 inodes = {}
133 libdir = os.path.abspath(dstdir + os.sep + libdir)
134 base_libdir = os.path.abspath(dstdir + os.sep + base_libdir)
135 exec_mask = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
136 #
137 # First lets figure out all of the files we may have to process
138 #
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800139 checkelf = []
140 inodecache = {}
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500141 for root, dirs, files in os.walk(dstdir):
142 for f in files:
143 file = os.path.join(root, f)
144
145 try:
146 ltarget = oe.path.realpath(file, dstdir, False)
147 s = os.lstat(ltarget)
148 except OSError as e:
149 (err, strerror) = e.args
150 if err != errno.ENOENT:
151 raise
152 # Skip broken symlinks
153 continue
154 if not s:
155 continue
156 # Check its an excutable
157 if s[stat.ST_MODE] & exec_mask \
158 or ((file.startswith(libdir) or file.startswith(base_libdir)) and ".so" in f) \
159 or file.endswith('.ko'):
160 # If it's a symlink, and points to an ELF file, we capture the readlink target
161 if os.path.islink(file):
162 continue
163
164 # It's a file (or hardlink), not a link
165 # ...but is it ELF, and is it already stripped?
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800166 checkelf.append(file)
167 inodecache[file] = s.st_ino
Andrew Geissler220dafd2023-10-04 10:18:08 -0500168 results = oe.utils.multiprocess_launch_mp(is_elf, checkelf, max_process)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800169 for (file, elf_file) in results:
170 #elf_file = is_elf(file)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500171 if elf_file & 1:
172 if elf_file & 2:
173 if qa_already_stripped:
174 bb.note("Skipping file %s from %s for already-stripped QA test" % (file[len(dstdir):], pn))
175 else:
176 bb.warn("File '%s' from %s was already stripped, this will prevent future debugging!" % (file[len(dstdir):], pn))
177 continue
178
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800179 if inodecache[file] in inodes:
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500180 os.unlink(file)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800181 os.link(inodes[inodecache[file]], file)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500182 else:
183 # break hardlinks so that we do not strip the original.
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800184 inodes[inodecache[file]] = file
185 bb.utils.break_hardlinks(file)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500186 elffiles[file] = elf_file
187
188 #
189 # Now strip them (in parallel)
190 #
191 sfiles = []
192 for file in elffiles:
193 elf_file = int(elffiles[file])
194 sfiles.append((file, elf_file, strip_cmd))
195
Andrew Geissler220dafd2023-10-04 10:18:08 -0500196 oe.utils.multiprocess_launch_mp(runstrip, sfiles, max_process)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500197
198
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500199def file_translate(file):
200 ft = file.replace("@", "@at@")
201 ft = ft.replace(" ", "@space@")
202 ft = ft.replace("\t", "@tab@")
203 ft = ft.replace("[", "@openbrace@")
204 ft = ft.replace("]", "@closebrace@")
205 ft = ft.replace("_", "@underscore@")
206 return ft
207
208def filedeprunner(arg):
209 import re, subprocess, shlex
210
211 (pkg, pkgfiles, rpmdeps, pkgdest) = arg
212 provides = {}
213 requires = {}
214
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500215 file_re = re.compile(r'\s+\d+\s(.*)')
216 dep_re = re.compile(r'\s+(\S)\s+(.*)')
217 r = re.compile(r'[<>=]+\s+\S*')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500218
219 def process_deps(pipe, pkg, pkgdest, provides, requires):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500220 file = None
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500221 for line in pipe.split("\n"):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500222
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500223 m = file_re.match(line)
224 if m:
225 file = m.group(1)
226 file = file.replace(pkgdest + "/" + pkg, "")
227 file = file_translate(file)
228 continue
229
230 m = dep_re.match(line)
231 if not m or not file:
232 continue
233
234 type, dep = m.groups()
235
236 if type == 'R':
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500237 i = requires
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500238 elif type == 'P':
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500239 i = provides
240 else:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500241 continue
242
243 if dep.startswith("python("):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500244 continue
245
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500246 # Ignore all perl(VMS::...) and perl(Mac::...) dependencies. These
247 # are typically used conditionally from the Perl code, but are
248 # generated as unconditional dependencies.
249 if dep.startswith('perl(VMS::') or dep.startswith('perl(Mac::'):
250 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500251
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500252 # Ignore perl dependencies on .pl files.
253 if dep.startswith('perl(') and dep.endswith('.pl)'):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500254 continue
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500255
256 # Remove perl versions and perl module versions since they typically
257 # do not make sense when used as package versions.
258 if dep.startswith('perl') and r.search(dep):
259 dep = dep.split()[0]
260
261 # Put parentheses around any version specifications.
262 dep = r.sub(r'(\g<0>)',dep)
263
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500264 if file not in i:
265 i[file] = []
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500266 i[file].append(dep)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500267
268 return provides, requires
269
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500270 output = subprocess.check_output(shlex.split(rpmdeps) + pkgfiles, stderr=subprocess.STDOUT).decode("utf-8")
271 provides, requires = process_deps(output, pkg, pkgdest, provides, requires)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500272
273 return (pkg, provides, requires)
274
275
276def read_shlib_providers(d):
277 import re
278
279 shlib_provider = {}
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500280 shlibs_dirs = d.getVar('SHLIBSDIRS').split()
Brad Bishop19323692019-04-05 15:28:33 -0400281 list_re = re.compile(r'^(.*)\.list$')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500282 # Go from least to most specific since the last one found wins
283 for dir in reversed(shlibs_dirs):
284 bb.debug(2, "Reading shlib providers in %s" % (dir))
285 if not os.path.exists(dir):
286 continue
Brad Bishop08902b02019-08-20 09:16:51 -0400287 for file in sorted(os.listdir(dir)):
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500288 m = list_re.match(file)
289 if m:
290 dep_pkg = m.group(1)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600291 try:
292 fd = open(os.path.join(dir, file))
293 except IOError:
294 # During a build unrelated shlib files may be deleted, so
295 # handle files disappearing between the listdirs and open.
296 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500297 lines = fd.readlines()
298 fd.close()
299 for l in lines:
300 s = l.strip().split(":")
301 if s[0] not in shlib_provider:
302 shlib_provider[s[0]] = {}
303 shlib_provider[s[0]][s[1]] = (dep_pkg, s[2])
304 return shlib_provider
Andrew Geissler517393d2023-01-13 08:55:19 -0600305
306# We generate a master list of directories to process, we start by
307# seeding this list with reasonable defaults, then load from
308# the fs-perms.txt files
309def fixup_perms(d):
310 import pwd, grp
311
312 cpath = oe.cachedpath.CachedPath()
313 dvar = d.getVar('PKGD')
314
315 # init using a string with the same format as a line as documented in
316 # the fs-perms.txt file
317 # <path> <mode> <uid> <gid> <walk> <fmode> <fuid> <fgid>
318 # <path> link <link target>
319 #
320 # __str__ can be used to print out an entry in the input format
321 #
322 # if fs_perms_entry.path is None:
323 # an error occurred
324 # if fs_perms_entry.link, you can retrieve:
325 # fs_perms_entry.path = path
326 # fs_perms_entry.link = target of link
327 # if not fs_perms_entry.link, you can retrieve:
328 # fs_perms_entry.path = path
329 # fs_perms_entry.mode = expected dir mode or None
330 # fs_perms_entry.uid = expected uid or -1
331 # fs_perms_entry.gid = expected gid or -1
332 # fs_perms_entry.walk = 'true' or something else
333 # fs_perms_entry.fmode = expected file mode or None
334 # fs_perms_entry.fuid = expected file uid or -1
335 # fs_perms_entry_fgid = expected file gid or -1
336 class fs_perms_entry():
337 def __init__(self, line):
338 lsplit = line.split()
339 if len(lsplit) == 3 and lsplit[1].lower() == "link":
340 self._setlink(lsplit[0], lsplit[2])
341 elif len(lsplit) == 8:
342 self._setdir(lsplit[0], lsplit[1], lsplit[2], lsplit[3], lsplit[4], lsplit[5], lsplit[6], lsplit[7])
343 else:
344 msg = "Fixup Perms: invalid config line %s" % line
345 oe.qa.handle_error("perm-config", msg, d)
346 self.path = None
347 self.link = None
348
349 def _setdir(self, path, mode, uid, gid, walk, fmode, fuid, fgid):
350 self.path = os.path.normpath(path)
351 self.link = None
352 self.mode = self._procmode(mode)
353 self.uid = self._procuid(uid)
354 self.gid = self._procgid(gid)
355 self.walk = walk.lower()
356 self.fmode = self._procmode(fmode)
357 self.fuid = self._procuid(fuid)
358 self.fgid = self._procgid(fgid)
359
360 def _setlink(self, path, link):
361 self.path = os.path.normpath(path)
362 self.link = link
363
364 def _procmode(self, mode):
365 if not mode or (mode and mode == "-"):
366 return None
367 else:
368 return int(mode,8)
369
370 # Note uid/gid -1 has special significance in os.lchown
371 def _procuid(self, uid):
372 if uid is None or uid == "-":
373 return -1
374 elif uid.isdigit():
375 return int(uid)
376 else:
377 return pwd.getpwnam(uid).pw_uid
378
379 def _procgid(self, gid):
380 if gid is None or gid == "-":
381 return -1
382 elif gid.isdigit():
383 return int(gid)
384 else:
385 return grp.getgrnam(gid).gr_gid
386
387 # Use for debugging the entries
388 def __str__(self):
389 if self.link:
390 return "%s link %s" % (self.path, self.link)
391 else:
392 mode = "-"
393 if self.mode:
394 mode = "0%o" % self.mode
395 fmode = "-"
396 if self.fmode:
397 fmode = "0%o" % self.fmode
398 uid = self._mapugid(self.uid)
399 gid = self._mapugid(self.gid)
400 fuid = self._mapugid(self.fuid)
401 fgid = self._mapugid(self.fgid)
402 return "%s %s %s %s %s %s %s %s" % (self.path, mode, uid, gid, self.walk, fmode, fuid, fgid)
403
404 def _mapugid(self, id):
405 if id is None or id == -1:
406 return "-"
407 else:
408 return "%d" % id
409
410 # Fix the permission, owner and group of path
411 def fix_perms(path, mode, uid, gid, dir):
412 if mode and not os.path.islink(path):
413 #bb.note("Fixup Perms: chmod 0%o %s" % (mode, dir))
414 os.chmod(path, mode)
415 # -1 is a special value that means don't change the uid/gid
416 # if they are BOTH -1, don't bother to lchown
417 if not (uid == -1 and gid == -1):
418 #bb.note("Fixup Perms: lchown %d:%d %s" % (uid, gid, dir))
419 os.lchown(path, uid, gid)
420
421 # Return a list of configuration files based on either the default
422 # files/fs-perms.txt or the contents of FILESYSTEM_PERMS_TABLES
423 # paths are resolved via BBPATH
424 def get_fs_perms_list(d):
425 str = ""
426 bbpath = d.getVar('BBPATH')
427 fs_perms_tables = d.getVar('FILESYSTEM_PERMS_TABLES') or ""
428 for conf_file in fs_perms_tables.split():
429 confpath = bb.utils.which(bbpath, conf_file)
430 if confpath:
431 str += " %s" % bb.utils.which(bbpath, conf_file)
432 else:
433 bb.warn("cannot find %s specified in FILESYSTEM_PERMS_TABLES" % conf_file)
434 return str
435
436 fs_perms_table = {}
437 fs_link_table = {}
438
439 # By default all of the standard directories specified in
440 # bitbake.conf will get 0755 root:root.
441 target_path_vars = [ 'base_prefix',
442 'prefix',
443 'exec_prefix',
444 'base_bindir',
445 'base_sbindir',
446 'base_libdir',
447 'datadir',
448 'sysconfdir',
449 'servicedir',
450 'sharedstatedir',
451 'localstatedir',
452 'infodir',
453 'mandir',
454 'docdir',
455 'bindir',
456 'sbindir',
457 'libexecdir',
458 'libdir',
459 'includedir',
460 'oldincludedir' ]
461
462 for path in target_path_vars:
463 dir = d.getVar(path) or ""
464 if dir == "":
465 continue
466 fs_perms_table[dir] = fs_perms_entry(d.expand("%s 0755 root root false - - -" % (dir)))
467
468 # Now we actually load from the configuration files
469 for conf in get_fs_perms_list(d).split():
470 if not os.path.exists(conf):
471 continue
472 with open(conf) as f:
473 for line in f:
474 if line.startswith('#'):
475 continue
476 lsplit = line.split()
477 if len(lsplit) == 0:
478 continue
479 if len(lsplit) != 8 and not (len(lsplit) == 3 and lsplit[1].lower() == "link"):
480 msg = "Fixup perms: %s invalid line: %s" % (conf, line)
481 oe.qa.handle_error("perm-line", msg, d)
482 continue
483 entry = fs_perms_entry(d.expand(line))
484 if entry and entry.path:
485 if entry.link:
486 fs_link_table[entry.path] = entry
487 if entry.path in fs_perms_table:
488 fs_perms_table.pop(entry.path)
489 else:
490 fs_perms_table[entry.path] = entry
491 if entry.path in fs_link_table:
492 fs_link_table.pop(entry.path)
493
494 # Debug -- list out in-memory table
495 #for dir in fs_perms_table:
496 # bb.note("Fixup Perms: %s: %s" % (dir, str(fs_perms_table[dir])))
497 #for link in fs_link_table:
498 # bb.note("Fixup Perms: %s: %s" % (link, str(fs_link_table[link])))
499
500 # We process links first, so we can go back and fixup directory ownership
501 # for any newly created directories
502 # Process in sorted order so /run gets created before /run/lock, etc.
503 for entry in sorted(fs_link_table.values(), key=lambda x: x.link):
504 link = entry.link
505 dir = entry.path
506 origin = dvar + dir
507 if not (cpath.exists(origin) and cpath.isdir(origin) and not cpath.islink(origin)):
508 continue
509
510 if link[0] == "/":
511 target = dvar + link
512 ptarget = link
513 else:
514 target = os.path.join(os.path.dirname(origin), link)
515 ptarget = os.path.join(os.path.dirname(dir), link)
516 if os.path.exists(target):
517 msg = "Fixup Perms: Unable to correct directory link, target already exists: %s -> %s" % (dir, ptarget)
518 oe.qa.handle_error("perm-link", msg, d)
519 continue
520
521 # Create path to move directory to, move it, and then setup the symlink
522 bb.utils.mkdirhier(os.path.dirname(target))
523 #bb.note("Fixup Perms: Rename %s -> %s" % (dir, ptarget))
524 bb.utils.rename(origin, target)
525 #bb.note("Fixup Perms: Link %s -> %s" % (dir, link))
526 os.symlink(link, origin)
527
528 for dir in fs_perms_table:
529 origin = dvar + dir
530 if not (cpath.exists(origin) and cpath.isdir(origin)):
531 continue
532
533 fix_perms(origin, fs_perms_table[dir].mode, fs_perms_table[dir].uid, fs_perms_table[dir].gid, dir)
534
535 if fs_perms_table[dir].walk == 'true':
536 for root, dirs, files in os.walk(origin):
537 for dr in dirs:
538 each_dir = os.path.join(root, dr)
539 fix_perms(each_dir, fs_perms_table[dir].mode, fs_perms_table[dir].uid, fs_perms_table[dir].gid, dir)
540 for f in files:
541 each_file = os.path.join(root, f)
542 fix_perms(each_file, fs_perms_table[dir].fmode, fs_perms_table[dir].fuid, fs_perms_table[dir].fgid, dir)
543
544# Get a list of files from file vars by searching files under current working directory
545# The list contains symlinks, directories and normal files.
546def files_from_filevars(filevars):
547 cpath = oe.cachedpath.CachedPath()
548 files = []
549 for f in filevars:
550 if os.path.isabs(f):
551 f = '.' + f
552 if not f.startswith("./"):
553 f = './' + f
Patrick Williamse760df82023-05-26 11:10:49 -0500554 globbed = glob.glob(f, recursive=True)
Andrew Geissler517393d2023-01-13 08:55:19 -0600555 if globbed:
556 if [ f ] != globbed:
557 files += globbed
558 continue
559 files.append(f)
560
561 symlink_paths = []
562 for ind, f in enumerate(files):
563 # Handle directory symlinks. Truncate path to the lowest level symlink
564 parent = ''
565 for dirname in f.split('/')[:-1]:
566 parent = os.path.join(parent, dirname)
567 if dirname == '.':
568 continue
569 if cpath.islink(parent):
570 bb.warn("FILES contains file '%s' which resides under a "
571 "directory symlink. Please fix the recipe and use the "
572 "real path for the file." % f[1:])
573 symlink_paths.append(f)
574 files[ind] = parent
575 f = parent
576 break
577
578 if not cpath.islink(f):
579 if cpath.isdir(f):
580 newfiles = [ os.path.join(f,x) for x in os.listdir(f) ]
581 if newfiles:
582 files += newfiles
583
584 return files, symlink_paths
585
586# Called in package_<rpm,ipk,deb>.bbclass to get the correct list of configuration files
587def get_conffiles(pkg, d):
588 pkgdest = d.getVar('PKGDEST')
589 root = os.path.join(pkgdest, pkg)
590 cwd = os.getcwd()
591 os.chdir(root)
592
593 conffiles = d.getVar('CONFFILES:%s' % pkg);
594 if conffiles == None:
595 conffiles = d.getVar('CONFFILES')
596 if conffiles == None:
597 conffiles = ""
598 conffiles = conffiles.split()
599 conf_orig_list = files_from_filevars(conffiles)[0]
600
601 # Remove links and directories from conf_orig_list to get conf_list which only contains normal files
602 conf_list = []
603 for f in conf_orig_list:
604 if os.path.isdir(f):
605 continue
606 if os.path.islink(f):
607 continue
608 if not os.path.exists(f):
609 continue
610 conf_list.append(f)
611
612 # Remove the leading './'
613 for i in range(0, len(conf_list)):
614 conf_list[i] = conf_list[i][1:]
615
616 os.chdir(cwd)
Patrick Williams2a254922023-08-11 09:48:11 -0500617 return sorted(conf_list)
Andrew Geissler517393d2023-01-13 08:55:19 -0600618
619def legitimize_package_name(s):
620 """
621 Make sure package names are legitimate strings
622 """
623
624 def fixutf(m):
625 cp = m.group(1)
626 if cp:
627 return ('\\u%s' % cp).encode('latin-1').decode('unicode_escape')
628
629 # Handle unicode codepoints encoded as <U0123>, as in glibc locale files.
630 s = re.sub(r'<U([0-9A-Fa-f]{1,4})>', fixutf, s)
631
632 # Remaining package name validity fixes
633 return s.lower().replace('_', '-').replace('@', '+').replace(',', '+').replace('/', '-')
634
635def split_locales(d):
636 cpath = oe.cachedpath.CachedPath()
637 if (d.getVar('PACKAGE_NO_LOCALE') == '1'):
638 bb.debug(1, "package requested not splitting locales")
639 return
640
641 packages = (d.getVar('PACKAGES') or "").split()
642
643 datadir = d.getVar('datadir')
644 if not datadir:
645 bb.note("datadir not defined")
646 return
647
648 dvar = d.getVar('PKGD')
649 pn = d.getVar('LOCALEBASEPN')
650
651 if pn + '-locale' in packages:
652 packages.remove(pn + '-locale')
653
654 localedir = os.path.join(dvar + datadir, 'locale')
655
656 if not cpath.isdir(localedir):
657 bb.debug(1, "No locale files in this package")
658 return
659
660 locales = os.listdir(localedir)
661
662 summary = d.getVar('SUMMARY') or pn
663 description = d.getVar('DESCRIPTION') or ""
664 locale_section = d.getVar('LOCALE_SECTION')
665 mlprefix = d.getVar('MLPREFIX') or ""
666 for l in sorted(locales):
667 ln = legitimize_package_name(l)
668 pkg = pn + '-locale-' + ln
669 packages.append(pkg)
670 d.setVar('FILES:' + pkg, os.path.join(datadir, 'locale', l))
671 d.setVar('RRECOMMENDS:' + pkg, '%svirtual-locale-%s' % (mlprefix, ln))
672 d.setVar('RPROVIDES:' + pkg, '%s-locale %s%s-translation' % (pn, mlprefix, ln))
673 d.setVar('SUMMARY:' + pkg, '%s - %s translations' % (summary, l))
674 d.setVar('DESCRIPTION:' + pkg, '%s This package contains language translation files for the %s locale.' % (description, l))
675 if locale_section:
676 d.setVar('SECTION:' + pkg, locale_section)
677
678 d.setVar('PACKAGES', ' '.join(packages))
679
680 # Disabled by RP 18/06/07
681 # Wildcards aren't supported in debian
682 # They break with ipkg since glibc-locale* will mean that
683 # glibc-localedata-translit* won't install as a dependency
684 # for some other package which breaks meta-toolchain
685 # Probably breaks since virtual-locale- isn't provided anywhere
686 #rdep = (d.getVar('RDEPENDS:%s' % pn) or "").split()
687 #rdep.append('%s-locale*' % pn)
688 #d.setVar('RDEPENDS:%s' % pn, ' '.join(rdep))
689
690def package_debug_vars(d):
691 # We default to '.debug' style
692 if d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-file-directory':
693 # Single debug-file-directory style debug info
694 debug_vars = {
695 "append": ".debug",
696 "staticappend": "",
697 "dir": "",
698 "staticdir": "",
699 "libdir": "/usr/lib/debug",
700 "staticlibdir": "/usr/lib/debug-static",
701 "srcdir": "/usr/src/debug",
702 }
703 elif d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-without-src':
704 # Original OE-core, a.k.a. ".debug", style debug info, but without sources in /usr/src/debug
705 debug_vars = {
706 "append": "",
707 "staticappend": "",
708 "dir": "/.debug",
709 "staticdir": "/.debug-static",
710 "libdir": "",
711 "staticlibdir": "",
712 "srcdir": "",
713 }
714 elif d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-with-srcpkg':
715 debug_vars = {
716 "append": "",
717 "staticappend": "",
718 "dir": "/.debug",
719 "staticdir": "/.debug-static",
720 "libdir": "",
721 "staticlibdir": "",
722 "srcdir": "/usr/src/debug",
723 }
724 else:
725 # Original OE-core, a.k.a. ".debug", style debug info
726 debug_vars = {
727 "append": "",
728 "staticappend": "",
729 "dir": "/.debug",
730 "staticdir": "/.debug-static",
731 "libdir": "",
732 "staticlibdir": "",
733 "srcdir": "/usr/src/debug",
734 }
735
736 return debug_vars
737
738
739def parse_debugsources_from_dwarfsrcfiles_output(dwarfsrcfiles_output):
740 debugfiles = {}
741
742 for line in dwarfsrcfiles_output.splitlines():
743 if line.startswith("\t"):
744 debugfiles[os.path.normpath(line.split()[0])] = ""
745
746 return debugfiles.keys()
747
748def source_info(file, d, fatal=True):
749 cmd = ["dwarfsrcfiles", file]
750 try:
751 output = subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.STDOUT)
752 retval = 0
753 except subprocess.CalledProcessError as exc:
754 output = exc.output
755 retval = exc.returncode
756
757 # 255 means a specific file wasn't fully parsed to get the debug file list, which is not a fatal failure
758 if retval != 0 and retval != 255:
759 msg = "dwarfsrcfiles failed with exit code %s (cmd was %s)%s" % (retval, cmd, ":\n%s" % output if output else "")
760 if fatal:
761 bb.fatal(msg)
762 bb.note(msg)
763
764 debugsources = parse_debugsources_from_dwarfsrcfiles_output(output)
765
766 return list(debugsources)
767
768def splitdebuginfo(file, dvar, dv, d):
769 # Function to split a single file into two components, one is the stripped
770 # target system binary, the other contains any debugging information. The
771 # two files are linked to reference each other.
772 #
773 # return a mapping of files:debugsources
774
775 src = file[len(dvar):]
776 dest = dv["libdir"] + os.path.dirname(src) + dv["dir"] + "/" + os.path.basename(src) + dv["append"]
777 debugfile = dvar + dest
778 sources = []
779
780 if file.endswith(".ko") and file.find("/lib/modules/") != -1:
781 if oe.package.is_kernel_module_signed(file):
782 bb.debug(1, "Skip strip on signed module %s" % file)
783 return (file, sources)
784
785 # Split the file...
786 bb.utils.mkdirhier(os.path.dirname(debugfile))
787 #bb.note("Split %s -> %s" % (file, debugfile))
788 # Only store off the hard link reference if we successfully split!
789
790 dvar = d.getVar('PKGD')
791 objcopy = d.getVar("OBJCOPY")
792
793 newmode = None
794 if not os.access(file, os.W_OK) or os.access(file, os.R_OK):
795 origmode = os.stat(file)[stat.ST_MODE]
796 newmode = origmode | stat.S_IWRITE | stat.S_IREAD
797 os.chmod(file, newmode)
798
799 # We need to extract the debug src information here...
800 if dv["srcdir"]:
801 sources = source_info(file, d)
802
803 bb.utils.mkdirhier(os.path.dirname(debugfile))
804
805 subprocess.check_output([objcopy, '--only-keep-debug', file, debugfile], stderr=subprocess.STDOUT)
806
807 # Set the debuglink to have the view of the file path on the target
808 subprocess.check_output([objcopy, '--add-gnu-debuglink', debugfile, file], stderr=subprocess.STDOUT)
809
810 if newmode:
811 os.chmod(file, origmode)
812
813 return (file, sources)
814
815def splitstaticdebuginfo(file, dvar, dv, d):
816 # Unlike the function above, there is no way to split a static library
817 # two components. So to get similar results we will copy the unmodified
818 # static library (containing the debug symbols) into a new directory.
819 # We will then strip (preserving symbols) the static library in the
820 # typical location.
821 #
822 # return a mapping of files:debugsources
823
824 src = file[len(dvar):]
825 dest = dv["staticlibdir"] + os.path.dirname(src) + dv["staticdir"] + "/" + os.path.basename(src) + dv["staticappend"]
826 debugfile = dvar + dest
827 sources = []
828
829 # Copy the file...
830 bb.utils.mkdirhier(os.path.dirname(debugfile))
831 #bb.note("Copy %s -> %s" % (file, debugfile))
832
833 dvar = d.getVar('PKGD')
834
835 newmode = None
836 if not os.access(file, os.W_OK) or os.access(file, os.R_OK):
837 origmode = os.stat(file)[stat.ST_MODE]
838 newmode = origmode | stat.S_IWRITE | stat.S_IREAD
839 os.chmod(file, newmode)
840
841 # We need to extract the debug src information here...
842 if dv["srcdir"]:
843 sources = source_info(file, d)
844
845 bb.utils.mkdirhier(os.path.dirname(debugfile))
846
847 # Copy the unmodified item to the debug directory
848 shutil.copy2(file, debugfile)
849
850 if newmode:
851 os.chmod(file, origmode)
852
853 return (file, sources)
854
855def inject_minidebuginfo(file, dvar, dv, d):
856 # Extract just the symbols from debuginfo into minidebuginfo,
857 # compress it with xz and inject it back into the binary in a .gnu_debugdata section.
858 # https://sourceware.org/gdb/onlinedocs/gdb/MiniDebugInfo.html
859
860 readelf = d.getVar('READELF')
861 nm = d.getVar('NM')
862 objcopy = d.getVar('OBJCOPY')
863
864 minidebuginfodir = d.expand('${WORKDIR}/minidebuginfo')
865
866 src = file[len(dvar):]
867 dest = dv["libdir"] + os.path.dirname(src) + dv["dir"] + "/" + os.path.basename(src) + dv["append"]
868 debugfile = dvar + dest
869 minidebugfile = minidebuginfodir + src + '.minidebug'
870 bb.utils.mkdirhier(os.path.dirname(minidebugfile))
871
872 # If we didn't produce debuginfo for any reason, we can't produce minidebuginfo either
873 # so skip it.
874 if not os.path.exists(debugfile):
875 bb.debug(1, 'ELF file {} has no debuginfo, skipping minidebuginfo injection'.format(file))
876 return
877
878 # minidebuginfo does not make sense to apply to ELF objects other than
879 # executables and shared libraries, skip applying the minidebuginfo
880 # generation for objects like kernel modules.
881 for line in subprocess.check_output([readelf, '-h', debugfile], universal_newlines=True).splitlines():
882 if not line.strip().startswith("Type:"):
883 continue
884 elftype = line.split(":")[1].strip()
885 if not any(elftype.startswith(i) for i in ["EXEC", "DYN"]):
886 bb.debug(1, 'ELF file {} is not executable/shared, skipping minidebuginfo injection'.format(file))
887 return
888 break
889
890 # Find non-allocated PROGBITS, NOTE, and NOBITS sections in the debuginfo.
891 # We will exclude all of these from minidebuginfo to save space.
892 remove_section_names = []
893 for line in subprocess.check_output([readelf, '-W', '-S', debugfile], universal_newlines=True).splitlines():
894 # strip the leading " [ 1]" section index to allow splitting on space
895 if ']' not in line:
896 continue
897 fields = line[line.index(']') + 1:].split()
898 if len(fields) < 7:
899 continue
900 name = fields[0]
901 type = fields[1]
902 flags = fields[6]
903 # .debug_ sections will be removed by objcopy -S so no need to explicitly remove them
904 if name.startswith('.debug_'):
905 continue
906 if 'A' not in flags and type in ['PROGBITS', 'NOTE', 'NOBITS']:
907 remove_section_names.append(name)
908
909 # List dynamic symbols in the binary. We can exclude these from minidebuginfo
910 # because they are always present in the binary.
911 dynsyms = set()
912 for line in subprocess.check_output([nm, '-D', file, '--format=posix', '--defined-only'], universal_newlines=True).splitlines():
913 dynsyms.add(line.split()[0])
914
915 # Find all function symbols from debuginfo which aren't in the dynamic symbols table.
916 # These are the ones we want to keep in minidebuginfo.
917 keep_symbols_file = minidebugfile + '.symlist'
918 found_any_symbols = False
919 with open(keep_symbols_file, 'w') as f:
920 for line in subprocess.check_output([nm, debugfile, '--format=sysv', '--defined-only'], universal_newlines=True).splitlines():
921 fields = line.split('|')
922 if len(fields) < 7:
923 continue
924 name = fields[0].strip()
925 type = fields[3].strip()
926 if type == 'FUNC' and name not in dynsyms:
927 f.write('{}\n'.format(name))
928 found_any_symbols = True
929
930 if not found_any_symbols:
931 bb.debug(1, 'ELF file {} contains no symbols, skipping minidebuginfo injection'.format(file))
932 return
933
934 bb.utils.remove(minidebugfile)
935 bb.utils.remove(minidebugfile + '.xz')
936
937 subprocess.check_call([objcopy, '-S'] +
938 ['--remove-section={}'.format(s) for s in remove_section_names] +
939 ['--keep-symbols={}'.format(keep_symbols_file), debugfile, minidebugfile])
940
941 subprocess.check_call(['xz', '--keep', minidebugfile])
942
943 subprocess.check_call([objcopy, '--add-section', '.gnu_debugdata={}.xz'.format(minidebugfile), file])
944
945def copydebugsources(debugsrcdir, sources, d):
946 # The debug src information written out to sourcefile is further processed
947 # and copied to the destination here.
948
949 cpath = oe.cachedpath.CachedPath()
950
951 if debugsrcdir and sources:
952 sourcefile = d.expand("${WORKDIR}/debugsources.list")
953 bb.utils.remove(sourcefile)
954
955 # filenames are null-separated - this is an artefact of the previous use
956 # of rpm's debugedit, which was writing them out that way, and the code elsewhere
957 # is still assuming that.
958 debuglistoutput = '\0'.join(sources) + '\0'
959 with open(sourcefile, 'a') as sf:
960 sf.write(debuglistoutput)
961
962 dvar = d.getVar('PKGD')
963 strip = d.getVar("STRIP")
964 objcopy = d.getVar("OBJCOPY")
965 workdir = d.getVar("WORKDIR")
966 sdir = d.getVar("S")
967 cflags = d.expand("${CFLAGS}")
968
969 prefixmap = {}
970 for flag in cflags.split():
971 if not flag.startswith("-fdebug-prefix-map"):
972 continue
973 if "recipe-sysroot" in flag:
974 continue
975 flag = flag.split("=")
976 prefixmap[flag[1]] = flag[2]
977
978 nosuchdir = []
979 basepath = dvar
980 for p in debugsrcdir.split("/"):
981 basepath = basepath + "/" + p
982 if not cpath.exists(basepath):
983 nosuchdir.append(basepath)
984 bb.utils.mkdirhier(basepath)
985 cpath.updatecache(basepath)
986
987 for pmap in prefixmap:
988 # Ignore files from the recipe sysroots (target and native)
989 cmd = "LC_ALL=C ; sort -z -u '%s' | egrep -v -z '((<internal>|<built-in>)$|/.*recipe-sysroot.*/)' | " % sourcefile
990 # We need to ignore files that are not actually ours
991 # we do this by only paying attention to items from this package
992 cmd += "fgrep -zw '%s' | " % prefixmap[pmap]
993 # Remove prefix in the source paths
994 cmd += "sed 's#%s/##g' | " % (prefixmap[pmap])
995 cmd += "(cd '%s' ; cpio -pd0mlL --no-preserve-owner '%s%s' 2>/dev/null)" % (pmap, dvar, prefixmap[pmap])
996
997 try:
998 subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
999 except subprocess.CalledProcessError:
1000 # Can "fail" if internal headers/transient sources are attempted
1001 pass
1002 # cpio seems to have a bug with -lL together and symbolic links are just copied, not dereferenced.
1003 # Work around this by manually finding and copying any symbolic links that made it through.
1004 cmd = "find %s%s -type l -print0 -delete | sed s#%s%s/##g | (cd '%s' ; cpio -pd0mL --no-preserve-owner '%s%s')" % \
1005 (dvar, prefixmap[pmap], dvar, prefixmap[pmap], pmap, dvar, prefixmap[pmap])
1006 subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
1007
1008 # debugsources.list may be polluted from the host if we used externalsrc,
1009 # cpio uses copy-pass and may have just created a directory structure
1010 # matching the one from the host, if thats the case move those files to
1011 # debugsrcdir to avoid host contamination.
1012 # Empty dir structure will be deleted in the next step.
1013
1014 # Same check as above for externalsrc
1015 if workdir not in sdir:
1016 if os.path.exists(dvar + debugsrcdir + sdir):
1017 cmd = "mv %s%s%s/* %s%s" % (dvar, debugsrcdir, sdir, dvar,debugsrcdir)
1018 subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
1019
1020 # The copy by cpio may have resulted in some empty directories! Remove these
1021 cmd = "find %s%s -empty -type d -delete" % (dvar, debugsrcdir)
1022 subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
1023
1024 # Also remove debugsrcdir if its empty
1025 for p in nosuchdir[::-1]:
1026 if os.path.exists(p) and not os.listdir(p):
1027 os.rmdir(p)
1028
1029
1030def process_split_and_strip_files(d):
1031 cpath = oe.cachedpath.CachedPath()
1032
1033 dvar = d.getVar('PKGD')
1034 pn = d.getVar('PN')
1035 hostos = d.getVar('HOST_OS')
1036
1037 oldcwd = os.getcwd()
1038 os.chdir(dvar)
1039
1040 dv = package_debug_vars(d)
1041
1042 #
1043 # First lets figure out all of the files we may have to process ... do this only once!
1044 #
1045 elffiles = {}
1046 symlinks = {}
1047 staticlibs = []
1048 inodes = {}
1049 libdir = os.path.abspath(dvar + os.sep + d.getVar("libdir"))
1050 baselibdir = os.path.abspath(dvar + os.sep + d.getVar("base_libdir"))
1051 skipfiles = (d.getVar("INHIBIT_PACKAGE_STRIP_FILES") or "").split()
1052 if (d.getVar('INHIBIT_PACKAGE_STRIP') != '1' or \
1053 d.getVar('INHIBIT_PACKAGE_DEBUG_SPLIT') != '1'):
1054 checkelf = {}
1055 checkelflinks = {}
1056 for root, dirs, files in cpath.walk(dvar):
1057 for f in files:
1058 file = os.path.join(root, f)
1059
1060 # Skip debug files
1061 if dv["append"] and file.endswith(dv["append"]):
1062 continue
1063 if dv["dir"] and dv["dir"] in os.path.dirname(file[len(dvar):]):
1064 continue
1065
1066 if file in skipfiles:
1067 continue
1068
1069 if oe.package.is_static_lib(file):
1070 staticlibs.append(file)
1071 continue
1072
1073 try:
1074 ltarget = cpath.realpath(file, dvar, False)
1075 s = cpath.lstat(ltarget)
1076 except OSError as e:
1077 (err, strerror) = e.args
1078 if err != errno.ENOENT:
1079 raise
1080 # Skip broken symlinks
1081 continue
1082 if not s:
1083 continue
1084 # Check its an executable
1085 if (s[stat.ST_MODE] & stat.S_IXUSR) or (s[stat.ST_MODE] & stat.S_IXGRP) \
1086 or (s[stat.ST_MODE] & stat.S_IXOTH) \
1087 or ((file.startswith(libdir) or file.startswith(baselibdir)) \
1088 and (".so" in f or ".node" in f)) \
1089 or (f.startswith('vmlinux') or ".ko" in f):
1090
1091 if cpath.islink(file):
1092 checkelflinks[file] = ltarget
1093 continue
1094 # Use a reference of device ID and inode number to identify files
1095 file_reference = "%d_%d" % (s.st_dev, s.st_ino)
1096 checkelf[file] = (file, file_reference)
1097
1098 results = oe.utils.multiprocess_launch(oe.package.is_elf, checkelflinks.values(), d)
1099 results_map = {}
1100 for (ltarget, elf_file) in results:
1101 results_map[ltarget] = elf_file
1102 for file in checkelflinks:
1103 ltarget = checkelflinks[file]
1104 # If it's a symlink, and points to an ELF file, we capture the readlink target
1105 if results_map[ltarget]:
1106 target = os.readlink(file)
1107 #bb.note("Sym: %s (%d)" % (ltarget, results_map[ltarget]))
1108 symlinks[file] = target
1109
1110 results = oe.utils.multiprocess_launch(oe.package.is_elf, checkelf.keys(), d)
1111
1112 # Sort results by file path. This ensures that the files are always
1113 # processed in the same order, which is important to make sure builds
1114 # are reproducible when dealing with hardlinks
1115 results.sort(key=lambda x: x[0])
1116
1117 for (file, elf_file) in results:
1118 # It's a file (or hardlink), not a link
1119 # ...but is it ELF, and is it already stripped?
1120 if elf_file & 1:
1121 if elf_file & 2:
1122 if 'already-stripped' in (d.getVar('INSANE_SKIP:' + pn) or "").split():
1123 bb.note("Skipping file %s from %s for already-stripped QA test" % (file[len(dvar):], pn))
1124 else:
1125 msg = "File '%s' from %s was already stripped, this will prevent future debugging!" % (file[len(dvar):], pn)
1126 oe.qa.handle_error("already-stripped", msg, d)
1127 continue
1128
1129 # At this point we have an unstripped elf file. We need to:
1130 # a) Make sure any file we strip is not hardlinked to anything else outside this tree
1131 # b) Only strip any hardlinked file once (no races)
1132 # c) Track any hardlinks between files so that we can reconstruct matching debug file hardlinks
1133
1134 # Use a reference of device ID and inode number to identify files
1135 file_reference = checkelf[file][1]
1136 if file_reference in inodes:
1137 os.unlink(file)
1138 os.link(inodes[file_reference][0], file)
1139 inodes[file_reference].append(file)
1140 else:
1141 inodes[file_reference] = [file]
1142 # break hardlink
1143 bb.utils.break_hardlinks(file)
1144 elffiles[file] = elf_file
1145 # Modified the file so clear the cache
1146 cpath.updatecache(file)
1147
1148 def strip_pkgd_prefix(f):
1149 nonlocal dvar
1150
1151 if f.startswith(dvar):
1152 return f[len(dvar):]
1153
1154 return f
1155
1156 #
1157 # First lets process debug splitting
1158 #
1159 if (d.getVar('INHIBIT_PACKAGE_DEBUG_SPLIT') != '1'):
1160 results = oe.utils.multiprocess_launch(splitdebuginfo, list(elffiles), d, extraargs=(dvar, dv, d))
1161
1162 if dv["srcdir"] and not hostos.startswith("mingw"):
1163 if (d.getVar('PACKAGE_DEBUG_STATIC_SPLIT') == '1'):
1164 results = oe.utils.multiprocess_launch(splitstaticdebuginfo, staticlibs, d, extraargs=(dvar, dv, d))
1165 else:
1166 for file in staticlibs:
1167 results.append( (file,source_info(file, d)) )
1168
1169 d.setVar("PKGDEBUGSOURCES", {strip_pkgd_prefix(f): sorted(s) for f, s in results})
1170
1171 sources = set()
1172 for r in results:
1173 sources.update(r[1])
1174
1175 # Hardlink our debug symbols to the other hardlink copies
1176 for ref in inodes:
1177 if len(inodes[ref]) == 1:
1178 continue
1179
1180 target = inodes[ref][0][len(dvar):]
1181 for file in inodes[ref][1:]:
1182 src = file[len(dvar):]
1183 dest = dv["libdir"] + os.path.dirname(src) + dv["dir"] + "/" + os.path.basename(target) + dv["append"]
1184 fpath = dvar + dest
1185 ftarget = dvar + dv["libdir"] + os.path.dirname(target) + dv["dir"] + "/" + os.path.basename(target) + dv["append"]
1186 bb.utils.mkdirhier(os.path.dirname(fpath))
1187 # Only one hardlink of separated debug info file in each directory
1188 if not os.access(fpath, os.R_OK):
1189 #bb.note("Link %s -> %s" % (fpath, ftarget))
1190 os.link(ftarget, fpath)
1191
1192 # Create symlinks for all cases we were able to split symbols
1193 for file in symlinks:
1194 src = file[len(dvar):]
1195 dest = dv["libdir"] + os.path.dirname(src) + dv["dir"] + "/" + os.path.basename(src) + dv["append"]
1196 fpath = dvar + dest
1197 # Skip it if the target doesn't exist
1198 try:
1199 s = os.stat(fpath)
1200 except OSError as e:
1201 (err, strerror) = e.args
1202 if err != errno.ENOENT:
1203 raise
1204 continue
1205
1206 ltarget = symlinks[file]
1207 lpath = os.path.dirname(ltarget)
1208 lbase = os.path.basename(ltarget)
1209 ftarget = ""
1210 if lpath and lpath != ".":
1211 ftarget += lpath + dv["dir"] + "/"
1212 ftarget += lbase + dv["append"]
1213 if lpath.startswith(".."):
1214 ftarget = os.path.join("..", ftarget)
1215 bb.utils.mkdirhier(os.path.dirname(fpath))
1216 #bb.note("Symlink %s -> %s" % (fpath, ftarget))
1217 os.symlink(ftarget, fpath)
1218
1219 # Process the dv["srcdir"] if requested...
1220 # This copies and places the referenced sources for later debugging...
1221 copydebugsources(dv["srcdir"], sources, d)
1222 #
1223 # End of debug splitting
1224 #
1225
1226 #
1227 # Now lets go back over things and strip them
1228 #
1229 if (d.getVar('INHIBIT_PACKAGE_STRIP') != '1'):
1230 strip = d.getVar("STRIP")
1231 sfiles = []
1232 for file in elffiles:
1233 elf_file = int(elffiles[file])
1234 #bb.note("Strip %s" % file)
1235 sfiles.append((file, elf_file, strip))
1236 if (d.getVar('PACKAGE_STRIP_STATIC') == '1' or d.getVar('PACKAGE_DEBUG_STATIC_SPLIT') == '1'):
1237 for f in staticlibs:
1238 sfiles.append((f, 16, strip))
1239
1240 oe.utils.multiprocess_launch(oe.package.runstrip, sfiles, d)
1241
1242 # Build "minidebuginfo" and reinject it back into the stripped binaries
1243 if d.getVar('PACKAGE_MINIDEBUGINFO') == '1':
1244 oe.utils.multiprocess_launch(inject_minidebuginfo, list(elffiles), d,
1245 extraargs=(dvar, dv, d))
1246
1247 #
1248 # End of strip
1249 #
1250 os.chdir(oldcwd)
1251
1252
1253def populate_packages(d):
1254 cpath = oe.cachedpath.CachedPath()
1255
1256 workdir = d.getVar('WORKDIR')
1257 outdir = d.getVar('DEPLOY_DIR')
1258 dvar = d.getVar('PKGD')
1259 packages = d.getVar('PACKAGES').split()
1260 pn = d.getVar('PN')
1261
1262 bb.utils.mkdirhier(outdir)
1263 os.chdir(dvar)
1264
1265 autodebug = not (d.getVar("NOAUTOPACKAGEDEBUG") or False)
1266
1267 split_source_package = (d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-with-srcpkg')
1268
1269 # If debug-with-srcpkg mode is enabled then add the source package if it
1270 # doesn't exist and add the source file contents to the source package.
1271 if split_source_package:
1272 src_package_name = ('%s-src' % d.getVar('PN'))
1273 if not src_package_name in packages:
1274 packages.append(src_package_name)
1275 d.setVar('FILES:%s' % src_package_name, '/usr/src/debug')
1276
1277 # Sanity check PACKAGES for duplicates
1278 # Sanity should be moved to sanity.bbclass once we have the infrastructure
1279 package_dict = {}
1280
1281 for i, pkg in enumerate(packages):
1282 if pkg in package_dict:
1283 msg = "%s is listed in PACKAGES multiple times, this leads to packaging errors." % pkg
1284 oe.qa.handle_error("packages-list", msg, d)
1285 # Ensure the source package gets the chance to pick up the source files
1286 # before the debug package by ordering it first in PACKAGES. Whether it
1287 # actually picks up any source files is controlled by
1288 # PACKAGE_DEBUG_SPLIT_STYLE.
1289 elif pkg.endswith("-src"):
1290 package_dict[pkg] = (10, i)
1291 elif autodebug and pkg.endswith("-dbg"):
1292 package_dict[pkg] = (30, i)
1293 else:
1294 package_dict[pkg] = (50, i)
1295 packages = sorted(package_dict.keys(), key=package_dict.get)
1296 d.setVar('PACKAGES', ' '.join(packages))
1297 pkgdest = d.getVar('PKGDEST')
1298
1299 seen = []
1300
1301 # os.mkdir masks the permissions with umask so we have to unset it first
1302 oldumask = os.umask(0)
1303
1304 debug = []
1305 for root, dirs, files in cpath.walk(dvar):
1306 dir = root[len(dvar):]
1307 if not dir:
1308 dir = os.sep
1309 for f in (files + dirs):
1310 path = "." + os.path.join(dir, f)
1311 if "/.debug/" in path or "/.debug-static/" in path or path.endswith("/.debug"):
1312 debug.append(path)
1313
1314 for pkg in packages:
1315 root = os.path.join(pkgdest, pkg)
1316 bb.utils.mkdirhier(root)
1317
1318 filesvar = d.getVar('FILES:%s' % pkg) or ""
1319 if "//" in filesvar:
1320 msg = "FILES variable for package %s contains '//' which is invalid. Attempting to fix this but you should correct the metadata.\n" % pkg
1321 oe.qa.handle_error("files-invalid", msg, d)
1322 filesvar.replace("//", "/")
1323
1324 origfiles = filesvar.split()
1325 files, symlink_paths = oe.package.files_from_filevars(origfiles)
1326
1327 if autodebug and pkg.endswith("-dbg"):
1328 files.extend(debug)
1329
1330 for file in files:
1331 if (not cpath.islink(file)) and (not cpath.exists(file)):
1332 continue
1333 if file in seen:
1334 continue
1335 seen.append(file)
1336
1337 def mkdir(src, dest, p):
1338 src = os.path.join(src, p)
1339 dest = os.path.join(dest, p)
1340 fstat = cpath.stat(src)
1341 os.mkdir(dest)
1342 os.chmod(dest, fstat.st_mode)
1343 os.chown(dest, fstat.st_uid, fstat.st_gid)
1344 if p not in seen:
1345 seen.append(p)
1346 cpath.updatecache(dest)
1347
1348 def mkdir_recurse(src, dest, paths):
1349 if cpath.exists(dest + '/' + paths):
1350 return
1351 while paths.startswith("./"):
1352 paths = paths[2:]
1353 p = "."
1354 for c in paths.split("/"):
1355 p = os.path.join(p, c)
1356 if not cpath.exists(os.path.join(dest, p)):
1357 mkdir(src, dest, p)
1358
1359 if cpath.isdir(file) and not cpath.islink(file):
1360 mkdir_recurse(dvar, root, file)
1361 continue
1362
1363 mkdir_recurse(dvar, root, os.path.dirname(file))
1364 fpath = os.path.join(root,file)
1365 if not cpath.islink(file):
1366 os.link(file, fpath)
1367 continue
1368 ret = bb.utils.copyfile(file, fpath)
1369 if ret is False or ret == 0:
1370 bb.fatal("File population failed")
1371
1372 # Check if symlink paths exist
1373 for file in symlink_paths:
1374 if not os.path.exists(os.path.join(root,file)):
1375 bb.fatal("File '%s' cannot be packaged into '%s' because its "
1376 "parent directory structure does not exist. One of "
1377 "its parent directories is a symlink whose target "
1378 "directory is not included in the package." %
1379 (file, pkg))
1380
1381 os.umask(oldumask)
1382 os.chdir(workdir)
1383
1384 # Handle excluding packages with incompatible licenses
1385 package_list = []
1386 for pkg in packages:
1387 licenses = d.getVar('_exclude_incompatible-' + pkg)
1388 if licenses:
1389 msg = "Excluding %s from packaging as it has incompatible license(s): %s" % (pkg, licenses)
1390 oe.qa.handle_error("incompatible-license", msg, d)
1391 else:
1392 package_list.append(pkg)
1393 d.setVar('PACKAGES', ' '.join(package_list))
1394
1395 unshipped = []
1396 for root, dirs, files in cpath.walk(dvar):
1397 dir = root[len(dvar):]
1398 if not dir:
1399 dir = os.sep
1400 for f in (files + dirs):
1401 path = os.path.join(dir, f)
1402 if ('.' + path) not in seen:
1403 unshipped.append(path)
1404
1405 if unshipped != []:
1406 msg = pn + ": Files/directories were installed but not shipped in any package:"
1407 if "installed-vs-shipped" in (d.getVar('INSANE_SKIP:' + pn) or "").split():
1408 bb.note("Package %s skipping QA tests: installed-vs-shipped" % pn)
1409 else:
1410 for f in unshipped:
1411 msg = msg + "\n " + f
1412 msg = msg + "\nPlease set FILES such that these items are packaged. Alternatively if they are unneeded, avoid installing them or delete them within do_install.\n"
1413 msg = msg + "%s: %d installed and not shipped files." % (pn, len(unshipped))
1414 oe.qa.handle_error("installed-vs-shipped", msg, d)
1415
1416def process_fixsymlinks(pkgfiles, d):
1417 cpath = oe.cachedpath.CachedPath()
1418 pkgdest = d.getVar('PKGDEST')
1419 packages = d.getVar("PACKAGES", False).split()
1420
1421 dangling_links = {}
1422 pkg_files = {}
1423 for pkg in packages:
1424 dangling_links[pkg] = []
1425 pkg_files[pkg] = []
1426 inst_root = os.path.join(pkgdest, pkg)
1427 for path in pkgfiles[pkg]:
1428 rpath = path[len(inst_root):]
1429 pkg_files[pkg].append(rpath)
1430 rtarget = cpath.realpath(path, inst_root, True, assume_dir = True)
1431 if not cpath.lexists(rtarget):
1432 dangling_links[pkg].append(os.path.normpath(rtarget[len(inst_root):]))
1433
1434 newrdepends = {}
1435 for pkg in dangling_links:
1436 for l in dangling_links[pkg]:
1437 found = False
1438 bb.debug(1, "%s contains dangling link %s" % (pkg, l))
1439 for p in packages:
1440 if l in pkg_files[p]:
1441 found = True
1442 bb.debug(1, "target found in %s" % p)
1443 if p == pkg:
1444 break
1445 if pkg not in newrdepends:
1446 newrdepends[pkg] = []
1447 newrdepends[pkg].append(p)
1448 break
1449 if found == False:
1450 bb.note("%s contains dangling symlink to %s" % (pkg, l))
1451
1452 for pkg in newrdepends:
1453 rdepends = bb.utils.explode_dep_versions2(d.getVar('RDEPENDS:' + pkg) or "")
1454 for p in newrdepends[pkg]:
1455 if p not in rdepends:
1456 rdepends[p] = []
1457 d.setVar('RDEPENDS:' + pkg, bb.utils.join_deps(rdepends, commasep=False))
1458
1459def process_filedeps(pkgfiles, d):
1460 """
1461 Collect perfile run-time dependency metadata
1462 Output:
1463 FILERPROVIDESFLIST:pkg - list of all files w/ deps
1464 FILERPROVIDES:filepath:pkg - per file dep
1465
1466 FILERDEPENDSFLIST:pkg - list of all files w/ deps
1467 FILERDEPENDS:filepath:pkg - per file dep
1468 """
1469 if d.getVar('SKIP_FILEDEPS') == '1':
1470 return
1471
1472 pkgdest = d.getVar('PKGDEST')
1473 packages = d.getVar('PACKAGES')
1474 rpmdeps = d.getVar('RPMDEPS')
1475
1476 def chunks(files, n):
1477 return [files[i:i+n] for i in range(0, len(files), n)]
1478
1479 pkglist = []
1480 for pkg in packages.split():
1481 if d.getVar('SKIP_FILEDEPS:' + pkg) == '1':
1482 continue
1483 if pkg.endswith('-dbg') or pkg.endswith('-doc') or pkg.find('-locale-') != -1 or pkg.find('-localedata-') != -1 or pkg.find('-gconv-') != -1 or pkg.find('-charmap-') != -1 or pkg.startswith('kernel-module-') or pkg.endswith('-src'):
1484 continue
1485 for files in chunks(pkgfiles[pkg], 100):
1486 pkglist.append((pkg, files, rpmdeps, pkgdest))
1487
1488 processed = oe.utils.multiprocess_launch(oe.package.filedeprunner, pkglist, d)
1489
1490 provides_files = {}
1491 requires_files = {}
1492
1493 for result in processed:
1494 (pkg, provides, requires) = result
1495
1496 if pkg not in provides_files:
1497 provides_files[pkg] = []
1498 if pkg not in requires_files:
1499 requires_files[pkg] = []
1500
1501 for file in sorted(provides):
1502 provides_files[pkg].append(file)
1503 key = "FILERPROVIDES:" + file + ":" + pkg
1504 d.appendVar(key, " " + " ".join(provides[file]))
1505
1506 for file in sorted(requires):
1507 requires_files[pkg].append(file)
1508 key = "FILERDEPENDS:" + file + ":" + pkg
1509 d.appendVar(key, " " + " ".join(requires[file]))
1510
1511 for pkg in requires_files:
1512 d.setVar("FILERDEPENDSFLIST:" + pkg, " ".join(sorted(requires_files[pkg])))
1513 for pkg in provides_files:
1514 d.setVar("FILERPROVIDESFLIST:" + pkg, " ".join(sorted(provides_files[pkg])))
1515
1516def process_shlibs(pkgfiles, d):
1517 cpath = oe.cachedpath.CachedPath()
1518
1519 exclude_shlibs = d.getVar('EXCLUDE_FROM_SHLIBS', False)
1520 if exclude_shlibs:
1521 bb.note("not generating shlibs")
1522 return
1523
1524 lib_re = re.compile(r"^.*\.so")
1525 libdir_re = re.compile(r".*/%s$" % d.getVar('baselib'))
1526
1527 packages = d.getVar('PACKAGES')
1528
1529 shlib_pkgs = []
1530 exclusion_list = d.getVar("EXCLUDE_PACKAGES_FROM_SHLIBS")
1531 if exclusion_list:
1532 for pkg in packages.split():
1533 if pkg not in exclusion_list.split():
1534 shlib_pkgs.append(pkg)
1535 else:
1536 bb.note("not generating shlibs for %s" % pkg)
1537 else:
1538 shlib_pkgs = packages.split()
1539
1540 hostos = d.getVar('HOST_OS')
1541
1542 workdir = d.getVar('WORKDIR')
1543
1544 ver = d.getVar('PKGV')
1545 if not ver:
1546 msg = "PKGV not defined"
1547 oe.qa.handle_error("pkgv-undefined", msg, d)
1548 return
1549
1550 pkgdest = d.getVar('PKGDEST')
1551
1552 shlibswork_dir = d.getVar('SHLIBSWORKDIR')
1553
1554 def linux_so(file, pkg, pkgver, d):
1555 needs_ldconfig = False
1556 needed = set()
1557 sonames = set()
1558 renames = []
1559 ldir = os.path.dirname(file).replace(pkgdest + "/" + pkg, '')
Patrick Williams8e7b46e2023-05-01 14:19:06 -05001560 cmd = d.getVar('OBJDUMP') + " -p " + shlex.quote(file) + " 2>/dev/null"
Andrew Geissler517393d2023-01-13 08:55:19 -06001561 fd = os.popen(cmd)
1562 lines = fd.readlines()
1563 fd.close()
1564 rpath = tuple()
1565 for l in lines:
1566 m = re.match(r"\s+RPATH\s+([^\s]*)", l)
1567 if m:
1568 rpaths = m.group(1).replace("$ORIGIN", ldir).split(":")
1569 rpath = tuple(map(os.path.normpath, rpaths))
1570 for l in lines:
1571 m = re.match(r"\s+NEEDED\s+([^\s]*)", l)
1572 if m:
1573 dep = m.group(1)
1574 if dep not in needed:
1575 needed.add((dep, file, rpath))
1576 m = re.match(r"\s+SONAME\s+([^\s]*)", l)
1577 if m:
1578 this_soname = m.group(1)
1579 prov = (this_soname, ldir, pkgver)
1580 if not prov in sonames:
1581 # if library is private (only used by package) then do not build shlib for it
1582 if not private_libs or len([i for i in private_libs if fnmatch.fnmatch(this_soname, i)]) == 0:
1583 sonames.add(prov)
1584 if libdir_re.match(os.path.dirname(file)):
1585 needs_ldconfig = True
1586 if needs_ldconfig and snap_symlinks and (os.path.basename(file) != this_soname):
1587 renames.append((file, os.path.join(os.path.dirname(file), this_soname)))
1588 return (needs_ldconfig, needed, sonames, renames)
1589
1590 def darwin_so(file, needed, sonames, renames, pkgver):
1591 if not os.path.exists(file):
1592 return
1593 ldir = os.path.dirname(file).replace(pkgdest + "/" + pkg, '')
1594
1595 def get_combinations(base):
1596 #
1597 # Given a base library name, find all combinations of this split by "." and "-"
1598 #
1599 combos = []
1600 options = base.split(".")
1601 for i in range(1, len(options) + 1):
1602 combos.append(".".join(options[0:i]))
1603 options = base.split("-")
1604 for i in range(1, len(options) + 1):
1605 combos.append("-".join(options[0:i]))
1606 return combos
1607
1608 if (file.endswith('.dylib') or file.endswith('.so')) and not pkg.endswith('-dev') and not pkg.endswith('-dbg') and not pkg.endswith('-src'):
1609 # Drop suffix
1610 name = os.path.basename(file).rsplit(".",1)[0]
1611 # Find all combinations
1612 combos = get_combinations(name)
1613 for combo in combos:
1614 if not combo in sonames:
1615 prov = (combo, ldir, pkgver)
1616 sonames.add(prov)
1617 if file.endswith('.dylib') or file.endswith('.so'):
1618 rpath = []
1619 p = subprocess.Popen([d.expand("${HOST_PREFIX}otool"), '-l', file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1620 out, err = p.communicate()
1621 # If returned successfully, process stdout for results
1622 if p.returncode == 0:
1623 for l in out.split("\n"):
1624 l = l.strip()
1625 if l.startswith('path '):
1626 rpath.append(l.split()[1])
1627
1628 p = subprocess.Popen([d.expand("${HOST_PREFIX}otool"), '-L', file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1629 out, err = p.communicate()
1630 # If returned successfully, process stdout for results
1631 if p.returncode == 0:
1632 for l in out.split("\n"):
1633 l = l.strip()
1634 if not l or l.endswith(":"):
1635 continue
1636 if "is not an object file" in l:
1637 continue
1638 name = os.path.basename(l.split()[0]).rsplit(".", 1)[0]
1639 if name and name not in needed[pkg]:
1640 needed[pkg].add((name, file, tuple()))
1641
1642 def mingw_dll(file, needed, sonames, renames, pkgver):
1643 if not os.path.exists(file):
1644 return
1645
1646 if file.endswith(".dll"):
1647 # assume all dlls are shared objects provided by the package
1648 sonames.add((os.path.basename(file), os.path.dirname(file).replace(pkgdest + "/" + pkg, ''), pkgver))
1649
1650 if (file.endswith(".dll") or file.endswith(".exe")):
1651 # use objdump to search for "DLL Name: .*\.dll"
1652 p = subprocess.Popen([d.expand("${HOST_PREFIX}objdump"), "-p", file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1653 out, err = p.communicate()
1654 # process the output, grabbing all .dll names
1655 if p.returncode == 0:
1656 for m in re.finditer(r"DLL Name: (.*?\.dll)$", out.decode(), re.MULTILINE | re.IGNORECASE):
1657 dllname = m.group(1)
1658 if dllname:
1659 needed[pkg].add((dllname, file, tuple()))
1660
1661 if d.getVar('PACKAGE_SNAP_LIB_SYMLINKS') == "1":
1662 snap_symlinks = True
1663 else:
1664 snap_symlinks = False
1665
1666 needed = {}
1667
1668 shlib_provider = oe.package.read_shlib_providers(d)
1669
1670 for pkg in shlib_pkgs:
1671 private_libs = d.getVar('PRIVATE_LIBS:' + pkg) or d.getVar('PRIVATE_LIBS') or ""
1672 private_libs = private_libs.split()
1673 needs_ldconfig = False
1674 bb.debug(2, "calculating shlib provides for %s" % pkg)
1675
1676 pkgver = d.getVar('PKGV:' + pkg)
1677 if not pkgver:
1678 pkgver = d.getVar('PV_' + pkg)
1679 if not pkgver:
1680 pkgver = ver
1681
1682 needed[pkg] = set()
1683 sonames = set()
1684 renames = []
1685 linuxlist = []
1686 for file in pkgfiles[pkg]:
1687 soname = None
1688 if cpath.islink(file):
1689 continue
1690 if hostos == "darwin" or hostos == "darwin8":
1691 darwin_so(file, needed, sonames, renames, pkgver)
1692 elif hostos.startswith("mingw"):
1693 mingw_dll(file, needed, sonames, renames, pkgver)
1694 elif os.access(file, os.X_OK) or lib_re.match(file):
1695 linuxlist.append(file)
1696
1697 if linuxlist:
1698 results = oe.utils.multiprocess_launch(linux_so, linuxlist, d, extraargs=(pkg, pkgver, d))
1699 for r in results:
1700 ldconfig = r[0]
1701 needed[pkg] |= r[1]
1702 sonames |= r[2]
1703 renames.extend(r[3])
1704 needs_ldconfig = needs_ldconfig or ldconfig
1705
1706 for (old, new) in renames:
1707 bb.note("Renaming %s to %s" % (old, new))
1708 bb.utils.rename(old, new)
1709 pkgfiles[pkg].remove(old)
1710
1711 shlibs_file = os.path.join(shlibswork_dir, pkg + ".list")
1712 if len(sonames):
1713 with open(shlibs_file, 'w') as fd:
1714 for s in sorted(sonames):
1715 if s[0] in shlib_provider and s[1] in shlib_provider[s[0]]:
1716 (old_pkg, old_pkgver) = shlib_provider[s[0]][s[1]]
1717 if old_pkg != pkg:
1718 bb.warn('%s-%s was registered as shlib provider for %s, changing it to %s-%s because it was built later' % (old_pkg, old_pkgver, s[0], pkg, pkgver))
1719 bb.debug(1, 'registering %s-%s as shlib provider for %s' % (pkg, pkgver, s[0]))
1720 fd.write(s[0] + ':' + s[1] + ':' + s[2] + '\n')
1721 if s[0] not in shlib_provider:
1722 shlib_provider[s[0]] = {}
1723 shlib_provider[s[0]][s[1]] = (pkg, pkgver)
1724 if needs_ldconfig:
1725 bb.debug(1, 'adding ldconfig call to postinst for %s' % pkg)
1726 postinst = d.getVar('pkg_postinst:%s' % pkg)
1727 if not postinst:
1728 postinst = '#!/bin/sh\n'
1729 postinst += d.getVar('ldconfig_postinst_fragment')
1730 d.setVar('pkg_postinst:%s' % pkg, postinst)
1731 bb.debug(1, 'LIBNAMES: pkg %s sonames %s' % (pkg, sonames))
1732
1733 assumed_libs = d.getVar('ASSUME_SHLIBS')
1734 if assumed_libs:
1735 libdir = d.getVar("libdir")
1736 for e in assumed_libs.split():
1737 l, dep_pkg = e.split(":")
1738 lib_ver = None
1739 dep_pkg = dep_pkg.rsplit("_", 1)
1740 if len(dep_pkg) == 2:
1741 lib_ver = dep_pkg[1]
1742 dep_pkg = dep_pkg[0]
1743 if l not in shlib_provider:
1744 shlib_provider[l] = {}
1745 shlib_provider[l][libdir] = (dep_pkg, lib_ver)
1746
1747 libsearchpath = [d.getVar('libdir'), d.getVar('base_libdir')]
1748
1749 for pkg in shlib_pkgs:
1750 bb.debug(2, "calculating shlib requirements for %s" % pkg)
1751
1752 private_libs = d.getVar('PRIVATE_LIBS:' + pkg) or d.getVar('PRIVATE_LIBS') or ""
1753 private_libs = private_libs.split()
1754
1755 deps = list()
1756 for n in needed[pkg]:
1757 # if n is in private libraries, don't try to search provider for it
1758 # this could cause problem in case some abc.bb provides private
1759 # /opt/abc/lib/libfoo.so.1 and contains /usr/bin/abc depending on system library libfoo.so.1
1760 # but skipping it is still better alternative than providing own
1761 # version and then adding runtime dependency for the same system library
1762 if private_libs and len([i for i in private_libs if fnmatch.fnmatch(n[0], i)]) > 0:
1763 bb.debug(2, '%s: Dependency %s covered by PRIVATE_LIBS' % (pkg, n[0]))
1764 continue
1765 if n[0] in shlib_provider.keys():
1766 shlib_provider_map = shlib_provider[n[0]]
1767 matches = set()
1768 for p in itertools.chain(list(n[2]), sorted(shlib_provider_map.keys()), libsearchpath):
1769 if p in shlib_provider_map:
1770 matches.add(p)
1771 if len(matches) > 1:
1772 matchpkgs = ', '.join([shlib_provider_map[match][0] for match in matches])
1773 bb.error("%s: Multiple shlib providers for %s: %s (used by files: %s)" % (pkg, n[0], matchpkgs, n[1]))
1774 elif len(matches) == 1:
1775 (dep_pkg, ver_needed) = shlib_provider_map[matches.pop()]
1776
1777 bb.debug(2, '%s: Dependency %s requires package %s (used by files: %s)' % (pkg, n[0], dep_pkg, n[1]))
1778
1779 if dep_pkg == pkg:
1780 continue
1781
1782 if ver_needed:
1783 dep = "%s (>= %s)" % (dep_pkg, ver_needed)
1784 else:
1785 dep = dep_pkg
1786 if not dep in deps:
1787 deps.append(dep)
1788 continue
1789 bb.note("Couldn't find shared library provider for %s, used by files: %s" % (n[0], n[1]))
1790
1791 deps_file = os.path.join(pkgdest, pkg + ".shlibdeps")
1792 if os.path.exists(deps_file):
1793 os.remove(deps_file)
1794 if deps:
1795 with open(deps_file, 'w') as fd:
1796 for dep in sorted(deps):
1797 fd.write(dep + '\n')
1798
1799def process_pkgconfig(pkgfiles, d):
1800 packages = d.getVar('PACKAGES')
1801 workdir = d.getVar('WORKDIR')
1802 pkgdest = d.getVar('PKGDEST')
1803
1804 shlibs_dirs = d.getVar('SHLIBSDIRS').split()
1805 shlibswork_dir = d.getVar('SHLIBSWORKDIR')
1806
1807 pc_re = re.compile(r'(.*)\.pc$')
1808 var_re = re.compile(r'(.*)=(.*)')
1809 field_re = re.compile(r'(.*): (.*)')
1810
1811 pkgconfig_provided = {}
1812 pkgconfig_needed = {}
1813 for pkg in packages.split():
1814 pkgconfig_provided[pkg] = []
1815 pkgconfig_needed[pkg] = []
1816 for file in sorted(pkgfiles[pkg]):
1817 m = pc_re.match(file)
1818 if m:
1819 pd = bb.data.init()
1820 name = m.group(1)
1821 pkgconfig_provided[pkg].append(os.path.basename(name))
1822 if not os.access(file, os.R_OK):
1823 continue
1824 with open(file, 'r') as f:
1825 lines = f.readlines()
1826 for l in lines:
Andrew Geissler517393d2023-01-13 08:55:19 -06001827 m = field_re.match(l)
1828 if m:
1829 hdr = m.group(1)
1830 exp = pd.expand(m.group(2))
1831 if hdr == 'Requires':
1832 pkgconfig_needed[pkg] += exp.replace(',', ' ').split()
Andrew Geisslerfc113ea2023-03-31 09:59:46 -05001833 continue
1834 m = var_re.match(l)
1835 if m:
1836 name = m.group(1)
1837 val = m.group(2)
1838 pd.setVar(name, pd.expand(val))
Andrew Geissler517393d2023-01-13 08:55:19 -06001839
1840 for pkg in packages.split():
1841 pkgs_file = os.path.join(shlibswork_dir, pkg + ".pclist")
1842 if pkgconfig_provided[pkg] != []:
1843 with open(pkgs_file, 'w') as f:
1844 for p in sorted(pkgconfig_provided[pkg]):
1845 f.write('%s\n' % p)
1846
1847 # Go from least to most specific since the last one found wins
1848 for dir in reversed(shlibs_dirs):
1849 if not os.path.exists(dir):
1850 continue
1851 for file in sorted(os.listdir(dir)):
1852 m = re.match(r'^(.*)\.pclist$', file)
1853 if m:
1854 pkg = m.group(1)
1855 with open(os.path.join(dir, file)) as fd:
1856 lines = fd.readlines()
1857 pkgconfig_provided[pkg] = []
1858 for l in lines:
1859 pkgconfig_provided[pkg].append(l.rstrip())
1860
1861 for pkg in packages.split():
1862 deps = []
1863 for n in pkgconfig_needed[pkg]:
1864 found = False
1865 for k in pkgconfig_provided.keys():
1866 if n in pkgconfig_provided[k]:
1867 if k != pkg and not (k in deps):
1868 deps.append(k)
1869 found = True
1870 if found == False:
1871 bb.note("couldn't find pkgconfig module '%s' in any package" % n)
1872 deps_file = os.path.join(pkgdest, pkg + ".pcdeps")
1873 if len(deps):
1874 with open(deps_file, 'w') as fd:
1875 for dep in deps:
1876 fd.write(dep + '\n')
1877
1878def read_libdep_files(d):
1879 pkglibdeps = {}
1880 packages = d.getVar('PACKAGES').split()
1881 for pkg in packages:
1882 pkglibdeps[pkg] = {}
1883 for extension in ".shlibdeps", ".pcdeps", ".clilibdeps":
1884 depsfile = d.expand("${PKGDEST}/" + pkg + extension)
1885 if os.access(depsfile, os.R_OK):
1886 with open(depsfile) as fd:
1887 lines = fd.readlines()
1888 for l in lines:
1889 l.rstrip()
1890 deps = bb.utils.explode_dep_versions2(l)
1891 for dep in deps:
1892 if not dep in pkglibdeps[pkg]:
1893 pkglibdeps[pkg][dep] = deps[dep]
1894 return pkglibdeps
1895
1896def process_depchains(pkgfiles, d):
1897 """
1898 For a given set of prefix and postfix modifiers, make those packages
1899 RRECOMMENDS on the corresponding packages for its RDEPENDS.
1900
1901 Example: If package A depends upon package B, and A's .bb emits an
1902 A-dev package, this would make A-dev Recommends: B-dev.
1903
1904 If only one of a given suffix is specified, it will take the RRECOMMENDS
1905 based on the RDEPENDS of *all* other packages. If more than one of a given
1906 suffix is specified, its will only use the RDEPENDS of the single parent
1907 package.
1908 """
1909
1910 packages = d.getVar('PACKAGES')
1911 postfixes = (d.getVar('DEPCHAIN_POST') or '').split()
1912 prefixes = (d.getVar('DEPCHAIN_PRE') or '').split()
1913
1914 def pkg_adddeprrecs(pkg, base, suffix, getname, depends, d):
1915
1916 #bb.note('depends for %s is %s' % (base, depends))
1917 rreclist = bb.utils.explode_dep_versions2(d.getVar('RRECOMMENDS:' + pkg) or "")
1918
1919 for depend in sorted(depends):
1920 if depend.find('-native') != -1 or depend.find('-cross') != -1 or depend.startswith('virtual/'):
1921 #bb.note("Skipping %s" % depend)
1922 continue
1923 if depend.endswith('-dev'):
1924 depend = depend[:-4]
1925 if depend.endswith('-dbg'):
1926 depend = depend[:-4]
1927 pkgname = getname(depend, suffix)
1928 #bb.note("Adding %s for %s" % (pkgname, depend))
1929 if pkgname not in rreclist and pkgname != pkg:
1930 rreclist[pkgname] = []
1931
1932 #bb.note('setting: RRECOMMENDS:%s=%s' % (pkg, ' '.join(rreclist)))
1933 d.setVar('RRECOMMENDS:%s' % pkg, bb.utils.join_deps(rreclist, commasep=False))
1934
1935 def pkg_addrrecs(pkg, base, suffix, getname, rdepends, d):
1936
1937 #bb.note('rdepends for %s is %s' % (base, rdepends))
1938 rreclist = bb.utils.explode_dep_versions2(d.getVar('RRECOMMENDS:' + pkg) or "")
1939
1940 for depend in sorted(rdepends):
1941 if depend.find('virtual-locale-') != -1:
1942 #bb.note("Skipping %s" % depend)
1943 continue
1944 if depend.endswith('-dev'):
1945 depend = depend[:-4]
1946 if depend.endswith('-dbg'):
1947 depend = depend[:-4]
1948 pkgname = getname(depend, suffix)
1949 #bb.note("Adding %s for %s" % (pkgname, depend))
1950 if pkgname not in rreclist and pkgname != pkg:
1951 rreclist[pkgname] = []
1952
1953 #bb.note('setting: RRECOMMENDS:%s=%s' % (pkg, ' '.join(rreclist)))
1954 d.setVar('RRECOMMENDS:%s' % pkg, bb.utils.join_deps(rreclist, commasep=False))
1955
1956 def add_dep(list, dep):
1957 if dep not in list:
1958 list.append(dep)
1959
1960 depends = []
1961 for dep in bb.utils.explode_deps(d.getVar('DEPENDS') or ""):
1962 add_dep(depends, dep)
1963
1964 rdepends = []
1965 for pkg in packages.split():
1966 for dep in bb.utils.explode_deps(d.getVar('RDEPENDS:' + pkg) or ""):
1967 add_dep(rdepends, dep)
1968
1969 #bb.note('rdepends is %s' % rdepends)
1970
1971 def post_getname(name, suffix):
1972 return '%s%s' % (name, suffix)
1973 def pre_getname(name, suffix):
1974 return '%s%s' % (suffix, name)
1975
1976 pkgs = {}
1977 for pkg in packages.split():
1978 for postfix in postfixes:
1979 if pkg.endswith(postfix):
1980 if not postfix in pkgs:
1981 pkgs[postfix] = {}
1982 pkgs[postfix][pkg] = (pkg[:-len(postfix)], post_getname)
1983
1984 for prefix in prefixes:
1985 if pkg.startswith(prefix):
1986 if not prefix in pkgs:
1987 pkgs[prefix] = {}
1988 pkgs[prefix][pkg] = (pkg[:-len(prefix)], pre_getname)
1989
1990 if "-dbg" in pkgs:
1991 pkglibdeps = read_libdep_files(d)
1992 pkglibdeplist = []
1993 for pkg in pkglibdeps:
1994 for k in pkglibdeps[pkg]:
1995 add_dep(pkglibdeplist, k)
1996 dbgdefaultdeps = ((d.getVar('DEPCHAIN_DBGDEFAULTDEPS') == '1') or (bb.data.inherits_class('packagegroup', d)))
1997
1998 for suffix in pkgs:
1999 for pkg in pkgs[suffix]:
2000 if d.getVarFlag('RRECOMMENDS:' + pkg, 'nodeprrecs'):
2001 continue
2002 (base, func) = pkgs[suffix][pkg]
2003 if suffix == "-dev":
2004 pkg_adddeprrecs(pkg, base, suffix, func, depends, d)
2005 elif suffix == "-dbg":
2006 if not dbgdefaultdeps:
2007 pkg_addrrecs(pkg, base, suffix, func, pkglibdeplist, d)
2008 continue
2009 if len(pkgs[suffix]) == 1:
2010 pkg_addrrecs(pkg, base, suffix, func, rdepends, d)
2011 else:
2012 rdeps = []
2013 for dep in bb.utils.explode_deps(d.getVar('RDEPENDS:' + base) or ""):
2014 add_dep(rdeps, dep)
2015 pkg_addrrecs(pkg, base, suffix, func, rdeps, d)