angstrom: prefer the git version of tslib
[openembedded.git] / classes / package.bbclass
blob2b98049b71afeb6c597ce9ee5cd35b1d0b9cab07
2 # General packaging help functions
5 PKGD    = "${WORKDIR}/package"
6 PKGDEST = "${WORKDIR}/packages-split"
8 PKGV    ?= "${PV}"
9 PKGR    ?= "${PR}${DISTRO_PR}"
11 EXTENDPKGEVER = "${@['','${PKGE\x7d:'][bb.data.getVar('PKGE',d,1) > 0]}"
12 EXTENDPKGV ?= "${EXTENDPKGEVER}${PKGV}-${PKGR}"
14 def legitimize_package_name(s):
15         """
16         Make sure package names are legitimate strings
17         """
18         import re
20         def fixutf(m):
21                 cp = m.group(1)
22                 if cp:
23                         return ('\u%s' % cp).decode('unicode_escape').encode('utf-8')
25         # Handle unicode codepoints encoded as <U0123>, as in glibc locale files.
26         s = re.sub('<U([0-9A-Fa-f]{1,4})>', fixutf, s)
28         # Remaining package name validity fixes
29         return s.lower().replace('_', '-').replace('@', '+').replace(',', '+').replace('/', '-')
31 def do_split_packages(d, root, file_regex, output_pattern, description, postinst=None, recursive=False, hook=None, extra_depends=None, aux_files_pattern=None, postrm=None, allow_dirs=False, prepend=False, match_path=False, aux_files_pattern_verbatim=None, allow_links=False):
32         """
33         Used in .bb files to split up dynamically generated subpackages of a 
34         given package, usually plugins or modules.
35         """
37         dvar = bb.data.getVar('PKGD', d, True)
39         packages = bb.data.getVar('PACKAGES', d, True).split()
41         if postinst:
42                 postinst = '#!/bin/sh\n' + postinst + '\n'
43         if postrm:
44                 postrm = '#!/bin/sh\n' + postrm + '\n'
45         if not recursive:
46                 objs = os.listdir(dvar + root)
47         else:
48                 objs = []
49                 for walkroot, dirs, files in os.walk(dvar + root):
50                         for file in files:
51                                 relpath = os.path.join(walkroot, file).replace(dvar + root + '/', '', 1)
52                                 if relpath:
53                                         objs.append(relpath)
55         if extra_depends == None:
56                 # This is *really* broken
57                 mainpkg = packages[0]
58                 # At least try and patch it up I guess...
59                 if mainpkg.find('-dbg'):
60                         mainpkg = mainpkg.replace('-dbg', '')
61                 if mainpkg.find('-dev'):
62                         mainpkg = mainpkg.replace('-dev', '')
63                 extra_depends = mainpkg
65         for o in objs:
66                 import re, stat
67                 if match_path:
68                         m = re.match(file_regex, o)
69                 else:
70                         m = re.match(file_regex, os.path.basename(o))
71                 
72                 if not m:
73                         continue
74                 f = os.path.join(dvar + root, o)
75                 mode = os.lstat(f).st_mode
76                 if not (stat.S_ISREG(mode) or (allow_links and stat.S_ISLNK(mode)) or (allow_dirs and stat.S_ISDIR(mode))):
77                         continue
78                 on = legitimize_package_name(m.group(1))
79                 pkg = output_pattern % on
80                 if not pkg in packages:
81                         if prepend:
82                                 packages = [pkg] + packages
83                         else:
84                                 packages.append(pkg)
85                         the_files = [os.path.join(root, o)]
86                         if aux_files_pattern:
87                                 if type(aux_files_pattern) is list:
88                                         for fp in aux_files_pattern:
89                                                 the_files.append(fp % on)       
90                                 else:
91                                         the_files.append(aux_files_pattern % on)
92                         if aux_files_pattern_verbatim:
93                                 if type(aux_files_pattern_verbatim) is list:
94                                         for fp in aux_files_pattern_verbatim:
95                                                 the_files.append(fp % m.group(1))       
96                                 else:
97                                         the_files.append(aux_files_pattern_verbatim % m.group(1))
98                         bb.data.setVar('FILES_' + pkg, " ".join(the_files), d)
99                         if extra_depends != '':
100                                 the_depends = bb.data.getVar('RDEPENDS_' + pkg, d, True)
101                                 if the_depends:
102                                         the_depends = '%s %s' % (the_depends, extra_depends)
103                                 else:
104                                         the_depends = extra_depends
105                                 bb.data.setVar('RDEPENDS_' + pkg, the_depends, d)
106                         bb.data.setVar('DESCRIPTION_' + pkg, description % on, d)
107                         if postinst:
108                                 bb.data.setVar('pkg_postinst_' + pkg, postinst, d)
109                         if postrm:
110                                 bb.data.setVar('pkg_postrm_' + pkg, postrm, d)
111                 else:
112                         oldfiles = bb.data.getVar('FILES_' + pkg, d, True)
113                         if not oldfiles:
114                                 bb.fatal("Package '%s' exists but has no files" % pkg)
115                         bb.data.setVar('FILES_' + pkg, oldfiles + " " + os.path.join(root, o), d)
116                 if callable(hook):
117                         hook(f, pkg, file_regex, output_pattern, m.group(1))
119         bb.data.setVar('PACKAGES', ' '.join(packages), d)
121 PACKAGE_DEPENDS += "file-native"
123 def package_stash_hook(func, name, d):
124         import bb, os.path
125         body = bb.data.getVar(func, d, True)
126         pn = bb.data.getVar('PN', d, True)
127         staging = bb.data.getVar('PKGDATA_DIR', d, True)
128         dirname = os.path.join(staging, 'hooks', name)
129         bb.mkdirhier(dirname)
130         fn = os.path.join(dirname, pn)
131         f = open(fn, 'w')
132         f.write("python () {\n");
133         f.write(body);
134         f.write("}\n");
135         f.close()
137 python () {
138     if bb.data.getVar('PACKAGES', d, True) != '':
139         deps = bb.data.getVarFlag('do_package', 'depends', d) or ""
140         for dep in (bb.data.getVar('PACKAGE_DEPENDS', d, True) or "").split():
141             deps += " %s:do_populate_sysroot" % dep
142         bb.data.setVarFlag('do_package', 'depends', deps, d)
144         deps = (bb.data.getVarFlag('do_package', 'deptask', d) or "").split()
145         # shlibs requires any DEPENDS to have already packaged for the *.list files
146         deps.append("do_package")
147         bb.data.setVarFlag('do_package', 'deptask', " ".join(deps), d)
150 def runstrip(file, d):
151     # Function to strip a single file, called from populate_packages below
152     # A working 'file' (one which works on the target architecture)
153     # is necessary for this stuff to work, hence the addition to do_package[depends]
155     import commands, stat
157     pathprefix = "export PATH=%s; " % bb.data.getVar('PATH', d, True)
159     ret, result = commands.getstatusoutput("%sfile '%s'" % (pathprefix, file))
161     if ret:
162         bb.error("runstrip: 'file %s' failed (forced strip)" % file)
164     if "not stripped" not in result:
165         bb.debug(1, "runstrip: skip %s" % file)
166         return 0
168     # If the file is in a .debug directory it was already stripped,
169     # don't do it again...
170     if os.path.dirname(file).endswith(".debug"):
171         bb.debug(2, "Already ran strip on %s" % file)
172         return 0
174     strip = bb.data.getVar("STRIP", d, True)
175     objcopy = bb.data.getVar("OBJCOPY", d, True)
177     newmode = None
178     if not os.access(file, os.W_OK):
179         origmode = os.stat(file)[stat.ST_MODE]
180         newmode = origmode | stat.S_IWRITE
181         os.chmod(file, newmode)
183     extraflags = ""
184     if ".so" in file and "shared" in result:
185         extraflags = "--remove-section=.comment --remove-section=.note --strip-unneeded"
186     elif "shared" in result or "executable" in result:
187         extraflags = "--remove-section=.comment --remove-section=.note"
188     elif file.endswith(".a"):
189         extraflags = "--remove-section=.comment --strip-debug"
192     bb.mkdirhier(os.path.join(os.path.dirname(file), ".debug"))
193     debugfile=os.path.join(os.path.dirname(file), ".debug", os.path.basename(file))
195     stripcmd = "'%s' %s '%s'" % (strip, extraflags, file)
196     bb.debug(1, "runstrip: %s" % stripcmd)
198     os.system("%s'%s' --only-keep-debug '%s' '%s'" % (pathprefix, objcopy, file, debugfile))
199     ret = os.system("%s%s" % (pathprefix, stripcmd))
200     if (bb.data.getVar('PACKAGE_STRIP', d, True) != 'full'):
201         os.system("%s'%s' --add-gnu-debuglink='%s' '%s'" % (pathprefix, objcopy, debugfile, file))
203     if newmode:
204         os.chmod(file, origmode)
206     if ret:
207         bb.error("runstrip: '%s' strip command failed" % stripcmd)
209     return 1
211 PACKAGESTRIPFUNCS += "do_runstrip"
212 python do_runstrip() {
213         import stat
215         dvar = bb.data.getVar('PKGD', d, True)
216         def isexec(path):
217                 try:
218                         s = os.stat(path)
219                 except (os.error, AttributeError):
220                         return 0
221                 return (s[stat.ST_MODE] & stat.S_IEXEC)
223         for root, dirs, files in os.walk(dvar):
224                 for f in files:
225                         file = os.path.join(root, f)
226                         if not os.path.islink(file) and not os.path.isdir(file) and isexec(file):
227                                 runstrip(file, d)
231 def write_package_md5sums (root, outfile, ignorepaths):
232     # For each regular file under root, writes an md5sum to outfile.
233     # With thanks to patch.bbclass.
234     import bb, os
236     try:
237         # Python 2.5+
238         import hashlib
239         ctor = hashlib.md5
240     except ImportError:
241         import md5
242         ctor = md5.new
244     outf = file(outfile, 'w')
246     # Each output line looks like: "<hex...>  <filename without leading slash>"
247     striplen = len(root)
248     if not root.endswith('/'):
249         striplen += 1
251     for walkroot, dirs, files in os.walk(root):
252         # Skip e.g. the DEBIAN directory
253         if walkroot[striplen:] in ignorepaths:
254             dirs[:] = []
255             continue
257         for name in files:
258             fullpath = os.path.join(walkroot, name)
259             if os.path.islink(fullpath) or (not os.path.isfile(fullpath)):
260                 continue
262             m = ctor()
263             f = file(fullpath, 'rb')
264             while True:
265                 d = f.read(8192)
266                 if not d:
267                     break
268                 m.update(d)
269             f.close()
271             print >> outf, "%s  %s" % (m.hexdigest(), fullpath[striplen:])
273     outf.close()
277 # Package data handling routines
280 def get_package_mapping (pkg, d):
281         import oe.packagedata
283         data = oe.packagedata.read_subpkgdata(pkg, d)
284         key = "PKG_%s" % pkg
286         if key in data:
287                 return data[key]
289         return pkg
291 def runtime_mapping_rename (varname, d):
292         #bb.note("%s before: %s" % (varname, bb.data.getVar(varname, d, True))) 
294         new_depends = []
295         for depend in explode_deps(bb.data.getVar(varname, d, True) or ""):
296                 # Have to be careful with any version component of the depend
297                 split_depend = depend.split(' (')
298                 new_depend = get_package_mapping(split_depend[0].strip(), d)
299                 if len(split_depend) > 1:
300                         new_depends.append("%s (%s" % (new_depend, split_depend[1]))
301                 else:
302                         new_depends.append(new_depend)
304         bb.data.setVar(varname, " ".join(new_depends) or None, d)
306         #bb.note("%s after: %s" % (varname, bb.data.getVar(varname, d, True)))
309 # Package functions suitable for inclusion in PACKAGEFUNCS
312 python package_do_split_locales() {
313         if (bb.data.getVar('PACKAGE_NO_LOCALE', d, True) == '1'):
314                 bb.debug(1, "package requested not splitting locales")
315                 return
317         packages = (bb.data.getVar('PACKAGES', d, True) or "").split()
319         datadir = bb.data.getVar('datadir', d, True)
320         if not datadir:
321                 bb.note("datadir not defined")
322                 return
324         dvar = bb.data.getVar('PKGD', d, True)
325         pn = bb.data.getVar('PN', d, True)
327         if pn + '-locale' in packages:
328                 packages.remove(pn + '-locale')
330         localedir = os.path.join(dvar + datadir, 'locale')
332         if not os.path.isdir(localedir):
333                 bb.debug(1, "No locale files in this package")
334                 return
336         locales = os.listdir(localedir)
338         # This is *really* broken
339         mainpkg = packages[0]
340         # At least try and patch it up I guess...
341         if mainpkg.find('-dbg'):
342                 mainpkg = mainpkg.replace('-dbg', '')
343         if mainpkg.find('-dev'):
344                 mainpkg = mainpkg.replace('-dev', '')
346         for l in locales:
347                 ln = legitimize_package_name(l)
348                 pkg = pn + '-locale-' + ln
349                 packages.append(pkg)
350                 bb.data.setVar('FILES_' + pkg, os.path.join(datadir, 'locale', l), d)
351                 bb.data.setVar('RDEPENDS_' + pkg, '%s virtual-locale-%s' % (mainpkg, ln), d)
352                 bb.data.setVar('RPROVIDES_' + pkg, '%s-locale %s-translation' % (pn, ln), d)
353                 bb.data.setVar('DESCRIPTION_' + pkg, '%s translation for %s' % (l, pn), d)
355         bb.data.setVar('PACKAGES', ' '.join(packages), d)
358 python perform_packagecopy () {
359         installdest = bb.data.getVar('D', d, True)
360         pkgcopy = bb.data.getVar('PKGD', d, True)
362         bb.mkdirhier(pkgcopy)
364         # Start by package population by taking a copy of the installed 
365         # files to operate on
366         os.system('rm -rf %s/*' % (pkgcopy))
367         os.system('cp -pPR %s/. %s/' % (installdest, pkgcopy))
370 python run_strip_funcs() {
371         if (bb.data.getVar('PACKAGE_STRIP', d, True) != 'no'):
372                 for f in (bb.data.getVar('PACKAGESTRIPFUNCS', d, True) or '').split():
373                         bb.build.exec_func(f, d)
376 python populate_packages () {
377         import glob, errno, re,os
379         workdir = bb.data.getVar('WORKDIR', d, True)
380         outdir = bb.data.getVar('DEPLOY_DIR', d, True)
381         dvar = bb.data.getVar('PKGD', d, True)
382         packages = bb.data.getVar('PACKAGES', d, True)
383         pn = bb.data.getVar('PN', d, True)
385         bb.mkdirhier(outdir)
386         os.chdir(dvar)
388         # Sanity check PACKAGES for duplicates - should be moved to 
389         # sanity.bbclass once we have the infrastucture
390         package_list = []
391         for pkg in packages.split():
392                 if pkg in package_list:
393                         bb.error("-------------------")
394                         bb.error("%s is listed in PACKAGES multiple times, this leads to packaging errors." % pkg)
395                         bb.error("Please fix the metadata/report this as bug to OE bugtracker.")
396                         bb.error("-------------------")
397                 else:
398                         package_list.append(pkg)
400         pkgdest = bb.data.getVar('PKGDEST', d, True)
401         os.system('rm -rf %s' % pkgdest)
403         seen = []
404         main_is_empty = 1
405         main_pkg = bb.data.getVar('PN', d, True)
407         for pkg in package_list:
408                 localdata = bb.data.createCopy(d)
409                 root = os.path.join(pkgdest, pkg)
410                 bb.mkdirhier(root)
412                 bb.data.setVar('PKG', pkg, localdata)
413                 overrides = bb.data.getVar('OVERRIDES', localdata, True)
414                 if not overrides:
415                         raise bb.build.FuncFailed('OVERRIDES not defined')
416                 bb.data.setVar('OVERRIDES', overrides + ':' + pkg, localdata)
417                 bb.data.update_data(localdata)
419                 filesvar = bb.data.getVar('FILES', localdata, True) or ""
420                 files = filesvar.split()
421                 for file in files:
422                         if os.path.isabs(file):
423                                 file = '.' + file
424                         if not os.path.islink(file):
425                                 if os.path.isdir(file):
426                                         newfiles =  [ os.path.join(file,x) for x in os.listdir(file) ]
427                                         if newfiles:
428                                                 files += newfiles
429                                                 continue
430                         globbed = glob.glob(file)
431                         if globbed:
432                                 if [ file ] != globbed:
433                                         if not file in globbed:
434                                                 files += globbed
435                                                 continue
436                                         else:
437                                                 globbed.remove(file)
438                                                 files += globbed
439                         if (not os.path.islink(file)) and (not os.path.exists(file)):
440                                 continue
441                         if file in seen:
442                                 continue
443                         seen.append(file)
444                         if os.path.isdir(file) and not os.path.islink(file):
445                                 bb.mkdirhier(os.path.join(root,file))
446                                 os.chmod(os.path.join(root,file), os.stat(file).st_mode)
447                                 continue
448                         fpath = os.path.join(root,file)
449                         dpath = os.path.dirname(fpath)
450                         bb.mkdirhier(dpath)
451                         ret = bb.copyfile(file, fpath)
452                         if ret is False:
453                                 raise bb.build.FuncFailed("File population failed when copying %s to %s" % (file, fpath))
454                         if pkg == main_pkg and main_is_empty:
455                                 main_is_empty = 0
456                 del localdata
457         os.chdir(workdir)
459         unshipped = []
460         for root, dirs, files in os.walk(dvar):
461                 for f in files:
462                         path = os.path.join(root[len(dvar):], f)
463                         if ('.' + path) not in seen:
464                                 unshipped.append(path)
466         if unshipped != []:
467                 bb.warn("the following files were installed but not shipped in any package:")
468                 for f in unshipped:
469                         bb.warn("  " + f)
471         bb.build.exec_func("package_name_hook", d)
473         for pkg in package_list:
474                 pkgname = bb.data.getVar('PKG_%s' % pkg, d, True)
475                 if pkgname is None:
476                         bb.data.setVar('PKG_%s' % pkg, pkg, d)
478         dangling_links = {}
479         pkg_files = {}
480         for pkg in package_list:
481                 dangling_links[pkg] = []
482                 pkg_files[pkg] = []
483                 inst_root = os.path.join(pkgdest, pkg)
484                 for root, dirs, files in os.walk(inst_root):
485                         for f in files:
486                                 path = os.path.join(root, f)
487                                 rpath = path[len(inst_root):]
488                                 pkg_files[pkg].append(rpath)
489                                 try:
490                                         s = os.stat(path)
491                                 except OSError, (err, strerror):
492                                         if err != errno.ENOENT:
493                                                 raise
494                                         target = os.readlink(path)
495                                         if target[0] != '/':
496                                                 target = os.path.join(root[len(inst_root):], target)
497                                         dangling_links[pkg].append(os.path.normpath(target))
499         for pkg in package_list:
500                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
502                 remstr = "${PN} (= ${EXTENDPKGV})"
503                 if main_is_empty and remstr in rdepends:
504                         rdepends.remove(remstr)
505                 for l in dangling_links[pkg]:
506                         found = False
507                         bb.debug(1, "%s contains dangling link %s" % (pkg, l))
508                         for p in package_list:
509                                 for f in pkg_files[p]:
510                                         if f == l:
511                                                 found = True
512                                                 bb.debug(1, "target found in %s" % p)
513                                                 if p == pkg:
514                                                         break
515                                                 if not p in rdepends:
516                                                         rdepends.append(p)
517                                                 break
518                         if found == False:
519                                 bb.note("%s contains dangling symlink to %s" % (pkg, l))
520                 bb.data.setVar('RDEPENDS_' + pkg, " ".join(rdepends), d)
522 populate_packages[dirs] = "${D}"
524 python emit_pkgdata() {
525         from glob import glob
527         def write_if_exists(f, pkg, var):
528                 def encode(str):
529                         import codecs
530                         c = codecs.getencoder("string_escape")
531                         return c(str)[0]
533                 val = bb.data.getVar('%s_%s' % (var, pkg), d, True)
534                 if val:
535                         f.write('%s_%s: %s\n' % (var, pkg, encode(val)))
536                         return
537                 val = bb.data.getVar('%s' % (var), d, True)
538                 if val:
539                         f.write('%s: %s\n' % (var, encode(val)))
540                 return
542         packages = bb.data.getVar('PACKAGES', d, True)
543         pkgdest = bb.data.getVar('PKGDEST', d, 1)
544         pkgdatadir = bb.data.getVar('PKGDATA_DIR', d, True)
546         lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
548         data_file = pkgdatadir + bb.data.expand("/${PN}" , d)
549         f = open(data_file, 'w')
550         f.write("PACKAGES: %s\n" % packages)
551         f.close()
552         package_stagefile(data_file, d)
554         workdir = bb.data.getVar('WORKDIR', d, True)
556         for pkg in packages.split():
557                 subdata_file = pkgdatadir + "/runtime/%s" % pkg
558                 sf = open(subdata_file, 'w')
559                 write_if_exists(sf, pkg, 'PN')
560                 write_if_exists(sf, pkg, 'PV')
561                 write_if_exists(sf, pkg, 'PR')
562                 write_if_exists(sf, pkg, 'PKGV')
563                 write_if_exists(sf, pkg, 'PKGR')
564                 write_if_exists(sf, pkg, 'DESCRIPTION')
565                 write_if_exists(sf, pkg, 'RDEPENDS')
566                 write_if_exists(sf, pkg, 'RPROVIDES')
567                 write_if_exists(sf, pkg, 'RRECOMMENDS')
568                 write_if_exists(sf, pkg, 'RSUGGESTS')
569                 write_if_exists(sf, pkg, 'RREPLACES')
570                 write_if_exists(sf, pkg, 'RCONFLICTS')
571                 write_if_exists(sf, pkg, 'PKG')
572                 write_if_exists(sf, pkg, 'ALLOW_EMPTY')
573                 write_if_exists(sf, pkg, 'FILES')
574                 write_if_exists(sf, pkg, 'pkg_postinst')
575                 write_if_exists(sf, pkg, 'pkg_postrm')
576                 write_if_exists(sf, pkg, 'pkg_preinst')
577                 write_if_exists(sf, pkg, 'pkg_prerm')
578                 sf.close()
580                 package_stagefile(subdata_file, d)
581                 #if pkgdatadir2:
582                 #       bb.copyfile(subdata_file, pkgdatadir2 + "/runtime/%s" % pkg)
584                 allow_empty = bb.data.getVar('ALLOW_EMPTY_%s' % pkg, d, True)
585                 if not allow_empty:
586                         allow_empty = bb.data.getVar('ALLOW_EMPTY', d, True)
587                 root = "%s/%s" % (pkgdest, pkg)
588                 os.chdir(root)
589                 g = glob('*') + glob('.[!.]*')
590                 if g or allow_empty == "1":
591                         packagedfile = pkgdatadir + '/runtime/%s.packaged' % pkg
592                         file(packagedfile, 'w').close()
593                         package_stagefile(packagedfile, d)
594         bb.utils.unlockfile(lf)
596 emit_pkgdata[dirs] = "${PKGDATA_DIR}/runtime"
598 ldconfig_postinst_fragment() {
599 if [ x"$D" = "x" ]; then
600         if [ -e /etc/ld.so.conf ] ; then
601                 [ -x /sbin/ldconfig ] && /sbin/ldconfig
602         fi
606 SHLIBSDIR = "${STAGING_DIR_HOST}/shlibs"
608 python package_do_shlibs() {
609         import re
611         exclude_shlibs = bb.data.getVar('EXCLUDE_FROM_SHLIBS', d, 0)
612         if exclude_shlibs:
613                 bb.debug(1, "not generating shlibs")
614                 return
615                 
616         lib_re = re.compile("^lib.*\.so")
617         libdir = bb.data.getVar('base_libdir', d, True)
618         libdir_re = re.compile(".*%s$" % (libdir))
620         packages = bb.data.getVar('PACKAGES', d, True)
622         workdir = bb.data.getVar('WORKDIR', d, True)
624         ver = bb.data.getVar('PKGV', d, True)
625         if not ver:
626                 bb.error("PKGV not defined")
627                 return
629         pkgdest = bb.data.getVar('PKGDEST', d, True)
631         shlibs_dir = bb.data.getVar('SHLIBSDIR', d, True)
632         bb.mkdirhier(shlibs_dir)
634         if bb.data.getVar('PACKAGE_SNAP_LIB_SYMLINKS', d, True) == "1":
635                 snap_symlinks = True
636         else:
637                 snap_symlinks = False
639         if (bb.data.getVar('USE_LDCONFIG', d, True) or "1") == "1":
640                 use_ldconfig = True
641         else:
642                 use_ldconfig = False
644         needed = {}
645         private_libs = bb.data.getVar('PRIVATE_LIBS', d, True)
647         lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
648         for pkg in packages.split():
649                 needs_ldconfig = False
650                 bb.debug(2, "calculating shlib provides for %s" % pkg)
652                 pkgver = bb.data.getVar('PKGV_' + pkg, d, True)
653                 if not pkgver:
654                         pkgver = bb.data.getVar('PV_' + pkg, d, True)
655                 if not pkgver:
656                         pkgver = ver
658                 needed[pkg] = []
659                 sonames = list()
660                 top = os.path.join(pkgdest, pkg)
661                 renames = []
662                 for root, dirs, files in os.walk(top):
663                         for file in files:
664                                 soname = None
665                                 path = os.path.join(root, file)
666                                 if (os.access(path, os.X_OK) or lib_re.match(file)) and not os.path.islink(path):
667                                         cmd = bb.data.getVar('OBJDUMP', d, True) + " -p " + path + " 2>/dev/null"
668                                         cmd = "PATH=\"%s\" %s" % (bb.data.getVar('PATH', d, True), cmd)
669                                         fd = os.popen(cmd)
670                                         lines = fd.readlines()
671                                         fd.close()
672                                         for l in lines:
673                                                 m = re.match("\s+NEEDED\s+([^\s]*)", l)
674                                                 if m:
675                                                         needed[pkg].append(m.group(1))
676                                                 m = re.match("\s+SONAME\s+([^\s]*)", l)
677                                                 if m:
678                                                         this_soname = m.group(1)
679                                                         if not this_soname in sonames:
680                                                                 # if library is private (only used by package) then do not build shlib for it
681                                                                 if not private_libs or -1 == private_libs.find(this_soname):
682                                                                         sonames.append(this_soname)
683                                                         if libdir_re.match(root):
684                                                                 needs_ldconfig = True
685                                                         if snap_symlinks and (file != soname):
686                                                                 renames.append((path, os.path.join(root, this_soname)))
687                 for (old, new) in renames:
688                         os.rename(old, new)
689                 shlibs_file = os.path.join(shlibs_dir, pkg + ".list")
690                 if os.path.exists(shlibs_file):
691                         os.remove(shlibs_file)
692                 shver_file = os.path.join(shlibs_dir, pkg + ".ver")
693                 if os.path.exists(shver_file):
694                         os.remove(shver_file)
695                 if len(sonames):
696                         fd = open(shlibs_file, 'w')
697                         for s in sonames:
698                                 fd.write(s + '\n')
699                         fd.close()
700                         package_stagefile(shlibs_file, d)
701                         fd = open(shver_file, 'w')
702                         fd.write(pkgver + '\n')
703                         fd.close()
704                         package_stagefile(shver_file, d)
705                 if needs_ldconfig and use_ldconfig:
706                         bb.debug(1, 'adding ldconfig call to postinst for %s' % pkg)
707                         postinst = bb.data.getVar('pkg_postinst_%s' % pkg, d, True) or bb.data.getVar('pkg_postinst', d, True)
708                         if not postinst:
709                                 postinst = '#!/bin/sh\n'
710                         postinst += bb.data.getVar('ldconfig_postinst_fragment', d, True)
711                         bb.data.setVar('pkg_postinst_%s' % pkg, postinst, d)
713         shlib_provider = {}
714         list_re = re.compile('^(.*)\.list$')
715         for dir in [shlibs_dir]: 
716                 if not os.path.exists(dir):
717                         continue
718                 for file in os.listdir(dir):
719                         m = list_re.match(file)
720                         if m:
721                                 dep_pkg = m.group(1)
722                                 fd = open(os.path.join(dir, file))
723                                 lines = fd.readlines()
724                                 fd.close()
725                                 ver_file = os.path.join(dir, dep_pkg + '.ver')
726                                 lib_ver = None
727                                 if os.path.exists(ver_file):
728                                         fd = open(ver_file)
729                                         lib_ver = fd.readline().rstrip()
730                                         fd.close()
731                                 for l in lines:
732                                         shlib_provider[l.rstrip()] = (dep_pkg, lib_ver)
733         bb.utils.unlockfile(lf)
735         assumed_libs = bb.data.getVar('ASSUME_SHLIBS', d, True)
736         if assumed_libs:
737             for e in assumed_libs.split():
738                 l, dep_pkg = e.split(":")
739                 lib_ver = None
740                 dep_pkg = dep_pkg.rsplit("_", 1)
741                 if len(dep_pkg) == 2:
742                     lib_ver = dep_pkg[1]
743                 dep_pkg = dep_pkg[0]
744                 shlib_provider[l] = (dep_pkg, lib_ver)
746         dep_packages = []
747         for pkg in packages.split():
748                 bb.debug(2, "calculating shlib requirements for %s" % pkg)
750                 deps = list()
751                 for n in needed[pkg]:
752                         if n in shlib_provider.keys():
753                                 (dep_pkg, ver_needed) = shlib_provider[n]
755                                 if dep_pkg == pkg:
756                                         continue
758                                 if ver_needed:
759                                         dep = "%s (>= %s)" % (dep_pkg, ver_needed)
760                                 else:
761                                         dep = dep_pkg
762                                 if not dep in deps:
763                                         deps.append(dep)
764                                 if not dep_pkg in dep_packages:
765                                         dep_packages.append(dep_pkg)
766                                         
767                         else:
768                                 bb.note("Couldn't find shared library provider for %s" % n)
770                 deps_file = os.path.join(pkgdest, pkg + ".shlibdeps")
771                 if os.path.exists(deps_file):
772                         os.remove(deps_file)
773                 if len(deps):
774                         fd = open(deps_file, 'w')
775                         for dep in deps:
776                                 fd.write(dep + '\n')
777                         fd.close()
780 python package_do_pkgconfig () {
781         import re
783         packages = bb.data.getVar('PACKAGES', d, True)
784         workdir = bb.data.getVar('WORKDIR', d, True)
785         pkgdest = bb.data.getVar('PKGDEST', d, True)
787         shlibs_dir = bb.data.getVar('SHLIBSDIR', d, True)
788         bb.mkdirhier(shlibs_dir)
790         pc_re = re.compile('(.*)\.pc$')
791         var_re = re.compile('(.*)=(.*)')
792         field_re = re.compile('(.*): (.*)')
794         pkgconfig_provided = {}
795         pkgconfig_needed = {}
796         for pkg in packages.split():
797                 pkgconfig_provided[pkg] = []
798                 pkgconfig_needed[pkg] = []
799                 top = os.path.join(pkgdest, pkg)
800                 for root, dirs, files in os.walk(top):
801                         for file in files:
802                                 m = pc_re.match(file)
803                                 if m:
804                                         pd = bb.data.init()
805                                         name = m.group(1)
806                                         pkgconfig_provided[pkg].append(name)
807                                         path = os.path.join(root, file)
808                                         if not os.access(path, os.R_OK):
809                                                 continue
810                                         f = open(path, 'r')
811                                         lines = f.readlines()
812                                         f.close()
813                                         for l in lines:
814                                                 m = var_re.match(l)
815                                                 if m:
816                                                         name = m.group(1)
817                                                         val = m.group(2)
818                                                         bb.data.setVar(name, bb.data.expand(val, pd), pd)
819                                                         continue
820                                                 m = field_re.match(l)
821                                                 if m:
822                                                         hdr = m.group(1)
823                                                         exp = bb.data.expand(m.group(2), pd)
824                                                         if hdr == 'Requires':
825                                                                 pkgconfig_needed[pkg] += exp.replace(',', ' ').split()
827         lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
829         for pkg in packages.split():
830                 pkgs_file = os.path.join(shlibs_dir, pkg + ".pclist")
831                 if os.path.exists(pkgs_file):
832                         os.remove(pkgs_file)
833                 if pkgconfig_provided[pkg] != []:
834                         f = open(pkgs_file, 'w')
835                         for p in pkgconfig_provided[pkg]:
836                                 f.write('%s\n' % p)
837                         f.close()
838                         package_stagefile(pkgs_file, d)
840         for dir in [shlibs_dir]:
841                 if not os.path.exists(dir):
842                         continue
843                 for file in os.listdir(dir):
844                         m = re.match('^(.*)\.pclist$', file)
845                         if m:
846                                 pkg = m.group(1)
847                                 fd = open(os.path.join(dir, file))
848                                 lines = fd.readlines()
849                                 fd.close()
850                                 pkgconfig_provided[pkg] = []
851                                 for l in lines:
852                                         pkgconfig_provided[pkg].append(l.rstrip())
854         for pkg in packages.split():
855                 deps = []
856                 for n in pkgconfig_needed[pkg]:
857                         found = False
858                         for k in pkgconfig_provided.keys():
859                                 if n in pkgconfig_provided[k]:
860                                         if k != pkg and not (k in deps):
861                                                 deps.append(k)
862                                         found = True
863                         if found == False:
864                                 bb.note("couldn't find pkgconfig module '%s' in any package" % n)
865                 deps_file = os.path.join(pkgdest, pkg + ".pcdeps")
866                 if os.path.exists(deps_file):
867                         os.remove(deps_file)
868                 if len(deps):
869                         fd = open(deps_file, 'w')
870                         for dep in deps:
871                                 fd.write(dep + '\n')
872                         fd.close()
873                         package_stagefile(deps_file, d)
875         bb.utils.unlockfile(lf)
878 python read_shlibdeps () {
879         packages = bb.data.getVar('PACKAGES', d, True).split()
880         for pkg in packages:
881                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
882                 for extension in ".shlibdeps", ".pcdeps", ".clilibdeps":
883                         depsfile = bb.data.expand("${PKGDEST}/" + pkg + extension, d)
884                         if os.access(depsfile, os.R_OK):
885                                 fd = file(depsfile)
886                                 lines = fd.readlines()
887                                 fd.close()
888                                 for l in lines:
889                                         rdepends.append(l.rstrip())
890                 bb.data.setVar('RDEPENDS_' + pkg, " ".join(rdepends), d)
893 python package_depchains() {
894         """
895         For a given set of prefix and postfix modifiers, make those packages
896         RRECOMMENDS on the corresponding packages for its RDEPENDS.
898         Example:  If package A depends upon package B, and A's .bb emits an
899         A-dev package, this would make A-dev Recommends: B-dev.
901         If only one of a given suffix is specified, it will take the RRECOMMENDS
902         based on the RDEPENDS of *all* other packages. If more than one of a given 
903         suffix is specified, its will only use the RDEPENDS of the single parent 
904         package.
905         """
907         packages  = bb.data.getVar('PACKAGES', d, True)
908         postfixes = (bb.data.getVar('DEPCHAIN_POST', d, True) or '').split()
909         prefixes  = (bb.data.getVar('DEPCHAIN_PRE', d, True) or '').split()
911         def pkg_adddeprrecs(pkg, base, suffix, getname, depends, d):
913                 #bb.note('depends for %s is %s' % (base, depends))
914                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, True) or bb.data.getVar('RRECOMMENDS', d, True) or "")
916                 for depend in depends:
917                         if depend.find('-native') != -1 or depend.find('-cross') != -1 or depend.startswith('virtual/'):
918                                 #bb.note("Skipping %s" % depend)
919                                 continue
920                         if depend.endswith('-dev'):
921                                 depend = depend.replace('-dev', '')
922                         if depend.endswith('-dbg'):
923                                 depend = depend.replace('-dbg', '')
924                         pkgname = getname(depend, suffix)
925                         #bb.note("Adding %s for %s" % (pkgname, depend))
926                         if not pkgname in rreclist:
927                                 rreclist.append(pkgname)
929                 #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
930                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
932         def pkg_addrrecs(pkg, base, suffix, getname, rdepends, d):
934                 #bb.note('rdepends for %s is %s' % (base, rdepends))
935                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, True) or bb.data.getVar('RRECOMMENDS', d, True) or "")
937                 for depend in rdepends:
938                         if depend.endswith('-dev'):
939                                 depend = depend.replace('-dev', '')
940                         if depend.endswith('-dbg'):
941                                 depend = depend.replace('-dbg', '')
942                         pkgname = getname(depend, suffix)
943                         if not pkgname in rreclist:
944                                 rreclist.append(pkgname)
946                 #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
947                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
949         def add_dep(list, dep):
950                 dep = dep.split(' (')[0].strip()
951                 if dep not in list:
952                         list.append(dep)
954         depends = []
955         for dep in explode_deps(bb.data.getVar('DEPENDS', d, True) or ""):
956                 add_dep(depends, dep)
958         rdepends = []
959         for dep in explode_deps(bb.data.getVar('RDEPENDS', d, True) or ""):
960                 add_dep(rdepends, dep)
962         for pkg in packages.split():
963                 for dep in explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, True) or ""):
964                         add_dep(rdepends, dep)
966         #bb.note('rdepends is %s' % rdepends)
968         def post_getname(name, suffix):
969                 return '%s%s' % (name, suffix)
970         def pre_getname(name, suffix):
971                 return '%s%s' % (suffix, name)
973         pkgs = {}
974         for pkg in packages.split():
975                 for postfix in postfixes:
976                         if pkg.endswith(postfix):
977                                 if not postfix in pkgs:
978                                         pkgs[postfix] = {}
979                                 pkgs[postfix][pkg] = (pkg[:-len(postfix)], post_getname)
981                 for prefix in prefixes:
982                         if pkg.startswith(prefix):
983                                 if not prefix in pkgs:
984                                         pkgs[prefix] = {}
985                                 pkgs[prefix][pkg] = (pkg[:-len(prefix)], pre_getname)
987         for suffix in pkgs:
988                 for pkg in pkgs[suffix]:
989                         (base, func) = pkgs[suffix][pkg]
990                         if suffix == "-dev" and not pkg.startswith("kernel-module-"):
991                                 pkg_adddeprrecs(pkg, base, suffix, func, depends, d)
992                         if len(pkgs[suffix]) == 1:
993                                 pkg_addrrecs(pkg, base, suffix, func, rdepends, d)
994                         else:
995                                 rdeps = []
996                                 for dep in explode_deps(bb.data.getVar('RDEPENDS_' + base, d, True) or bb.data.getVar('RDEPENDS', d, True) or ""):
997                                         add_dep(rdeps, dep)
998                                 pkg_addrrecs(pkg, base, suffix, func, rdeps, d)
1001 PACKAGE_PREPROCESS_FUNCS ?= ""
1002 PACKAGEFUNCS ?= "perform_packagecopy \
1003                 ${PACKAGE_PREPROCESS_FUNCS} \
1004                 package_do_split_locales \
1005                 run_strip_funcs \
1006                 populate_packages \
1007                 package_do_shlibs \
1008                 package_do_pkgconfig \
1009                 read_shlibdeps \
1010                 package_depchains \
1011                 emit_pkgdata"
1013 def package_run_hooks(f, d):
1014         import bb, os
1015         staging = bb.data.getVar('PKGDATA_DIR', d, True)
1016         dn = os.path.join(staging, 'hooks', f)
1017         if os.access(dn, os.R_OK):
1018                 for f in os.listdir(dn):
1019                         fn = os.path.join(dn, f)
1020                         fp = open(fn, 'r')
1021                         line = 0
1022                         for l in fp.readlines():
1023                                 l = l.rstrip()
1024                                 bb.parse.parse_py.BBHandler.feeder(line, l, fn, os.path.basename(fn), d)
1025                                 line += 1
1026                         fp.close()
1027                         anonqueue = bb.data.getVar("__anonqueue", d, True) or []
1028                         body = [x['content'] for x in anonqueue]
1029                         flag = { 'python' : 1, 'func' : 1 }
1030                         bb.data.setVar("__anonfunc", "\n".join(body), d)
1031                         bb.data.setVarFlags("__anonfunc", flag, d)
1032                         try:
1033                                 t = bb.data.getVar('T', d)
1034                                 bb.data.setVar('T', '${TMPDIR}/', d)
1035                                 bb.build.exec_func("__anonfunc", d)
1036                                 bb.data.delVar('T', d)
1037                                 if t:
1038                                         bb.data.setVar('T', t, d)
1039                         except Exception, e:
1040                                 bb.msg.debug(1, bb.msg.domain.Parsing, "Exception when executing anonymous function: %s" % e)
1041                                 raise
1042                         bb.data.delVar("__anonqueue", d)
1043                         bb.data.delVar("__anonfunc", d)
1045 python package_do_package () {
1046         packages = (bb.data.getVar('PACKAGES', d, True) or "").split()
1047         if len(packages) < 1:
1048                 bb.debug(1, "No packages to build, skipping do_package")
1049                 return
1051         workdir = bb.data.getVar('WORKDIR', d, True)
1052         outdir = bb.data.getVar('DEPLOY_DIR', d, True)
1053         dest = bb.data.getVar('D', d, True)
1054         dvar = bb.data.getVar('PKGD', d, True)
1055         pn = bb.data.getVar('PN', d, True)
1057         if not workdir or not outdir or not dest or not dvar or not pn or not packages:
1058                 bb.error("WORKDIR, DEPLOY_DIR, D, PN and PKGD all must be defined, unable to package")
1059                 return
1061         for f in (bb.data.getVar('PACKAGEFUNCS', d, True) or '').split():
1062                 bb.build.exec_func(f, d)
1063                 package_run_hooks(f, d)
1065 do_package[dirs] = "${D}"
1066 addtask package before do_build after do_install
1068 # Dummy task to mark when all packaging is complete
1069 do_package_write () {
1070         :
1072 addtask package_write before do_build after do_package
1074 EXPORT_FUNCTIONS do_package do_package_write
1077 # Helper functions for the package writing classes
1080 python package_mapping_rename_hook () {
1081         """
1082         Rewrite variables to account for package renaming in things
1083         like debian.bbclass or manual PKG variable name changes
1084         """
1085         runtime_mapping_rename("RDEPENDS", d)
1086         runtime_mapping_rename("RRECOMMENDS", d)
1087         runtime_mapping_rename("RSUGGESTS", d)
1088         runtime_mapping_rename("RPROVIDES", d)
1089         runtime_mapping_rename("RREPLACES", d)
1090         runtime_mapping_rename("RCONFLICTS", d)
1093 EXPORT_FUNCTIONS mapping_rename_hook