genext2fs: update package LICENSE
[openembedded.git] / classes / package.bbclass
blob2769595bf9e1da8b04751a1324617cedc1ceb3a4
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 populate_packages () {
371         import glob, errno, re,os
373         workdir = bb.data.getVar('WORKDIR', d, True)
374         outdir = bb.data.getVar('DEPLOY_DIR', d, True)
375         dvar = bb.data.getVar('PKGD', d, True)
376         packages = bb.data.getVar('PACKAGES', d, True)
377         pn = bb.data.getVar('PN', d, True)
379         bb.mkdirhier(outdir)
380         os.chdir(dvar)
382         # Sanity check PACKAGES for duplicates - should be moved to 
383         # sanity.bbclass once we have the infrastucture
384         package_list = []
385         for pkg in packages.split():
386                 if pkg in package_list:
387                         bb.error("-------------------")
388                         bb.error("%s is listed in PACKAGES multiple times, this leads to packaging errors." % pkg)
389                         bb.error("Please fix the metadata/report this as bug to OE bugtracker.")
390                         bb.error("-------------------")
391                 else:
392                         package_list.append(pkg)
395         if (bb.data.getVar('PACKAGE_STRIP', d, True) != 'no'):
396                 for f in (bb.data.getVar('PACKAGESTRIPFUNCS', d, True) or '').split():
397                         bb.build.exec_func(f, d)
399         pkgdest = bb.data.getVar('PKGDEST', d, True)
400         os.system('rm -rf %s' % pkgdest)
402         seen = []
403         main_is_empty = 1
404         main_pkg = bb.data.getVar('PN', d, True)
406         for pkg in package_list:
407                 localdata = bb.data.createCopy(d)
408                 root = os.path.join(pkgdest, pkg)
409                 bb.mkdirhier(root)
411                 bb.data.setVar('PKG', pkg, localdata)
412                 overrides = bb.data.getVar('OVERRIDES', localdata, True)
413                 if not overrides:
414                         raise bb.build.FuncFailed('OVERRIDES not defined')
415                 bb.data.setVar('OVERRIDES', overrides + ':' + pkg, localdata)
416                 bb.data.update_data(localdata)
418                 filesvar = bb.data.getVar('FILES', localdata, True) or ""
419                 files = filesvar.split()
420                 for file in files:
421                         if os.path.isabs(file):
422                                 file = '.' + file
423                         if not os.path.islink(file):
424                                 if os.path.isdir(file):
425                                         newfiles =  [ os.path.join(file,x) for x in os.listdir(file) ]
426                                         if newfiles:
427                                                 files += newfiles
428                                                 continue
429                         globbed = glob.glob(file)
430                         if globbed:
431                                 if [ file ] != globbed:
432                                         if not file in globbed:
433                                                 files += globbed
434                                                 continue
435                                         else:
436                                                 globbed.remove(file)
437                                                 files += globbed
438                         if (not os.path.islink(file)) and (not os.path.exists(file)):
439                                 continue
440                         if file in seen:
441                                 continue
442                         seen.append(file)
443                         if os.path.isdir(file) and not os.path.islink(file):
444                                 bb.mkdirhier(os.path.join(root,file))
445                                 os.chmod(os.path.join(root,file), os.stat(file).st_mode)
446                                 continue
447                         fpath = os.path.join(root,file)
448                         dpath = os.path.dirname(fpath)
449                         bb.mkdirhier(dpath)
450                         ret = bb.copyfile(file, fpath)
451                         if ret is False:
452                                 raise bb.build.FuncFailed("File population failed when copying %s to %s" % (file, fpath))
453                         if pkg == main_pkg and main_is_empty:
454                                 main_is_empty = 0
455                 del localdata
456         os.chdir(workdir)
458         unshipped = []
459         for root, dirs, files in os.walk(dvar):
460                 for f in files:
461                         path = os.path.join(root[len(dvar):], f)
462                         if ('.' + path) not in seen:
463                                 unshipped.append(path)
465         if unshipped != []:
466                 bb.note("the following files were installed but not shipped in any package:")
467                 for f in unshipped:
468                         bb.note("  " + f)
470         bb.build.exec_func("package_name_hook", d)
472         for pkg in package_list:
473                 pkgname = bb.data.getVar('PKG_%s' % pkg, d, True)
474                 if pkgname is None:
475                         bb.data.setVar('PKG_%s' % pkg, pkg, d)
477         dangling_links = {}
478         pkg_files = {}
479         for pkg in package_list:
480                 dangling_links[pkg] = []
481                 pkg_files[pkg] = []
482                 inst_root = os.path.join(pkgdest, pkg)
483                 for root, dirs, files in os.walk(inst_root):
484                         for f in files:
485                                 path = os.path.join(root, f)
486                                 rpath = path[len(inst_root):]
487                                 pkg_files[pkg].append(rpath)
488                                 try:
489                                         s = os.stat(path)
490                                 except OSError, (err, strerror):
491                                         if err != errno.ENOENT:
492                                                 raise
493                                         target = os.readlink(path)
494                                         if target[0] != '/':
495                                                 target = os.path.join(root[len(inst_root):], target)
496                                         dangling_links[pkg].append(os.path.normpath(target))
498         for pkg in package_list:
499                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
501                 remstr = "${PN} (= ${EXTENDPKGV})"
502                 if main_is_empty and remstr in rdepends:
503                         rdepends.remove(remstr)
504                 for l in dangling_links[pkg]:
505                         found = False
506                         bb.debug(1, "%s contains dangling link %s" % (pkg, l))
507                         for p in package_list:
508                                 for f in pkg_files[p]:
509                                         if f == l:
510                                                 found = True
511                                                 bb.debug(1, "target found in %s" % p)
512                                                 if p == pkg:
513                                                         break
514                                                 if not p in rdepends:
515                                                         rdepends.append(p)
516                                                 break
517                         if found == False:
518                                 bb.note("%s contains dangling symlink to %s" % (pkg, l))
519                 bb.data.setVar('RDEPENDS_' + pkg, " " + " ".join(rdepends), d)
521 populate_packages[dirs] = "${D}"
523 python emit_pkgdata() {
524         from glob import glob
526         def write_if_exists(f, pkg, var):
527                 def encode(str):
528                         import codecs
529                         c = codecs.getencoder("string_escape")
530                         return c(str)[0]
532                 val = bb.data.getVar('%s_%s' % (var, pkg), d, True)
533                 if val:
534                         f.write('%s_%s: %s\n' % (var, pkg, encode(val)))
535                         return
536                 val = bb.data.getVar('%s' % (var), d, True)
537                 if val:
538                         f.write('%s: %s\n' % (var, encode(val)))
539                 return
541         packages = bb.data.getVar('PACKAGES', d, True)
542         pkgdest = bb.data.getVar('PKGDEST', d, 1)
543         pkgdatadir = bb.data.getVar('PKGDATA_DIR', d, True)
545         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
546         if pstageactive == "1":
547                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
549         data_file = pkgdatadir + bb.data.expand("/${PN}" , d)
550         f = open(data_file, 'w')
551         f.write("PACKAGES: %s\n" % packages)
552         f.close()
553         package_stagefile(data_file, d)
555         workdir = bb.data.getVar('WORKDIR', d, True)
557         for pkg in packages.split():
558                 subdata_file = pkgdatadir + "/runtime/%s" % pkg
559                 sf = open(subdata_file, 'w')
560                 write_if_exists(sf, pkg, 'PN')
561                 write_if_exists(sf, pkg, 'PV')
562                 write_if_exists(sf, pkg, 'PR')
563                 write_if_exists(sf, pkg, 'PKGV')
564                 write_if_exists(sf, pkg, 'PKGR')
565                 write_if_exists(sf, pkg, 'DESCRIPTION')
566                 write_if_exists(sf, pkg, 'RDEPENDS')
567                 write_if_exists(sf, pkg, 'RPROVIDES')
568                 write_if_exists(sf, pkg, 'RRECOMMENDS')
569                 write_if_exists(sf, pkg, 'RSUGGESTS')
570                 write_if_exists(sf, pkg, 'RREPLACES')
571                 write_if_exists(sf, pkg, 'RCONFLICTS')
572                 write_if_exists(sf, pkg, 'PKG')
573                 write_if_exists(sf, pkg, 'ALLOW_EMPTY')
574                 write_if_exists(sf, pkg, 'FILES')
575                 write_if_exists(sf, pkg, 'pkg_postinst')
576                 write_if_exists(sf, pkg, 'pkg_postrm')
577                 write_if_exists(sf, pkg, 'pkg_preinst')
578                 write_if_exists(sf, pkg, 'pkg_prerm')
579                 sf.close()
581                 package_stagefile(subdata_file, d)
582                 #if pkgdatadir2:
583                 #       bb.copyfile(subdata_file, pkgdatadir2 + "/runtime/%s" % pkg)
585                 allow_empty = bb.data.getVar('ALLOW_EMPTY_%s' % pkg, d, True)
586                 if not allow_empty:
587                         allow_empty = bb.data.getVar('ALLOW_EMPTY', d, True)
588                 root = "%s/%s" % (pkgdest, pkg)
589                 os.chdir(root)
590                 g = glob('*') + glob('.[!.]*')
591                 if g or allow_empty == "1":
592                         packagedfile = pkgdatadir + '/runtime/%s.packaged' % pkg
593                         file(packagedfile, 'w').close()
594                         package_stagefile(packagedfile, d)
595         if pstageactive == "1":
596                 bb.utils.unlockfile(lf)
598 emit_pkgdata[dirs] = "${PKGDATA_DIR}/runtime"
600 ldconfig_postinst_fragment() {
601 if [ x"$D" = "x" ]; then
602         if [ -e /etc/ld.so.conf ] ; then
603                 [ -x /sbin/ldconfig ] && /sbin/ldconfig
604         fi
608 SHLIBSDIR = "${STAGING_DIR_HOST}/shlibs"
610 python package_do_shlibs() {
611         import re
613         exclude_shlibs = bb.data.getVar('EXCLUDE_FROM_SHLIBS', d, 0)
614         if exclude_shlibs:
615                 bb.debug(1, "not generating shlibs")
616                 return
617                 
618         lib_re = re.compile("^lib.*\.so")
619         libdir = bb.data.getVar('base_libdir', d, True)
620         libdir_re = re.compile(".*%s$" % (libdir))
622         packages = bb.data.getVar('PACKAGES', d, True)
624         workdir = bb.data.getVar('WORKDIR', d, True)
626         ver = bb.data.getVar('PKGV', d, True)
627         if not ver:
628                 bb.error("PKGV not defined")
629                 return
631         pkgdest = bb.data.getVar('PKGDEST', d, True)
633         shlibs_dir = bb.data.getVar('SHLIBSDIR', d, True)
634         bb.mkdirhier(shlibs_dir)
636         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
637         if pstageactive == "1":
638                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
640         if bb.data.getVar('PACKAGE_SNAP_LIB_SYMLINKS', d, True) == "1":
641                 snap_symlinks = True
642         else:
643                 snap_symlinks = False
645         if (bb.data.getVar('USE_LDCONFIG', d, True) or "1") == "1":
646                 use_ldconfig = True
647         else:
648                 use_ldconfig = False
650         needed = {}
651         private_libs = bb.data.getVar('PRIVATE_LIBS', d, True)
652         for pkg in packages.split():
653                 needs_ldconfig = False
654                 bb.debug(2, "calculating shlib provides for %s" % pkg)
656                 pkgver = bb.data.getVar('PKGV_' + pkg, d, True)
657                 if not pkgver:
658                         pkgver = bb.data.getVar('PV_' + pkg, d, True)
659                 if not pkgver:
660                         pkgver = ver
662                 needed[pkg] = []
663                 sonames = list()
664                 top = os.path.join(pkgdest, pkg)
665                 renames = []
666                 for root, dirs, files in os.walk(top):
667                         for file in files:
668                                 soname = None
669                                 path = os.path.join(root, file)
670                                 if (os.access(path, os.X_OK) or lib_re.match(file)) and not os.path.islink(path):
671                                         cmd = bb.data.getVar('OBJDUMP', d, True) + " -p " + path + " 2>/dev/null"
672                                         cmd = "PATH=\"%s\" %s" % (bb.data.getVar('PATH', d, True), cmd)
673                                         fd = os.popen(cmd)
674                                         lines = fd.readlines()
675                                         fd.close()
676                                         for l in lines:
677                                                 m = re.match("\s+NEEDED\s+([^\s]*)", l)
678                                                 if m:
679                                                         needed[pkg].append(m.group(1))
680                                                 m = re.match("\s+SONAME\s+([^\s]*)", l)
681                                                 if m:
682                                                         this_soname = m.group(1)
683                                                         if not this_soname in sonames:
684                                                                 # if library is private (only used by package) then do not build shlib for it
685                                                                 if not private_libs or -1 == private_libs.find(this_soname):
686                                                                         sonames.append(this_soname)
687                                                         if libdir_re.match(root):
688                                                                 needs_ldconfig = True
689                                                         if snap_symlinks and (file != soname):
690                                                                 renames.append((path, os.path.join(root, this_soname)))
691                 for (old, new) in renames:
692                         os.rename(old, new)
693                 shlibs_file = os.path.join(shlibs_dir, pkg + ".list")
694                 if os.path.exists(shlibs_file):
695                         os.remove(shlibs_file)
696                 shver_file = os.path.join(shlibs_dir, pkg + ".ver")
697                 if os.path.exists(shver_file):
698                         os.remove(shver_file)
699                 if len(sonames):
700                         fd = open(shlibs_file, 'w')
701                         for s in sonames:
702                                 fd.write(s + '\n')
703                         fd.close()
704                         package_stagefile(shlibs_file, d)
705                         fd = open(shver_file, 'w')
706                         fd.write(pkgver + '\n')
707                         fd.close()
708                         package_stagefile(shver_file, d)
709                 if needs_ldconfig and use_ldconfig:
710                         bb.debug(1, 'adding ldconfig call to postinst for %s' % pkg)
711                         postinst = bb.data.getVar('pkg_postinst_%s' % pkg, d, True) or bb.data.getVar('pkg_postinst', d, True)
712                         if not postinst:
713                                 postinst = '#!/bin/sh\n'
714                         postinst += bb.data.getVar('ldconfig_postinst_fragment', d, True)
715                         bb.data.setVar('pkg_postinst_%s' % pkg, postinst, d)
717         if pstageactive == "1":
718                 bb.utils.unlockfile(lf)
720         shlib_provider = {}
721         list_re = re.compile('^(.*)\.list$')
722         for dir in [shlibs_dir]: 
723                 if not os.path.exists(dir):
724                         continue
725                 for file in os.listdir(dir):
726                         m = list_re.match(file)
727                         if m:
728                                 dep_pkg = m.group(1)
729                                 fd = open(os.path.join(dir, file))
730                                 lines = fd.readlines()
731                                 fd.close()
732                                 ver_file = os.path.join(dir, dep_pkg + '.ver')
733                                 lib_ver = None
734                                 if os.path.exists(ver_file):
735                                         fd = open(ver_file)
736                                         lib_ver = fd.readline().rstrip()
737                                         fd.close()
738                                 for l in lines:
739                                         shlib_provider[l.rstrip()] = (dep_pkg, lib_ver)
741         assumed_libs = bb.data.getVar('ASSUME_SHLIBS', d, True)
742         if assumed_libs:
743             for e in assumed_libs.split():
744                 l, dep_pkg = e.split(":")
745                 lib_ver = None
746                 dep_pkg = dep_pkg.rsplit("_", 1)
747                 if len(dep_pkg) == 2:
748                     lib_ver = dep_pkg[1]
749                 dep_pkg = dep_pkg[0]
750                 shlib_provider[l] = (dep_pkg, lib_ver)
752         dep_packages = []
753         for pkg in packages.split():
754                 bb.debug(2, "calculating shlib requirements for %s" % pkg)
756                 deps = list()
757                 for n in needed[pkg]:
758                         if n in shlib_provider.keys():
759                                 (dep_pkg, ver_needed) = shlib_provider[n]
761                                 if dep_pkg == pkg:
762                                         continue
764                                 if ver_needed:
765                                         dep = "%s (>= %s)" % (dep_pkg, ver_needed)
766                                 else:
767                                         dep = dep_pkg
768                                 if not dep in deps:
769                                         deps.append(dep)
770                                 if not dep_pkg in dep_packages:
771                                         dep_packages.append(dep_pkg)
772                                         
773                         else:
774                                 bb.note("Couldn't find shared library provider for %s" % n)
776                 deps_file = os.path.join(pkgdest, pkg + ".shlibdeps")
777                 if os.path.exists(deps_file):
778                         os.remove(deps_file)
779                 if len(deps):
780                         fd = open(deps_file, 'w')
781                         for dep in deps:
782                                 fd.write(dep + '\n')
783                         fd.close()
786 python package_do_pkgconfig () {
787         import re
789         packages = bb.data.getVar('PACKAGES', d, True)
790         workdir = bb.data.getVar('WORKDIR', d, True)
791         pkgdest = bb.data.getVar('PKGDEST', d, True)
793         shlibs_dir = bb.data.getVar('SHLIBSDIR', d, True)
794         bb.mkdirhier(shlibs_dir)
796         pc_re = re.compile('(.*)\.pc$')
797         var_re = re.compile('(.*)=(.*)')
798         field_re = re.compile('(.*): (.*)')
800         pkgconfig_provided = {}
801         pkgconfig_needed = {}
802         for pkg in packages.split():
803                 pkgconfig_provided[pkg] = []
804                 pkgconfig_needed[pkg] = []
805                 top = os.path.join(pkgdest, pkg)
806                 for root, dirs, files in os.walk(top):
807                         for file in files:
808                                 m = pc_re.match(file)
809                                 if m:
810                                         pd = bb.data.init()
811                                         name = m.group(1)
812                                         pkgconfig_provided[pkg].append(name)
813                                         path = os.path.join(root, file)
814                                         if not os.access(path, os.R_OK):
815                                                 continue
816                                         f = open(path, 'r')
817                                         lines = f.readlines()
818                                         f.close()
819                                         for l in lines:
820                                                 m = var_re.match(l)
821                                                 if m:
822                                                         name = m.group(1)
823                                                         val = m.group(2)
824                                                         bb.data.setVar(name, bb.data.expand(val, pd), pd)
825                                                         continue
826                                                 m = field_re.match(l)
827                                                 if m:
828                                                         hdr = m.group(1)
829                                                         exp = bb.data.expand(m.group(2), pd)
830                                                         if hdr == 'Requires':
831                                                                 pkgconfig_needed[pkg] += exp.replace(',', ' ').split()
833         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
834         if pstageactive == "1":
835                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
837         for pkg in packages.split():
838                 pkgs_file = os.path.join(shlibs_dir, pkg + ".pclist")
839                 if os.path.exists(pkgs_file):
840                         os.remove(pkgs_file)
841                 if pkgconfig_provided[pkg] != []:
842                         f = open(pkgs_file, 'w')
843                         for p in pkgconfig_provided[pkg]:
844                                 f.write('%s\n' % p)
845                         f.close()
846                         package_stagefile(pkgs_file, d)
848         for dir in [shlibs_dir]:
849                 if not os.path.exists(dir):
850                         continue
851                 for file in os.listdir(dir):
852                         m = re.match('^(.*)\.pclist$', file)
853                         if m:
854                                 pkg = m.group(1)
855                                 fd = open(os.path.join(dir, file))
856                                 lines = fd.readlines()
857                                 fd.close()
858                                 pkgconfig_provided[pkg] = []
859                                 for l in lines:
860                                         pkgconfig_provided[pkg].append(l.rstrip())
862         for pkg in packages.split():
863                 deps = []
864                 for n in pkgconfig_needed[pkg]:
865                         found = False
866                         for k in pkgconfig_provided.keys():
867                                 if n in pkgconfig_provided[k]:
868                                         if k != pkg and not (k in deps):
869                                                 deps.append(k)
870                                         found = True
871                         if found == False:
872                                 bb.note("couldn't find pkgconfig module '%s' in any package" % n)
873                 deps_file = os.path.join(pkgdest, pkg + ".pcdeps")
874                 if os.path.exists(deps_file):
875                         os.remove(deps_file)
876                 if len(deps):
877                         fd = open(deps_file, 'w')
878                         for dep in deps:
879                                 fd.write(dep + '\n')
880                         fd.close()
881                         package_stagefile(deps_file, d)
883         if pstageactive == "1":
884                 bb.utils.unlockfile(lf)
887 python read_shlibdeps () {
888         packages = bb.data.getVar('PACKAGES', d, True).split()
889         for pkg in packages:
890                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
891                 for extension in ".shlibdeps", ".pcdeps", ".clilibdeps":
892                         depsfile = bb.data.expand("${PKGDEST}/" + pkg + extension, d)
893                         if os.access(depsfile, os.R_OK):
894                                 fd = file(depsfile)
895                                 lines = fd.readlines()
896                                 fd.close()
897                                 for l in lines:
898                                         rdepends.append(l.rstrip())
899                 bb.data.setVar('RDEPENDS_' + pkg, " " + " ".join(rdepends), d)
902 python package_depchains() {
903         """
904         For a given set of prefix and postfix modifiers, make those packages
905         RRECOMMENDS on the corresponding packages for its RDEPENDS.
907         Example:  If package A depends upon package B, and A's .bb emits an
908         A-dev package, this would make A-dev Recommends: B-dev.
910         If only one of a given suffix is specified, it will take the RRECOMMENDS
911         based on the RDEPENDS of *all* other packages. If more than one of a given 
912         suffix is specified, its will only use the RDEPENDS of the single parent 
913         package.
914         """
916         packages  = bb.data.getVar('PACKAGES', d, True)
917         postfixes = (bb.data.getVar('DEPCHAIN_POST', d, True) or '').split()
918         prefixes  = (bb.data.getVar('DEPCHAIN_PRE', d, True) or '').split()
920         def pkg_adddeprrecs(pkg, base, suffix, getname, depends, d):
922                 #bb.note('depends for %s is %s' % (base, depends))
923                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, True) or bb.data.getVar('RRECOMMENDS', d, True) or "")
925                 for depend in depends:
926                         if depend.find('-native') != -1 or depend.find('-cross') != -1 or depend.startswith('virtual/'):
927                                 #bb.note("Skipping %s" % depend)
928                                 continue
929                         if depend.endswith('-dev'):
930                                 depend = depend.replace('-dev', '')
931                         if depend.endswith('-dbg'):
932                                 depend = depend.replace('-dbg', '')
933                         pkgname = getname(depend, suffix)
934                         #bb.note("Adding %s for %s" % (pkgname, depend))
935                         if not pkgname in rreclist:
936                                 rreclist.append(pkgname)
938                 #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
939                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
941         def pkg_addrrecs(pkg, base, suffix, getname, rdepends, d):
943                 #bb.note('rdepends for %s is %s' % (base, rdepends))
944                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, True) or bb.data.getVar('RRECOMMENDS', d, True) or "")
946                 for depend in rdepends:
947                         if depend.endswith('-dev'):
948                                 depend = depend.replace('-dev', '')
949                         if depend.endswith('-dbg'):
950                                 depend = depend.replace('-dbg', '')
951                         pkgname = getname(depend, suffix)
952                         if not pkgname in rreclist:
953                                 rreclist.append(pkgname)
955                 #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
956                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
958         def add_dep(list, dep):
959                 dep = dep.split(' (')[0].strip()
960                 if dep not in list:
961                         list.append(dep)
963         depends = []
964         for dep in explode_deps(bb.data.getVar('DEPENDS', d, True) or ""):
965                 add_dep(depends, dep)
967         rdepends = []
968         for dep in explode_deps(bb.data.getVar('RDEPENDS', d, True) or ""):
969                 add_dep(rdepends, dep)
971         for pkg in packages.split():
972                 for dep in explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, True) or ""):
973                         add_dep(rdepends, dep)
975         #bb.note('rdepends is %s' % rdepends)
977         def post_getname(name, suffix):
978                 return '%s%s' % (name, suffix)
979         def pre_getname(name, suffix):
980                 return '%s%s' % (suffix, name)
982         pkgs = {}
983         for pkg in packages.split():
984                 for postfix in postfixes:
985                         if pkg.endswith(postfix):
986                                 if not postfix in pkgs:
987                                         pkgs[postfix] = {}
988                                 pkgs[postfix][pkg] = (pkg[:-len(postfix)], post_getname)
990                 for prefix in prefixes:
991                         if pkg.startswith(prefix):
992                                 if not prefix in pkgs:
993                                         pkgs[prefix] = {}
994                                 pkgs[prefix][pkg] = (pkg[:-len(prefix)], pre_getname)
996         for suffix in pkgs:
997                 for pkg in pkgs[suffix]:
998                         (base, func) = pkgs[suffix][pkg]
999                         if suffix == "-dev" and not pkg.startswith("kernel-module-"):
1000                                 pkg_adddeprrecs(pkg, base, suffix, func, depends, d)
1001                         if len(pkgs[suffix]) == 1:
1002                                 pkg_addrrecs(pkg, base, suffix, func, rdepends, d)
1003                         else:
1004                                 rdeps = []
1005                                 for dep in explode_deps(bb.data.getVar('RDEPENDS_' + base, d, True) or bb.data.getVar('RDEPENDS', d, True) or ""):
1006                                         add_dep(rdeps, dep)
1007                                 pkg_addrrecs(pkg, base, suffix, func, rdeps, d)
1010 PACKAGE_PREPROCESS_FUNCS ?= ""
1011 PACKAGEFUNCS ?= "perform_packagecopy \
1012                 ${PACKAGE_PREPROCESS_FUNCS} \
1013                 package_do_split_locales \
1014                 populate_packages \
1015                 package_do_shlibs \
1016                 package_do_pkgconfig \
1017                 read_shlibdeps \
1018                 package_depchains \
1019                 emit_pkgdata"
1021 def package_run_hooks(f, d):
1022         import bb, os
1023         staging = bb.data.getVar('PKGDATA_DIR', d, True)
1024         dn = os.path.join(staging, 'hooks', f)
1025         if os.access(dn, os.R_OK):
1026                 for f in os.listdir(dn):
1027                         fn = os.path.join(dn, f)
1028                         fp = open(fn, 'r')
1029                         line = 0
1030                         for l in fp.readlines():
1031                                 l = l.rstrip()
1032                                 bb.parse.parse_py.BBHandler.feeder(line, l, fn, os.path.basename(fn), d)
1033                                 line += 1
1034                         fp.close()
1035                         anonqueue = bb.data.getVar("__anonqueue", d, True) or []
1036                         body = [x['content'] for x in anonqueue]
1037                         flag = { 'python' : 1, 'func' : 1 }
1038                         bb.data.setVar("__anonfunc", "\n".join(body), d)
1039                         bb.data.setVarFlags("__anonfunc", flag, d)
1040                         try:
1041                                 t = bb.data.getVar('T', d)
1042                                 bb.data.setVar('T', '${TMPDIR}/', d)
1043                                 bb.build.exec_func("__anonfunc", d)
1044                                 bb.data.delVar('T', d)
1045                                 if t:
1046                                         bb.data.setVar('T', t, d)
1047                         except Exception, e:
1048                                 bb.msg.debug(1, bb.msg.domain.Parsing, "Exception when executing anonymous function: %s" % e)
1049                                 raise
1050                         bb.data.delVar("__anonqueue", d)
1051                         bb.data.delVar("__anonfunc", d)
1053 python package_do_package () {
1054         packages = (bb.data.getVar('PACKAGES', d, True) or "").split()
1055         if len(packages) < 1:
1056                 bb.debug(1, "No packages to build, skipping do_package")
1057                 return
1059         workdir = bb.data.getVar('WORKDIR', d, True)
1060         outdir = bb.data.getVar('DEPLOY_DIR', d, True)
1061         dest = bb.data.getVar('D', d, True)
1062         dvar = bb.data.getVar('PKGD', d, True)
1063         pn = bb.data.getVar('PN', d, True)
1065         if not workdir or not outdir or not dest or not dvar or not pn or not packages:
1066                 bb.error("WORKDIR, DEPLOY_DIR, D, PN and PKGD all must be defined, unable to package")
1067                 return
1069         for f in (bb.data.getVar('PACKAGEFUNCS', d, True) or '').split():
1070                 bb.build.exec_func(f, d)
1071                 package_run_hooks(f, d)
1073 do_package[dirs] = "${D}"
1074 addtask package before do_build after do_install
1076 # Dummy task to mark when all packaging is complete
1077 do_package_write () {
1078         :
1080 addtask package_write before do_build after do_package
1082 EXPORT_FUNCTIONS do_package do_package_write
1085 # Helper functions for the package writing classes
1088 python package_mapping_rename_hook () {
1089         """
1090         Rewrite variables to account for package renaming in things
1091         like debian.bbclass or manual PKG variable name changes
1092         """
1093         runtime_mapping_rename("RDEPENDS", d)
1094         runtime_mapping_rename("RRECOMMENDS", d)
1095         runtime_mapping_rename("RSUGGESTS", d)
1096         runtime_mapping_rename("RPROVIDES", d)
1097         runtime_mapping_rename("RREPLACES", d)
1098         runtime_mapping_rename("RCONFLICTS", d)
1101 EXPORT_FUNCTIONS mapping_rename_hook