Merge branch 'org.openembedded.dev' of git@git.openembedded.org:openembedded into...
[openembedded.git] / classes / package.bbclass
blobf6bd7c5b4a06e1f2c81347d5aad304c64d8d100a
2 # General packaging help functions
5 PKGDEST = "${WORKDIR}/install"
7 def legitimize_package_name(s):
8         """
9         Make sure package names are legitimate strings
10         """
11         import re
13         def fixutf(m):
14                 cp = m.group(1)
15                 if cp:
16                         return ('\u%s' % cp).decode('unicode_escape').encode('utf-8')
18         # Handle unicode codepoints encoded as <U0123>, as in glibc locale files.
19         s = re.sub('<U([0-9A-Fa-f]{1,4})>', fixutf, s)
21         # Remaining package name validity fixes
22         return s.lower().replace('_', '-').replace('@', '+').replace(',', '+').replace('/', '-')
24 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):
25         """
26         Used in .bb files to split up dynamically generated subpackages of a 
27         given package, usually plugins or modules.
28         """
29         import os, os.path, bb
31         dvar = bb.data.getVar('D', d, 1)
32         if not dvar:
33                 bb.error("D not defined")
34                 return
36         packages = bb.data.getVar('PACKAGES', d, 1).split()
38         if postinst:
39                 postinst = '#!/bin/sh\n' + postinst + '\n'
40         if postrm:
41                 postrm = '#!/bin/sh\n' + postrm + '\n'
42         if not recursive:
43                 objs = os.listdir(dvar + root)
44         else:
45                 objs = []
46                 for walkroot, dirs, files in os.walk(dvar + root):
47                         for file in files:
48                                 relpath = os.path.join(walkroot, file).replace(dvar + root + '/', '', 1)
49                                 if relpath:
50                                         objs.append(relpath)
52         if extra_depends == None:
53                 # This is *really* broken
54                 mainpkg = packages[0]
55                 # At least try and patch it up I guess...
56                 if mainpkg.find('-dbg'):
57                         mainpkg = mainpkg.replace('-dbg', '')
58                 if mainpkg.find('-dev'):
59                         mainpkg = mainpkg.replace('-dev', '')
60                 extra_depends = mainpkg
62         for o in objs:
63                 import re, stat
64                 if match_path:
65                         m = re.match(file_regex, o)
66                 else:
67                         m = re.match(file_regex, os.path.basename(o))
68                 
69                 if not m:
70                         continue
71                 f = os.path.join(dvar + root, o)
72                 mode = os.lstat(f).st_mode
73                 if not (stat.S_ISREG(mode) or (allow_links and stat.S_ISLNK(mode)) or (allow_dirs and stat.S_ISDIR(mode))):
74                         continue
75                 on = legitimize_package_name(m.group(1))
76                 pkg = output_pattern % on
77                 if not pkg in packages:
78                         if prepend:
79                                 packages = [pkg] + packages
80                         else:
81                                 packages.append(pkg)
82                         the_files = [os.path.join(root, o)]
83                         if aux_files_pattern:
84                                 if type(aux_files_pattern) is list:
85                                         for fp in aux_files_pattern:
86                                                 the_files.append(fp % on)       
87                                 else:
88                                         the_files.append(aux_files_pattern % on)
89                         if aux_files_pattern_verbatim:
90                                 if type(aux_files_pattern_verbatim) is list:
91                                         for fp in aux_files_pattern_verbatim:
92                                                 the_files.append(fp % m.group(1))       
93                                 else:
94                                         the_files.append(aux_files_pattern_verbatim % m.group(1))
95                         bb.data.setVar('FILES_' + pkg, " ".join(the_files), d)
96                         if extra_depends != '':
97                                 the_depends = bb.data.getVar('RDEPENDS_' + pkg, d, 1)
98                                 if the_depends:
99                                         the_depends = '%s %s' % (the_depends, extra_depends)
100                                 else:
101                                         the_depends = extra_depends
102                                 bb.data.setVar('RDEPENDS_' + pkg, the_depends, d)
103                         bb.data.setVar('DESCRIPTION_' + pkg, description % on, d)
104                         if postinst:
105                                 bb.data.setVar('pkg_postinst_' + pkg, postinst, d)
106                         if postrm:
107                                 bb.data.setVar('pkg_postrm_' + pkg, postrm, d)
108                 else:
109                         oldfiles = bb.data.getVar('FILES_' + pkg, d, 1)
110                         if not oldfiles:
111                                 bb.fatal("Package '%s' exists but has no files" % pkg)
112                         bb.data.setVar('FILES_' + pkg, oldfiles + " " + os.path.join(root, o), d)
113                 if callable(hook):
114                         hook(f, pkg, file_regex, output_pattern, m.group(1))
116         bb.data.setVar('PACKAGES', ' '.join(packages), d)
118 PACKAGE_DEPENDS += "file-native"
120 def package_stash_hook(func, name, d):
121         import bb, os.path
122         body = bb.data.getVar(func, d, True)
123         pn = bb.data.getVar('PN', d, True)
124         staging = bb.data.getVar('PKGDATA_DIR', d, True)
125         dirname = os.path.join(staging, 'hooks', name)
126         bb.mkdirhier(dirname)
127         fn = os.path.join(dirname, pn)
128         f = open(fn, 'w')
129         f.write("python () {\n");
130         f.write(body);
131         f.write("}\n");
132         f.close()
134 python () {
135     import bb
136     if bb.data.getVar('PACKAGES', d, True) != '':
137         deps = bb.data.getVarFlag('do_package', 'depends', d) or ""
138         for dep in (bb.data.getVar('PACKAGE_DEPENDS', d, True) or "").split():
139             deps += " %s:do_populate_staging" % dep
140         bb.data.setVarFlag('do_package', 'depends', deps, d)
142         deps = (bb.data.getVarFlag('do_package', 'deptask', d) or "").split()
143         # shlibs requires any DEPENDS to have already packaged for the *.list files
144         deps.append("do_package")
145         bb.data.setVarFlag('do_package', 'deptask', " ".join(deps), d)
148 def runstrip(file, d):
149     # Function to strip a single file, called from populate_packages below
150     # A working 'file' (one which works on the target architecture)
151     # is necessary for this stuff to work, hence the addition to do_package[depends]
153     import bb, os, commands, stat
155     pathprefix = "export PATH=%s; " % bb.data.getVar('PATH', d, 1)
157     ret, result = commands.getstatusoutput("%sfile '%s'" % (pathprefix, file))
159     if ret:
160         bb.error("runstrip: 'file %s' failed (forced strip)" % file)
162     if "not stripped" not in result:
163         bb.debug(1, "runstrip: skip %s" % file)
164         return 0
166     # If the file is in a .debug directory it was already stripped,
167     # don't do it again...
168     if os.path.dirname(file).endswith(".debug"):
169         bb.debug(2, "Already ran strip on %s" % file)
170         return 0
172     strip = bb.data.getVar("STRIP", d, 1)
173     objcopy = bb.data.getVar("OBJCOPY", d, 1)
175     newmode = None
176     if not os.access(file, os.W_OK):
177         origmode = os.stat(file)[stat.ST_MODE]
178         newmode = origmode | stat.S_IWRITE
179         os.chmod(file, newmode)
181     extraflags = ""
182     if ".so" in file and "shared" in result:
183         extraflags = "--remove-section=.comment --remove-section=.note --strip-unneeded"
184     elif "shared" in result or "executable" in result:
185         extraflags = "--remove-section=.comment --remove-section=.note"
187     bb.mkdirhier(os.path.join(os.path.dirname(file), ".debug"))
188     debugfile=os.path.join(os.path.dirname(file), ".debug", os.path.basename(file))
190     stripcmd = "'%s' %s '%s'" % (strip, extraflags, file)
191     bb.debug(1, "runstrip: %s" % stripcmd)
193     os.system("%s'%s' --only-keep-debug '%s' '%s'" % (pathprefix, objcopy, file, debugfile))
194     ret = os.system("%s%s" % (pathprefix, stripcmd))
195     os.system("%s'%s' --add-gnu-debuglink='%s' '%s'" % (pathprefix, objcopy, debugfile, file))
197     if newmode:
198         os.chmod(file, origmode)
200     if ret:
201         bb.error("runstrip: '%s' strip command failed" % stripcmd)
203     return 1
206 # Package data handling routines
209 def get_package_mapping (pkg, d):
210         import bb, os
212         data = read_subpkgdata(pkg, d)
213         key = "PKG_%s" % pkg
215         if key in data:
216                 return data[key]
218         return pkg
220 def runtime_mapping_rename (varname, d):
221         import bb, os
223         #bb.note("%s before: %s" % (varname, bb.data.getVar(varname, d, 1)))    
225         new_depends = []
226         for depend in explode_deps(bb.data.getVar(varname, d, 1) or ""):
227                 # Have to be careful with any version component of the depend
228                 split_depend = depend.split(' (')
229                 new_depend = get_package_mapping(split_depend[0].strip(), d)
230                 if len(split_depend) > 1:
231                         new_depends.append("%s (%s" % (new_depend, split_depend[1]))
232                 else:
233                         new_depends.append(new_depend)
235         bb.data.setVar(varname, " ".join(new_depends) or None, d)
237         #bb.note("%s after: %s" % (varname, bb.data.getVar(varname, d, 1)))
240 # Package functions suitable for inclusion in PACKAGEFUNCS
243 python package_do_split_locales() {
244         import os
246         if (bb.data.getVar('PACKAGE_NO_LOCALE', d, 1) == '1'):
247                 bb.debug(1, "package requested not splitting locales")
248                 return
250         packages = (bb.data.getVar('PACKAGES', d, 1) or "").split()
252         datadir = bb.data.getVar('datadir', d, 1)
253         if not datadir:
254                 bb.note("datadir not defined")
255                 return
257         dvar = bb.data.getVar('D', d, 1)
258         if not dvar:
259                 bb.error("D not defined")
260                 return
262         pn = bb.data.getVar('PN', d, 1)
263         if not pn:
264                 bb.error("PN not defined")
265                 return
267         if pn + '-locale' in packages:
268                 packages.remove(pn + '-locale')
270         localedir = os.path.join(dvar + datadir, 'locale')
272         if not os.path.isdir(localedir):
273                 bb.debug(1, "No locale files in this package")
274                 return
276         locales = os.listdir(localedir)
278         # This is *really* broken
279         mainpkg = packages[0]
280         # At least try and patch it up I guess...
281         if mainpkg.find('-dbg'):
282                 mainpkg = mainpkg.replace('-dbg', '')
283         if mainpkg.find('-dev'):
284                 mainpkg = mainpkg.replace('-dev', '')
286         for l in locales:
287                 ln = legitimize_package_name(l)
288                 pkg = pn + '-locale-' + ln
289                 packages.append(pkg)
290                 bb.data.setVar('FILES_' + pkg, os.path.join(datadir, 'locale', l), d)
291                 bb.data.setVar('RDEPENDS_' + pkg, '%s virtual-locale-%s' % (mainpkg, ln), d)
292                 bb.data.setVar('RPROVIDES_' + pkg, '%s-locale %s-translation' % (pn, ln), d)
293                 bb.data.setVar('DESCRIPTION_' + pkg, '%s translation for %s' % (l, pn), d)
295         bb.data.setVar('PACKAGES', ' '.join(packages), d)
298 python populate_packages () {
299         import glob, stat, errno, re
301         workdir = bb.data.getVar('WORKDIR', d, 1)
302         if not workdir:
303                 bb.error("WORKDIR not defined, unable to package")
304                 return
306         import os # path manipulations
307         outdir = bb.data.getVar('DEPLOY_DIR', d, 1)
308         if not outdir:
309                 bb.error("DEPLOY_DIR not defined, unable to package")
310                 return
311         bb.mkdirhier(outdir)
313         dvar = bb.data.getVar('D', d, 1)
314         if not dvar:
315                 bb.error("D not defined, unable to package")
316                 return
317         bb.mkdirhier(dvar)
319         packages = bb.data.getVar('PACKAGES', d, 1)
321         pn = bb.data.getVar('PN', d, 1)
322         if not pn:
323                 bb.error("PN not defined")
324                 return
326         os.chdir(dvar)
328         def isexec(path):
329                 try:
330                         s = os.stat(path)
331                 except (os.error, AttributeError):
332                         return 0
333                 return (s[stat.ST_MODE] & stat.S_IEXEC)
335         # Sanity check PACKAGES for duplicates - should be moved to 
336         # sanity.bbclass once we have the infrastucture
337         package_list = []
338         for pkg in packages.split():
339                 if pkg in package_list:
340                         bb.error("-------------------")
341                         bb.error("%s is listed in PACKAGES multiple times, this leads to packaging errors." % pkg)
342                         bb.error("Please fix the metadata/report this as bug to OE bugtracker.")
343                         bb.error("-------------------")
344                 else:
345                         package_list.append(pkg)
347         if (bb.data.getVar('INHIBIT_PACKAGE_STRIP', d, 1) != '1'):
348                 for root, dirs, files in os.walk(dvar):
349                         for f in files:
350                                 file = os.path.join(root, f)
351                                 if not os.path.islink(file) and not os.path.isdir(file) and isexec(file):
352                                         runstrip(file, d)
354         pkgdest = bb.data.getVar('PKGDEST', d, 1)
355         os.system('rm -rf %s' % pkgdest)
357         seen = []
358         main_is_empty = 1
359         main_pkg = bb.data.getVar('PN', d, 1)
361         for pkg in package_list:
362                 localdata = bb.data.createCopy(d)
363                 root = os.path.join(pkgdest, pkg)
364                 bb.mkdirhier(root)
366                 bb.data.setVar('PKG', pkg, localdata)
367                 overrides = bb.data.getVar('OVERRIDES', localdata, 1)
368                 if not overrides:
369                         raise bb.build.FuncFailed('OVERRIDES not defined')
370                 bb.data.setVar('OVERRIDES', overrides + ':' + pkg, localdata)
371                 bb.data.update_data(localdata)
373                 filesvar = bb.data.getVar('FILES', localdata, 1) or ""
374                 files = filesvar.split()
375                 for file in files:
376                         if os.path.isabs(file):
377                                 file = '.' + file
378                         if not os.path.islink(file):
379                                 if os.path.isdir(file):
380                                         newfiles =  [ os.path.join(file,x) for x in os.listdir(file) ]
381                                         if newfiles:
382                                                 files += newfiles
383                                                 continue
384                         globbed = glob.glob(file)
385                         if globbed:
386                                 if [ file ] != globbed:
387                                         if not file in globbed:
388                                                 files += globbed
389                                                 continue
390                                         else:
391                                                 globbed.remove(file)
392                                                 files += globbed
393                         if (not os.path.islink(file)) and (not os.path.exists(file)):
394                                 continue
395                         if file in seen:
396                                 continue
397                         seen.append(file)
398                         if os.path.isdir(file) and not os.path.islink(file):
399                                 bb.mkdirhier(os.path.join(root,file))
400                                 os.chmod(os.path.join(root,file), os.stat(file).st_mode)
401                                 continue
402                         fpath = os.path.join(root,file)
403                         dpath = os.path.dirname(fpath)
404                         bb.mkdirhier(dpath)
405                         ret = bb.copyfile(file, fpath)
406                         if ret is False or ret == 0:
407                                 raise bb.build.FuncFailed("File population failed")
408                         if pkg == main_pkg and main_is_empty:
409                                 main_is_empty = 0
410                 del localdata
411         os.chdir(workdir)
413         unshipped = []
414         for root, dirs, files in os.walk(dvar):
415                 for f in files:
416                         path = os.path.join(root[len(dvar):], f)
417                         if ('.' + path) not in seen:
418                                 unshipped.append(path)
420         if unshipped != []:
421                 bb.note("the following files were installed but not shipped in any package:")
422                 for f in unshipped:
423                         bb.note("  " + f)
425         bb.build.exec_func("package_name_hook", d)
427         for pkg in package_list:
428                 pkgname = bb.data.getVar('PKG_%s' % pkg, d, 1)
429                 if pkgname is None:
430                         bb.data.setVar('PKG_%s' % pkg, pkg, d)
432         dangling_links = {}
433         pkg_files = {}
434         for pkg in package_list:
435                 dangling_links[pkg] = []
436                 pkg_files[pkg] = []
437                 inst_root = os.path.join(pkgdest, pkg)
438                 for root, dirs, files in os.walk(inst_root):
439                         for f in files:
440                                 path = os.path.join(root, f)
441                                 rpath = path[len(inst_root):]
442                                 pkg_files[pkg].append(rpath)
443                                 try:
444                                         s = os.stat(path)
445                                 except OSError, (err, strerror):
446                                         if err != errno.ENOENT:
447                                                 raise
448                                         target = os.readlink(path)
449                                         if target[0] != '/':
450                                                 target = os.path.join(root[len(inst_root):], target)
451                                         dangling_links[pkg].append(os.path.normpath(target))
453         for pkg in package_list:
454                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
456                 remstr = "${PN} (= ${EXTENDPV})"
457                 if main_is_empty and remstr in rdepends:
458                         rdepends.remove(remstr)
459                 for l in dangling_links[pkg]:
460                         found = False
461                         bb.debug(1, "%s contains dangling link %s" % (pkg, l))
462                         for p in package_list:
463                                 for f in pkg_files[p]:
464                                         if f == l:
465                                                 found = True
466                                                 bb.debug(1, "target found in %s" % p)
467                                                 if p == pkg:
468                                                         break
469                                                 if not p in rdepends:
470                                                         rdepends.append(p)
471                                                 break
472                         if found == False:
473                                 bb.note("%s contains dangling symlink to %s" % (pkg, l))
474                 bb.data.setVar('RDEPENDS_' + pkg, " " + " ".join(rdepends), d)
476 populate_packages[dirs] = "${D}"
478 python emit_pkgdata() {
479         from glob import glob
481         def write_if_exists(f, pkg, var):
482                 def encode(str):
483                         import codecs
484                         c = codecs.getencoder("string_escape")
485                         return c(str)[0]
487                 val = bb.data.getVar('%s_%s' % (var, pkg), d, 1)
488                 if val:
489                         f.write('%s_%s: %s\n' % (var, pkg, encode(val)))
490                         return
491                 val = bb.data.getVar('%s' % (var), d, 1)
492                 if val:
493                         f.write('%s: %s\n' % (var, encode(val)))
494                 return
496         packages = bb.data.getVar('PACKAGES', d, True)
497         pkgdatadir = bb.data.getVar('PKGDATA_DIR', d, True)
499         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
500         if pstageactive == "1":
501                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
503         data_file = pkgdatadir + bb.data.expand("/${PN}" , d)
504         f = open(data_file, 'w')
505         f.write("PACKAGES: %s\n" % packages)
506         f.close()
507         package_stagefile(data_file, d)
509         workdir = bb.data.getVar('WORKDIR', d, 1)
511         for pkg in packages.split():
512                 subdata_file = pkgdatadir + "/runtime/%s" % pkg
513                 sf = open(subdata_file, 'w')
514                 write_if_exists(sf, pkg, 'PN')
515                 write_if_exists(sf, pkg, 'PV')
516                 write_if_exists(sf, pkg, 'PR')
517                 write_if_exists(sf, pkg, 'DESCRIPTION')
518                 write_if_exists(sf, pkg, 'RDEPENDS')
519                 write_if_exists(sf, pkg, 'RPROVIDES')
520                 write_if_exists(sf, pkg, 'RRECOMMENDS')
521                 write_if_exists(sf, pkg, 'RSUGGESTS')
522                 write_if_exists(sf, pkg, 'RREPLACES')
523                 write_if_exists(sf, pkg, 'RCONFLICTS')
524                 write_if_exists(sf, pkg, 'PKG')
525                 write_if_exists(sf, pkg, 'ALLOW_EMPTY')
526                 write_if_exists(sf, pkg, 'FILES')
527                 write_if_exists(sf, pkg, 'pkg_postinst')
528                 write_if_exists(sf, pkg, 'pkg_postrm')
529                 write_if_exists(sf, pkg, 'pkg_preinst')
530                 write_if_exists(sf, pkg, 'pkg_prerm')
531                 sf.close()
533                 package_stagefile(subdata_file, d)
534                 #if pkgdatadir2:
535                 #       bb.copyfile(subdata_file, pkgdatadir2 + "/runtime/%s" % pkg)
537                 allow_empty = bb.data.getVar('ALLOW_EMPTY_%s' % pkg, d, 1)
538                 if not allow_empty:
539                         allow_empty = bb.data.getVar('ALLOW_EMPTY', d, 1)
540                 root = "%s/install/%s" % (workdir, pkg)
541                 os.chdir(root)
542                 g = glob('*') + glob('.[!.]*')
543                 if g or allow_empty == "1":
544                         packagedfile = pkgdatadir + '/runtime/%s.packaged' % pkg
545                         file(packagedfile, 'w').close()
546                         package_stagefile(packagedfile, d)
547         if pstageactive == "1":
548                 bb.utils.unlockfile(lf)
550 emit_pkgdata[dirs] = "${PKGDATA_DIR}/runtime"
552 ldconfig_postinst_fragment() {
553 if [ x"$D" = "x" ]; then
554         if [ -e /etc/ld.so.conf ] ; then
555                 [ -x /sbin/ldconfig ] && /sbin/ldconfig
556         fi
560 SHLIBSDIR = "${STAGING_DIR_HOST}/shlibs"
562 python package_do_shlibs() {
563         import os, re, os.path
565         exclude_shlibs = bb.data.getVar('EXCLUDE_FROM_SHLIBS', d, 0)
566         if exclude_shlibs:
567                 bb.debug(1, "not generating shlibs")
568                 return
569                 
570         lib_re = re.compile("^lib.*\.so")
571         libdir_re = re.compile(".*/lib$")
573         packages = bb.data.getVar('PACKAGES', d, 1)
575         workdir = bb.data.getVar('WORKDIR', d, 1)
576         if not workdir:
577                 bb.error("WORKDIR not defined")
578                 return
580         ver = bb.data.getVar('PV', d, 1)
581         if not ver:
582                 bb.error("PV not defined")
583                 return
585         pkgdest = bb.data.getVar('PKGDEST', d, 1)
587         shlibs_dir = bb.data.getVar('SHLIBSDIR', d, 1)
588         bb.mkdirhier(shlibs_dir)
590         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
591         if pstageactive == "1":
592                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
594         if bb.data.getVar('PACKAGE_SNAP_LIB_SYMLINKS', d, True) == "1":
595                 snap_symlinks = True
596         else:
597                 snap_symlinks = False
599         if (bb.data.getVar('USE_LDCONFIG', d, True) or "1") == "1":
600                 use_ldconfig = True
601         else:
602                 use_ldconfig = False
604         needed = {}
605         private_libs = bb.data.getVar('PRIVATE_LIBS', d, 1)
606         for pkg in packages.split():
607                 needs_ldconfig = False
608                 bb.debug(2, "calculating shlib provides for %s" % pkg)
610                 needed[pkg] = []
611                 sonames = list()
612                 top = os.path.join(pkgdest, pkg)
613                 renames = []
614                 for root, dirs, files in os.walk(top):
615                         for file in files:
616                                 soname = None
617                                 path = os.path.join(root, file)
618                                 if (os.access(path, os.X_OK) or lib_re.match(file)) and not os.path.islink(path):
619                                         cmd = bb.data.getVar('OBJDUMP', d, 1) + " -p " + path + " 2>/dev/null"
620                                         cmd = "PATH=\"%s\" %s" % (bb.data.getVar('PATH', d, 1), cmd)
621                                         fd = os.popen(cmd)
622                                         lines = fd.readlines()
623                                         fd.close()
624                                         for l in lines:
625                                                 m = re.match("\s+NEEDED\s+([^\s]*)", l)
626                                                 if m:
627                                                         needed[pkg].append(m.group(1))
628                                                 m = re.match("\s+SONAME\s+([^\s]*)", l)
629                                                 if m:
630                                                         this_soname = m.group(1)
631                                                         if not this_soname in sonames:
632                                                                 # if library is private (only used by package) then do not build shlib for it
633                                                                 if not private_libs or -1 == private_libs.find(this_soname):
634                                                                         sonames.append(this_soname)
635                                                         if libdir_re.match(root):
636                                                                 needs_ldconfig = True
637                                                         if snap_symlinks and (file != soname):
638                                                                 renames.append((path, os.path.join(root, this_soname)))
639                 for (old, new) in renames:
640                         os.rename(old, new)
641                 shlibs_file = os.path.join(shlibs_dir, pkg + ".list")
642                 if os.path.exists(shlibs_file):
643                         os.remove(shlibs_file)
644                 shver_file = os.path.join(shlibs_dir, pkg + ".ver")
645                 if os.path.exists(shver_file):
646                         os.remove(shver_file)
647                 if len(sonames):
648                         fd = open(shlibs_file, 'w')
649                         for s in sonames:
650                                 fd.write(s + '\n')
651                         fd.close()
652                         package_stagefile(shlibs_file, d)
653                         fd = open(shver_file, 'w')
654                         fd.write(ver + '\n')
655                         fd.close()
656                         package_stagefile(shver_file, d)
657                 if needs_ldconfig and use_ldconfig:
658                         bb.debug(1, 'adding ldconfig call to postinst for %s' % pkg)
659                         postinst = bb.data.getVar('pkg_postinst_%s' % pkg, d, 1) or bb.data.getVar('pkg_postinst', d, 1)
660                         if not postinst:
661                                 postinst = '#!/bin/sh\n'
662                         postinst += bb.data.getVar('ldconfig_postinst_fragment', d, 1)
663                         bb.data.setVar('pkg_postinst_%s' % pkg, postinst, d)
665         if pstageactive == "1":
666                 bb.utils.unlockfile(lf)
668         shlib_provider = {}
669         list_re = re.compile('^(.*)\.list$')
670         for dir in [shlibs_dir]: 
671                 if not os.path.exists(dir):
672                         continue
673                 for file in os.listdir(dir):
674                         m = list_re.match(file)
675                         if m:
676                                 dep_pkg = m.group(1)
677                                 fd = open(os.path.join(dir, file))
678                                 lines = fd.readlines()
679                                 fd.close()
680                                 ver_file = os.path.join(dir, dep_pkg + '.ver')
681                                 lib_ver = None
682                                 if os.path.exists(ver_file):
683                                         fd = open(ver_file)
684                                         lib_ver = fd.readline().rstrip()
685                                         fd.close()
686                                 for l in lines:
687                                         shlib_provider[l.rstrip()] = (dep_pkg, lib_ver)
689         assumed_libs = bb.data.getVar('ASSUME_SHLIBS', d, 1)
690         if assumed_libs:
691             for e in assumed_libs.split():
692                 l, dep_pkg = e.split(":")
693                 lib_ver = None
694                 dep_pkg = dep_pkg.rsplit("_", 1)
695                 if len(dep_pkg) == 2:
696                     lib_ver = dep_pkg[1]
697                 dep_pkg = dep_pkg[0]
698                 shlib_provider[l] = (dep_pkg, lib_ver)
700         dep_packages = []
701         for pkg in packages.split():
702                 bb.debug(2, "calculating shlib requirements for %s" % pkg)
704                 deps = list()
705                 for n in needed[pkg]:
706                         if n in shlib_provider.keys():
707                                 (dep_pkg, ver_needed) = shlib_provider[n]
709                                 if dep_pkg == pkg:
710                                         continue
712                                 if ver_needed:
713                                         dep = "%s (>= %s)" % (dep_pkg, ver_needed)
714                                 else:
715                                         dep = dep_pkg
716                                 if not dep in deps:
717                                         deps.append(dep)
718                                 if not dep_pkg in dep_packages:
719                                         dep_packages.append(dep_pkg)
720                                         
721                         else:
722                                 bb.note("Couldn't find shared library provider for %s" % n)
724                 deps_file = os.path.join(pkgdest, pkg + ".shlibdeps")
725                 if os.path.exists(deps_file):
726                         os.remove(deps_file)
727                 if len(deps):
728                         fd = open(deps_file, 'w')
729                         for dep in deps:
730                                 fd.write(dep + '\n')
731                         fd.close()
734 python package_do_pkgconfig () {
735         import re, os
737         packages = bb.data.getVar('PACKAGES', d, 1)
739         workdir = bb.data.getVar('WORKDIR', d, 1)
740         if not workdir:
741                 bb.error("WORKDIR not defined")
742                 return
744         pkgdest = bb.data.getVar('PKGDEST', d, 1)
746         shlibs_dir = bb.data.getVar('SHLIBSDIR', d, 1)
747         bb.mkdirhier(shlibs_dir)
749         pc_re = re.compile('(.*)\.pc$')
750         var_re = re.compile('(.*)=(.*)')
751         field_re = re.compile('(.*): (.*)')
753         pkgconfig_provided = {}
754         pkgconfig_needed = {}
755         for pkg in packages.split():
756                 pkgconfig_provided[pkg] = []
757                 pkgconfig_needed[pkg] = []
758                 top = os.path.join(pkgdest, pkg)
759                 for root, dirs, files in os.walk(top):
760                         for file in files:
761                                 m = pc_re.match(file)
762                                 if m:
763                                         pd = bb.data.init()
764                                         name = m.group(1)
765                                         pkgconfig_provided[pkg].append(name)
766                                         path = os.path.join(root, file)
767                                         if not os.access(path, os.R_OK):
768                                                 continue
769                                         f = open(path, 'r')
770                                         lines = f.readlines()
771                                         f.close()
772                                         for l in lines:
773                                                 m = var_re.match(l)
774                                                 if m:
775                                                         name = m.group(1)
776                                                         val = m.group(2)
777                                                         bb.data.setVar(name, bb.data.expand(val, pd), pd)
778                                                         continue
779                                                 m = field_re.match(l)
780                                                 if m:
781                                                         hdr = m.group(1)
782                                                         exp = bb.data.expand(m.group(2), pd)
783                                                         if hdr == 'Requires':
784                                                                 pkgconfig_needed[pkg] += exp.replace(',', ' ').split()
786         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
787         if pstageactive == "1":
788                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
790         for pkg in packages.split():
791                 pkgs_file = os.path.join(shlibs_dir, pkg + ".pclist")
792                 if os.path.exists(pkgs_file):
793                         os.remove(pkgs_file)
794                 if pkgconfig_provided[pkg] != []:
795                         f = open(pkgs_file, 'w')
796                         for p in pkgconfig_provided[pkg]:
797                                 f.write('%s\n' % p)
798                         f.close()
799                         package_stagefile(pkgs_file, d)
801         for dir in [shlibs_dir]:
802                 if not os.path.exists(dir):
803                         continue
804                 for file in os.listdir(dir):
805                         m = re.match('^(.*)\.pclist$', file)
806                         if m:
807                                 pkg = m.group(1)
808                                 fd = open(os.path.join(dir, file))
809                                 lines = fd.readlines()
810                                 fd.close()
811                                 pkgconfig_provided[pkg] = []
812                                 for l in lines:
813                                         pkgconfig_provided[pkg].append(l.rstrip())
815         for pkg in packages.split():
816                 deps = []
817                 for n in pkgconfig_needed[pkg]:
818                         found = False
819                         for k in pkgconfig_provided.keys():
820                                 if n in pkgconfig_provided[k]:
821                                         if k != pkg and not (k in deps):
822                                                 deps.append(k)
823                                         found = True
824                         if found == False:
825                                 bb.note("couldn't find pkgconfig module '%s' in any package" % n)
826                 deps_file = os.path.join(pkgdest, pkg + ".pcdeps")
827                 if os.path.exists(deps_file):
828                         os.remove(deps_file)
829                 if len(deps):
830                         fd = open(deps_file, 'w')
831                         for dep in deps:
832                                 fd.write(dep + '\n')
833                         fd.close()
834                         package_stagefile(deps_file, d)
836         if pstageactive == "1":
837                 bb.utils.unlockfile(lf)
840 python read_shlibdeps () {
841         packages = bb.data.getVar('PACKAGES', d, 1).split()
842         for pkg in packages:
843                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
844                 for extension in ".shlibdeps", ".pcdeps", ".clilibdeps":
845                         depsfile = bb.data.expand("${PKGDEST}/" + pkg + extension, d)
846                         if os.access(depsfile, os.R_OK):
847                                 fd = file(depsfile)
848                                 lines = fd.readlines()
849                                 fd.close()
850                                 for l in lines:
851                                         rdepends.append(l.rstrip())
852                 bb.data.setVar('RDEPENDS_' + pkg, " " + " ".join(rdepends), d)
855 python package_depchains() {
856         """
857         For a given set of prefix and postfix modifiers, make those packages
858         RRECOMMENDS on the corresponding packages for its RDEPENDS.
860         Example:  If package A depends upon package B, and A's .bb emits an
861         A-dev package, this would make A-dev Recommends: B-dev.
863         If only one of a given suffix is specified, it will take the RRECOMMENDS
864         based on the RDEPENDS of *all* other packages. If more than one of a given 
865         suffix is specified, its will only use the RDEPENDS of the single parent 
866         package.
867         """
869         packages  = bb.data.getVar('PACKAGES', d, 1)
870         postfixes = (bb.data.getVar('DEPCHAIN_POST', d, 1) or '').split()
871         prefixes  = (bb.data.getVar('DEPCHAIN_PRE', d, 1) or '').split()
873         def pkg_adddeprrecs(pkg, base, suffix, getname, depends, d):
875                 #bb.note('depends for %s is %s' % (base, depends))
876                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, 1) or bb.data.getVar('RRECOMMENDS', d, 1) or "")
878                 for depend in depends:
879                         if depend.find('-native') != -1 or depend.find('-cross') != -1 or depend.startswith('virtual/'):
880                                 #bb.note("Skipping %s" % depend)
881                                 continue
882                         if depend.endswith('-dev'):
883                                 depend = depend.replace('-dev', '')
884                         if depend.endswith('-dbg'):
885                                 depend = depend.replace('-dbg', '')
886                         pkgname = getname(depend, suffix)
887                         #bb.note("Adding %s for %s" % (pkgname, depend))
888                         if not pkgname in rreclist:
889                                 rreclist.append(pkgname)
891                 #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
892                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
894         def pkg_addrrecs(pkg, base, suffix, getname, rdepends, d):
896                 #bb.note('rdepends for %s is %s' % (base, rdepends))
897                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, 1) or bb.data.getVar('RRECOMMENDS', d, 1) or "")
899                 for depend in rdepends:
900                         if depend.endswith('-dev'):
901                                 depend = depend.replace('-dev', '')
902                         if depend.endswith('-dbg'):
903                                 depend = depend.replace('-dbg', '')
904                         pkgname = getname(depend, suffix)
905                         if not pkgname in rreclist:
906                                 rreclist.append(pkgname)
908                 #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
909                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
911         def add_dep(list, dep):
912                 dep = dep.split(' (')[0].strip()
913                 if dep not in list:
914                         list.append(dep)
916         depends = []
917         for dep in explode_deps(bb.data.getVar('DEPENDS', d, 1) or ""):
918                 add_dep(depends, dep)
920         rdepends = []
921         for dep in explode_deps(bb.data.getVar('RDEPENDS', d, 1) or ""):
922                 add_dep(rdepends, dep)
924         for pkg in packages.split():
925                 for dep in explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 1) or ""):
926                         add_dep(rdepends, dep)
928         #bb.note('rdepends is %s' % rdepends)
930         def post_getname(name, suffix):
931                 return '%s%s' % (name, suffix)
932         def pre_getname(name, suffix):
933                 return '%s%s' % (suffix, name)
935         pkgs = {}
936         for pkg in packages.split():
937                 for postfix in postfixes:
938                         if pkg.endswith(postfix):
939                                 if not postfix in pkgs:
940                                         pkgs[postfix] = {}
941                                 pkgs[postfix][pkg] = (pkg[:-len(postfix)], post_getname)
943                 for prefix in prefixes:
944                         if pkg.startswith(prefix):
945                                 if not prefix in pkgs:
946                                         pkgs[prefix] = {}
947                                 pkgs[prefix][pkg] = (pkg[:-len(prefix)], pre_getname)
949         for suffix in pkgs:
950                 for pkg in pkgs[suffix]:
951                         (base, func) = pkgs[suffix][pkg]
952                         if suffix == "-dev" and not pkg.startswith("kernel-module-"):
953                                 pkg_adddeprrecs(pkg, base, suffix, func, depends, d)
954                         if len(pkgs[suffix]) == 1:
955                                 pkg_addrrecs(pkg, base, suffix, func, rdepends, d)
956                         else:
957                                 rdeps = []
958                                 for dep in explode_deps(bb.data.getVar('RDEPENDS_' + base, d, 1) or bb.data.getVar('RDEPENDS', d, 1) or ""):
959                                         add_dep(rdeps, dep)
960                                 pkg_addrrecs(pkg, base, suffix, func, rdeps, d)
964 PACKAGEFUNCS ?= "package_do_split_locales \
965                 populate_packages \
966                 package_do_shlibs \
967                 package_do_pkgconfig \
968                 read_shlibdeps \
969                 package_depchains \
970                 emit_pkgdata"
972 def package_run_hooks(f, d):
973         import bb, os
974         staging = bb.data.getVar('PKGDATA_DIR', d, True)
975         dn = os.path.join(staging, 'hooks', f)
976         if os.access(dn, os.R_OK):
977                 for f in os.listdir(dn):
978                         fn = os.path.join(dn, f)
979                         fp = open(fn, 'r')
980                         line = 0
981                         for l in fp.readlines():
982                                 l = l.rstrip()
983                                 bb.parse.parse_py.BBHandler.feeder(line, l, fn, os.path.basename(fn), d)
984                                 line += 1
985                         fp.close()
986                         anonqueue = bb.data.getVar("__anonqueue", d, 1) or []
987                         body = [x['content'] for x in anonqueue]
988                         flag = { 'python' : 1, 'func' : 1 }
989                         bb.data.setVar("__anonfunc", "\n".join(body), d)
990                         bb.data.setVarFlags("__anonfunc", flag, d)
991                         try:
992                                 t = bb.data.getVar('T', d)
993                                 bb.data.setVar('T', '${TMPDIR}/', d)
994                                 bb.build.exec_func("__anonfunc", d)
995                                 bb.data.delVar('T', d)
996                                 if t:
997                                         bb.data.setVar('T', t, d)
998                         except Exception, e:
999                                 bb.msg.debug(1, bb.msg.domain.Parsing, "Exception when executing anonymous function: %s" % e)
1000                                 raise
1001                         bb.data.delVar("__anonqueue", d)
1002                         bb.data.delVar("__anonfunc", d)
1004 python package_do_package () {
1005         packages = (bb.data.getVar('PACKAGES', d, 1) or "").split()
1006         if len(packages) < 1:
1007                 bb.debug(1, "No packages to build, skipping do_package")
1008                 return
1010         for f in (bb.data.getVar('PACKAGEFUNCS', d, 1) or '').split():
1011                 bb.build.exec_func(f, d)
1012                 package_run_hooks(f, d)
1014 do_package[dirs] = "${D}"
1015 addtask package before do_build after do_install
1017 # Dummy task to mark when all packaging is complete
1018 do_package_write () {
1019         :
1021 addtask package_write before do_build after do_package
1023 EXPORT_FUNCTIONS do_package do_package_write
1026 # Helper functions for the package writing classes
1029 python package_mapping_rename_hook () {
1030         """
1031         Rewrite variables to account for package renaming in things
1032         like debian.bbclass or manual PKG variable name changes
1033         """
1034         runtime_mapping_rename("RDEPENDS", d)
1035         runtime_mapping_rename("RRECOMMENDS", d)
1036         runtime_mapping_rename("RSUGGESTS", d)
1037         runtime_mapping_rename("RPROVIDES", d)
1038         runtime_mapping_rename("RREPLACES", d)
1039         runtime_mapping_rename("RCONFLICTS", d)
1042 EXPORT_FUNCTIONS mapping_rename_hook