Update drivers
[vuplus_openembedded] / classes / package.bbclass
1 #
2 # General packaging help functions
3 #
4
5 PKGD    = "${WORKDIR}/package"
6 PKGDEST = "${WORKDIR}/packages-split"
7
8 PKGV    ?= "${PV}"
9 PKGR    ?= "${PR}${DISTRO_PR}"
10
11 EXTENDPKGEVER = "${@['','${PKGE\x7d:'][bb.data.getVar('PKGE',d,1) > 0]}"
12 EXTENDPKGV ?= "${EXTENDPKGEVER}${PKGV}-${PKGR}"
13
14 def legitimize_package_name(s):
15         """
16         Make sure package names are legitimate strings
17         """
18         import re
19
20         def fixutf(m):
21                 cp = m.group(1)
22                 if cp:
23                         return ('\u%s' % cp).decode('unicode_escape').encode('utf-8')
24
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)
27
28         # Remaining package name validity fixes
29         return s.lower().replace('_', '-').replace('@', '+').replace(',', '+').replace('/', '-')
30
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         """
36
37         dvar = bb.data.getVar('PKGD', d, True)
38
39         packages = bb.data.getVar('PACKAGES', d, True).split()
40
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)
54
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
64
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))
118
119         bb.data.setVar('PACKAGES', ' '.join(packages), d)
120
121 PACKAGE_DEPENDS += "file-native"
122
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()
136
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_staging" % dep
142         bb.data.setVarFlag('do_package', 'depends', deps, d)
143
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)
148 }
149
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]
154
155     import commands, stat
156
157     pathprefix = "export PATH=%s; " % bb.data.getVar('PATH', d, True)
158
159     ret, result = commands.getstatusoutput("%sfile '%s'" % (pathprefix, file))
160
161     if ret:
162         bb.error("runstrip: 'file %s' failed (forced strip)" % file)
163
164     if "not stripped" not in result:
165         bb.debug(1, "runstrip: skip %s" % file)
166         return 0
167
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
173
174     strip = bb.data.getVar("STRIP", d, True)
175     objcopy = bb.data.getVar("OBJCOPY", d, True)
176
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)
182
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"
190
191
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))
194
195     stripcmd = "'%s' %s '%s'" % (strip, extraflags, file)
196     bb.debug(1, "runstrip: %s" % stripcmd)
197
198     os.system("%s'%s' --only-keep-debug '%s' '%s'" % (pathprefix, objcopy, file, debugfile))
199     ret = os.system("%s%s" % (pathprefix, stripcmd))
200     os.system("%s'%s' --add-gnu-debuglink='%s' '%s'" % (pathprefix, objcopy, debugfile, file))
201
202     if newmode:
203         os.chmod(file, origmode)
204
205     if ret:
206         bb.error("runstrip: '%s' strip command failed" % stripcmd)
207
208     return 1
209
210 PACKAGESTRIPFUNCS += "do_runstrip"
211 python do_runstrip() {
212         import stat
213
214         dvar = bb.data.getVar('PKGD', d, True)
215         def isexec(path):
216                 try:
217                         s = os.stat(path)
218                 except (os.error, AttributeError):
219                         return 0
220                 return (s[stat.ST_MODE] & stat.S_IEXEC)
221
222         for root, dirs, files in os.walk(dvar):
223                 for f in files:
224                         file = os.path.join(root, f)
225                         if not os.path.islink(file) and not os.path.isdir(file) and isexec(file):
226                                 runstrip(file, d)
227 }
228
229
230 def write_package_md5sums (root, outfile, ignorepaths):
231     # For each regular file under root, writes an md5sum to outfile.
232     # With thanks to patch.bbclass.
233     import bb, os
234
235     try:
236         # Python 2.5+
237         import hashlib
238         ctor = hashlib.md5
239     except ImportError:
240         import md5
241         ctor = md5.new
242
243     outf = file(outfile, 'w')
244
245     # Each output line looks like: "<hex...>  <filename without leading slash>"
246     striplen = len(root)
247     if not root.endswith('/'):
248         striplen += 1
249
250     for walkroot, dirs, files in os.walk(root):
251         # Skip e.g. the DEBIAN directory
252         if walkroot[striplen:] in ignorepaths:
253             dirs[:] = []
254             continue
255
256         for name in files:
257             fullpath = os.path.join(walkroot, name)
258             if os.path.islink(fullpath) or (not os.path.isfile(fullpath)):
259                 continue
260
261             m = ctor()
262             f = file(fullpath, 'rb')
263             while True:
264                 d = f.read(8192)
265                 if not d:
266                     break
267                 m.update(d)
268             f.close()
269
270             print >> outf, "%s  %s" % (m.hexdigest(), fullpath[striplen:])
271
272     outf.close()
273
274
275 #
276 # Package data handling routines
277 #
278
279 def get_package_mapping (pkg, d):
280         data = read_subpkgdata(pkg, d)
281         key = "PKG_%s" % pkg
282
283         if key in data:
284                 return data[key]
285
286         return pkg
287
288 def runtime_mapping_rename (varname, d):
289         #bb.note("%s before: %s" % (varname, bb.data.getVar(varname, d, True))) 
290
291         new_depends = []
292         for depend in explode_deps(bb.data.getVar(varname, d, True) or ""):
293                 # Have to be careful with any version component of the depend
294                 split_depend = depend.split(' (')
295                 new_depend = get_package_mapping(split_depend[0].strip(), d)
296                 if len(split_depend) > 1:
297                         new_depends.append("%s (%s" % (new_depend, split_depend[1]))
298                 else:
299                         new_depends.append(new_depend)
300
301         bb.data.setVar(varname, " ".join(new_depends) or None, d)
302
303         #bb.note("%s after: %s" % (varname, bb.data.getVar(varname, d, True)))
304
305 #
306 # Package functions suitable for inclusion in PACKAGEFUNCS
307 #
308
309 python package_do_split_locales() {
310         if (bb.data.getVar('PACKAGE_NO_LOCALE', d, True) == '1'):
311                 bb.debug(1, "package requested not splitting locales")
312                 return
313
314         packages = (bb.data.getVar('PACKAGES', d, True) or "").split()
315
316         datadir = bb.data.getVar('datadir', d, True)
317         if not datadir:
318                 bb.note("datadir not defined")
319                 return
320
321         dvar = bb.data.getVar('PKGD', d, True)
322         pn = bb.data.getVar('PN', d, True)
323
324         if pn + '-locale' in packages:
325                 packages.remove(pn + '-locale')
326
327         localedir = os.path.join(dvar + datadir, 'locale')
328
329         if not os.path.isdir(localedir):
330                 bb.debug(1, "No locale files in this package")
331                 return
332
333         locales = os.listdir(localedir)
334
335         # This is *really* broken
336         mainpkg = packages[0]
337         # At least try and patch it up I guess...
338         if mainpkg.find('-dbg'):
339                 mainpkg = mainpkg.replace('-dbg', '')
340         if mainpkg.find('-dev'):
341                 mainpkg = mainpkg.replace('-dev', '')
342
343         for l in locales:
344                 ln = legitimize_package_name(l)
345                 pkg = pn + '-locale-' + ln
346                 packages.append(pkg)
347                 bb.data.setVar('FILES_' + pkg, os.path.join(datadir, 'locale', l), d)
348                 bb.data.setVar('RDEPENDS_' + pkg, '%s virtual-locale-%s' % (mainpkg, ln), d)
349                 bb.data.setVar('RPROVIDES_' + pkg, '%s-locale %s-translation' % (pn, ln), d)
350                 bb.data.setVar('DESCRIPTION_' + pkg, '%s translation for %s' % (l, pn), d)
351
352         bb.data.setVar('PACKAGES', ' '.join(packages), d)
353 }
354
355 python perform_packagecopy () {
356         dest = bb.data.getVar('D', d, True)
357         dvar = bb.data.getVar('PKGD', d, True)
358
359         bb.mkdirhier(dvar)
360
361         # Start by package population by taking a copy of the installed 
362         # files to operate on
363         os.system('rm -rf %s/*' % (dvar))
364         os.system('cp -pPR %s/* %s/' % (dest, dvar))
365 }
366
367 python populate_packages () {
368         import glob, errno, re,os
369
370         workdir = bb.data.getVar('WORKDIR', d, True)
371         outdir = bb.data.getVar('DEPLOY_DIR', d, True)
372         dvar = bb.data.getVar('PKGD', d, True)
373         packages = bb.data.getVar('PACKAGES', d, True)
374         pn = bb.data.getVar('PN', d, True)
375
376         bb.mkdirhier(outdir)
377         os.chdir(dvar)
378
379         # Sanity check PACKAGES for duplicates - should be moved to 
380         # sanity.bbclass once we have the infrastucture
381         package_list = []
382         for pkg in packages.split():
383                 if pkg in package_list:
384                         bb.error("-------------------")
385                         bb.error("%s is listed in PACKAGES multiple times, this leads to packaging errors." % pkg)
386                         bb.error("Please fix the metadata/report this as bug to OE bugtracker.")
387                         bb.error("-------------------")
388                 else:
389                         package_list.append(pkg)
390
391
392         if (bb.data.getVar('INHIBIT_PACKAGE_STRIP', d, True) != '1'):
393                 for f in (bb.data.getVar('PACKAGESTRIPFUNCS', d, True) or '').split():
394                         bb.build.exec_func(f, d)
395
396         pkgdest = bb.data.getVar('PKGDEST', d, True)
397         os.system('rm -rf %s' % pkgdest)
398
399         seen = []
400         main_is_empty = 1
401         main_pkg = bb.data.getVar('PN', d, True)
402
403         for pkg in package_list:
404                 localdata = bb.data.createCopy(d)
405                 root = os.path.join(pkgdest, pkg)
406                 bb.mkdirhier(root)
407
408                 bb.data.setVar('PKG', pkg, localdata)
409                 overrides = bb.data.getVar('OVERRIDES', localdata, True)
410                 if not overrides:
411                         raise bb.build.FuncFailed('OVERRIDES not defined')
412                 bb.data.setVar('OVERRIDES', overrides + ':' + pkg, localdata)
413                 bb.data.update_data(localdata)
414
415                 filesvar = bb.data.getVar('FILES', localdata, True) or ""
416                 files = filesvar.split()
417                 for file in files:
418                         if os.path.isabs(file):
419                                 file = '.' + file
420                         if not os.path.islink(file):
421                                 if os.path.isdir(file):
422                                         newfiles =  [ os.path.join(file,x) for x in os.listdir(file) ]
423                                         if newfiles:
424                                                 files += newfiles
425                                                 continue
426                         globbed = glob.glob(file)
427                         if globbed:
428                                 if [ file ] != globbed:
429                                         if not file in globbed:
430                                                 files += globbed
431                                                 continue
432                                         else:
433                                                 globbed.remove(file)
434                                                 files += globbed
435                         if (not os.path.islink(file)) and (not os.path.exists(file)):
436                                 continue
437                         if file[-4:] == '.pyc':
438                                 continue
439                         if file in seen:
440                                 continue
441                         seen.append(file)
442                         if os.path.isdir(file) and not os.path.islink(file):
443                                 bb.mkdirhier(os.path.join(root,file))
444                                 os.chmod(os.path.join(root,file), os.stat(file).st_mode)
445                                 continue
446                         fpath = os.path.join(root,file)
447                         dpath = os.path.dirname(fpath)
448                         bb.mkdirhier(dpath)
449                         ret = bb.copyfile(file, fpath)
450                         if ret is False:
451                                 raise bb.build.FuncFailed("File population failed when copying %s to %s" % (file, fpath))
452                         if pkg == main_pkg and main_is_empty:
453                                 main_is_empty = 0
454                 del localdata
455         os.chdir(workdir)
456
457         unshipped = []
458         for root, dirs, files in os.walk(dvar):
459                 for f in files:
460                         path = os.path.join(root[len(dvar):], f)
461                         if ('.' + path) not in seen:
462                                 unshipped.append(path)
463
464         if unshipped != []:
465                 bb.note("the following files were installed but not shipped in any package:")
466                 for f in unshipped:
467                         bb.note("  " + f)
468
469         bb.build.exec_func("package_name_hook", d)
470
471         for pkg in package_list:
472                 pkgname = bb.data.getVar('PKG_%s' % pkg, d, True)
473                 if pkgname is None:
474                         bb.data.setVar('PKG_%s' % pkg, pkg, d)
475
476         dangling_links = {}
477         pkg_files = {}
478         for pkg in package_list:
479                 dangling_links[pkg] = []
480                 pkg_files[pkg] = []
481                 inst_root = os.path.join(pkgdest, pkg)
482                 for root, dirs, files in os.walk(inst_root):
483                         for f in files:
484                                 path = os.path.join(root, f)
485                                 rpath = path[len(inst_root):]
486                                 pkg_files[pkg].append(rpath)
487                                 try:
488                                         s = os.stat(path)
489                                 except OSError, (err, strerror):
490                                         if err != errno.ENOENT:
491                                                 raise
492                                         target = os.readlink(path)
493                                         if target[0] != '/':
494                                                 target = os.path.join(root[len(inst_root):], target)
495                                         dangling_links[pkg].append(os.path.normpath(target))
496
497         for pkg in package_list:
498                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
499
500                 remstr = "${PN} (= ${EXTENDPKGV})"
501                 if main_is_empty and remstr in rdepends:
502                         rdepends.remove(remstr)
503                 for l in dangling_links[pkg]:
504                         found = False
505                         bb.debug(1, "%s contains dangling link %s" % (pkg, l))
506                         for p in package_list:
507                                 for f in pkg_files[p]:
508                                         if f == l:
509                                                 found = True
510                                                 bb.debug(1, "target found in %s" % p)
511                                                 if p == pkg:
512                                                         break
513                                                 if not p in rdepends:
514                                                         rdepends.append(p)
515                                                 break
516                         if found == False:
517                                 bb.note("%s contains dangling symlink to %s" % (pkg, l))
518                 bb.data.setVar('RDEPENDS_' + pkg, " " + " ".join(rdepends), d)
519 }
520 populate_packages[dirs] = "${D}"
521
522 python emit_pkgdata() {
523         from glob import glob
524
525         def write_if_exists(f, pkg, var):
526                 def encode(str):
527                         import codecs
528                         c = codecs.getencoder("string_escape")
529                         return c(str)[0]
530
531                 val = bb.data.getVar('%s_%s' % (var, pkg), d, True)
532                 if val:
533                         f.write('%s_%s: %s\n' % (var, pkg, encode(val)))
534                         return
535                 val = bb.data.getVar('%s' % (var), d, True)
536                 if val:
537                         f.write('%s: %s\n' % (var, encode(val)))
538                 return
539
540         packages = bb.data.getVar('PACKAGES', d, True)
541         pkgdest = bb.data.getVar('PKGDEST', d, 1)
542         pkgdatadir = bb.data.getVar('PKGDATA_DIR', d, True)
543
544         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
545         if pstageactive == "1":
546                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
547
548         data_file = pkgdatadir + bb.data.expand("/${PN}" , d)
549         f = open(data_file, 'w')
550         f.write("PACKAGES: %s\n" % packages)
551         f.close()
552         package_stagefile(data_file, d)
553
554         workdir = bb.data.getVar('WORKDIR', d, True)
555
556         for pkg in packages.split():
557                 subdata_file = pkgdatadir + "/runtime/%s" % pkg
558                 sf = open(subdata_file, 'w')
559                 write_if_exists(sf, pkg, 'PN')
560                 write_if_exists(sf, pkg, 'PV')
561                 write_if_exists(sf, pkg, 'PR')
562                 write_if_exists(sf, pkg, 'PKGV')
563                 write_if_exists(sf, pkg, 'PKGR')
564                 write_if_exists(sf, pkg, 'DESCRIPTION')
565                 write_if_exists(sf, pkg, 'RDEPENDS')
566                 write_if_exists(sf, pkg, 'RPROVIDES')
567                 write_if_exists(sf, pkg, 'RRECOMMENDS')
568                 write_if_exists(sf, pkg, 'RSUGGESTS')
569                 write_if_exists(sf, pkg, 'RREPLACES')
570                 write_if_exists(sf, pkg, 'RCONFLICTS')
571                 write_if_exists(sf, pkg, 'PKG')
572                 write_if_exists(sf, pkg, 'ALLOW_EMPTY')
573                 write_if_exists(sf, pkg, 'FILES')
574                 write_if_exists(sf, pkg, 'pkg_postinst')
575                 write_if_exists(sf, pkg, 'pkg_postrm')
576                 write_if_exists(sf, pkg, 'pkg_preinst')
577                 write_if_exists(sf, pkg, 'pkg_prerm')
578                 sf.close()
579
580                 package_stagefile(subdata_file, d)
581                 #if pkgdatadir2:
582                 #       bb.copyfile(subdata_file, pkgdatadir2 + "/runtime/%s" % pkg)
583
584                 allow_empty = bb.data.getVar('ALLOW_EMPTY_%s' % pkg, d, True)
585                 if not allow_empty:
586                         allow_empty = bb.data.getVar('ALLOW_EMPTY', d, True)
587                 root = "%s/%s" % (pkgdest, pkg)
588                 os.chdir(root)
589                 g = glob('*') + glob('.[!.]*')
590                 if g or allow_empty == "1":
591                         packagedfile = pkgdatadir + '/runtime/%s.packaged' % pkg
592                         file(packagedfile, 'w').close()
593                         package_stagefile(packagedfile, d)
594         if pstageactive == "1":
595                 bb.utils.unlockfile(lf)
596 }
597 emit_pkgdata[dirs] = "${PKGDATA_DIR}/runtime"
598
599 ldconfig_postinst_fragment() {
600 if [ x"$D" = "x" ]; then
601         if [ -e /etc/ld.so.conf ] ; then
602                 [ -x /sbin/ldconfig ] && /sbin/ldconfig
603         fi
604 fi
605 }
606
607 SHLIBSDIR = "${STAGING_DIR_HOST}/shlibs"
608
609 python package_do_shlibs() {
610         import re
611
612         exclude_shlibs = bb.data.getVar('EXCLUDE_FROM_SHLIBS', d, 0)
613         if exclude_shlibs:
614                 bb.debug(1, "not generating shlibs")
615                 return
616                 
617         lib_re = re.compile("^lib.*\.so")
618         libdir_re = re.compile(".*/lib$")
619
620         packages = bb.data.getVar('PACKAGES', d, True)
621
622         workdir = bb.data.getVar('WORKDIR', d, True)
623
624         ver = bb.data.getVar('PKGV', d, True)
625         if not ver:
626                 bb.error("PKGV not defined")
627                 return
628
629         pkgdest = bb.data.getVar('PKGDEST', d, True)
630
631         shlibs_dir = bb.data.getVar('SHLIBSDIR', d, True)
632         bb.mkdirhier(shlibs_dir)
633
634         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
635         if pstageactive == "1":
636                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
637
638         if bb.data.getVar('PACKAGE_SNAP_LIB_SYMLINKS', d, True) == "1":
639                 snap_symlinks = True
640         else:
641                 snap_symlinks = False
642
643         if (bb.data.getVar('USE_LDCONFIG', d, True) or "1") == "1":
644                 use_ldconfig = True
645         else:
646                 use_ldconfig = False
647
648         needed = {}
649         private_libs = bb.data.getVar('PRIVATE_LIBS', d, True)
650         for pkg in packages.split():
651                 needs_ldconfig = False
652                 bb.debug(2, "calculating shlib provides for %s" % pkg)
653
654                 pkgver = bb.data.getVar('PKGV_' + pkg, d, True)
655                 if not pkgver:
656                         pkgver = bb.data.getVar('PV_' + pkg, d, True)
657                 if not pkgver:
658                         pkgver = ver
659
660                 needed[pkg] = []
661                 sonames = list()
662                 top = os.path.join(pkgdest, pkg)
663                 renames = []
664                 for root, dirs, files in os.walk(top):
665                         for file in files:
666                                 soname = None
667                                 path = os.path.join(root, file)
668                                 if (os.access(path, os.X_OK) or lib_re.match(file)) and not os.path.islink(path):
669                                         cmd = bb.data.getVar('OBJDUMP', d, True) + " -p " + path + " 2>/dev/null"
670                                         cmd = "PATH=\"%s\" %s" % (bb.data.getVar('PATH', d, True), cmd)
671                                         fd = os.popen(cmd)
672                                         lines = fd.readlines()
673                                         fd.close()
674                                         for l in lines:
675                                                 m = re.match("\s+NEEDED\s+([^\s]*)", l)
676                                                 if m:
677                                                         needed[pkg].append(m.group(1))
678                                                 m = re.match("\s+SONAME\s+([^\s]*)", l)
679                                                 if m:
680                                                         this_soname = m.group(1)
681                                                         if not this_soname in sonames:
682                                                                 # if library is private (only used by package) then do not build shlib for it
683                                                                 if not private_libs or -1 == private_libs.find(this_soname):
684                                                                         sonames.append(this_soname)
685                                                         if libdir_re.match(root):
686                                                                 needs_ldconfig = True
687                                                         if snap_symlinks and (file != soname):
688                                                                 renames.append((path, os.path.join(root, this_soname)))
689                 for (old, new) in renames:
690                         os.rename(old, new)
691                 shlibs_file = os.path.join(shlibs_dir, pkg + ".list")
692                 if os.path.exists(shlibs_file):
693                         os.remove(shlibs_file)
694                 shver_file = os.path.join(shlibs_dir, pkg + ".ver")
695                 if os.path.exists(shver_file):
696                         os.remove(shver_file)
697                 if len(sonames):
698                         fd = open(shlibs_file, 'w')
699                         for s in sonames:
700                                 fd.write(s + '\n')
701                         fd.close()
702                         package_stagefile(shlibs_file, d)
703                         fd = open(shver_file, 'w')
704                         fd.write(pkgver + '\n')
705                         fd.close()
706                         package_stagefile(shver_file, d)
707                 if needs_ldconfig and use_ldconfig:
708                         bb.debug(1, 'adding ldconfig call to postinst for %s' % pkg)
709                         postinst = bb.data.getVar('pkg_postinst_%s' % pkg, d, True) or bb.data.getVar('pkg_postinst', d, True)
710                         if not postinst:
711                                 postinst = '#!/bin/sh\n'
712                         postinst += bb.data.getVar('ldconfig_postinst_fragment', d, True)
713                         bb.data.setVar('pkg_postinst_%s' % pkg, postinst, d)
714
715         if pstageactive == "1":
716                 bb.utils.unlockfile(lf)
717
718         shlib_provider = {}
719         list_re = re.compile('^(.*)\.list$')
720         for dir in [shlibs_dir]: 
721                 if not os.path.exists(dir):
722                         continue
723                 for file in os.listdir(dir):
724                         m = list_re.match(file)
725                         if m:
726                                 dep_pkg = m.group(1)
727                                 fd = open(os.path.join(dir, file))
728                                 lines = fd.readlines()
729                                 fd.close()
730                                 ver_file = os.path.join(dir, dep_pkg + '.ver')
731                                 lib_ver = None
732                                 if os.path.exists(ver_file):
733                                         fd = open(ver_file)
734                                         lib_ver = fd.readline().rstrip()
735                                         fd.close()
736                                 for l in lines:
737                                         shlib_provider[l.rstrip()] = (dep_pkg, lib_ver)
738
739         assumed_libs = bb.data.getVar('ASSUME_SHLIBS', d, True)
740         if assumed_libs:
741             for e in assumed_libs.split():
742                 l, dep_pkg = e.split(":")
743                 lib_ver = None
744                 dep_pkg = dep_pkg.rsplit("_", 1)
745                 if len(dep_pkg) == 2:
746                     lib_ver = dep_pkg[1]
747                 dep_pkg = dep_pkg[0]
748                 shlib_provider[l] = (dep_pkg, lib_ver)
749
750         dep_packages = []
751         for pkg in packages.split():
752                 bb.debug(2, "calculating shlib requirements for %s" % pkg)
753
754                 deps = list()
755                 for n in needed[pkg]:
756                         if n in shlib_provider.keys():
757                                 (dep_pkg, ver_needed) = shlib_provider[n]
758
759                                 if dep_pkg == pkg:
760                                         continue
761
762                                 if ver_needed:
763                                         dep = "%s (>= %s)" % (dep_pkg, ver_needed)
764                                 else:
765                                         dep = dep_pkg
766                                 if not dep in deps:
767                                         deps.append(dep)
768                                 if not dep_pkg in dep_packages:
769                                         dep_packages.append(dep_pkg)
770                                         
771                         else:
772                                 bb.note("Couldn't find shared library provider for %s" % n)
773
774                 deps_file = os.path.join(pkgdest, pkg + ".shlibdeps")
775                 if os.path.exists(deps_file):
776                         os.remove(deps_file)
777                 if len(deps):
778                         fd = open(deps_file, 'w')
779                         for dep in deps:
780                                 fd.write(dep + '\n')
781                         fd.close()
782 }
783
784 python package_do_pkgconfig () {
785         import re
786
787         packages = bb.data.getVar('PACKAGES', d, True)
788         workdir = bb.data.getVar('WORKDIR', d, True)
789         pkgdest = bb.data.getVar('PKGDEST', d, True)
790
791         shlibs_dir = bb.data.getVar('SHLIBSDIR', d, True)
792         bb.mkdirhier(shlibs_dir)
793
794         pc_re = re.compile('(.*)\.pc$')
795         var_re = re.compile('(.*)=(.*)')
796         field_re = re.compile('(.*): (.*)')
797
798         pkgconfig_provided = {}
799         pkgconfig_needed = {}
800         for pkg in packages.split():
801                 pkgconfig_provided[pkg] = []
802                 pkgconfig_needed[pkg] = []
803                 top = os.path.join(pkgdest, pkg)
804                 for root, dirs, files in os.walk(top):
805                         for file in files:
806                                 m = pc_re.match(file)
807                                 if m:
808                                         pd = bb.data.init()
809                                         name = m.group(1)
810                                         pkgconfig_provided[pkg].append(name)
811                                         path = os.path.join(root, file)
812                                         if not os.access(path, os.R_OK):
813                                                 continue
814                                         f = open(path, 'r')
815                                         lines = f.readlines()
816                                         f.close()
817                                         for l in lines:
818                                                 m = var_re.match(l)
819                                                 if m:
820                                                         name = m.group(1)
821                                                         val = m.group(2)
822                                                         bb.data.setVar(name, bb.data.expand(val, pd), pd)
823                                                         continue
824                                                 m = field_re.match(l)
825                                                 if m:
826                                                         hdr = m.group(1)
827                                                         exp = bb.data.expand(m.group(2), pd)
828                                                         if hdr == 'Requires':
829                                                                 pkgconfig_needed[pkg] += exp.replace(',', ' ').split()
830
831         pstageactive = bb.data.getVar('PSTAGING_ACTIVE', d, True)
832         if pstageactive == "1":
833                 lf = bb.utils.lockfile(bb.data.expand("${STAGING_DIR}/staging.lock", d))
834
835         for pkg in packages.split():
836                 pkgs_file = os.path.join(shlibs_dir, pkg + ".pclist")
837                 if os.path.exists(pkgs_file):
838                         os.remove(pkgs_file)
839                 if pkgconfig_provided[pkg] != []:
840                         f = open(pkgs_file, 'w')
841                         for p in pkgconfig_provided[pkg]:
842                                 f.write('%s\n' % p)
843                         f.close()
844                         package_stagefile(pkgs_file, d)
845
846         for dir in [shlibs_dir]:
847                 if not os.path.exists(dir):
848                         continue
849                 for file in os.listdir(dir):
850                         m = re.match('^(.*)\.pclist$', file)
851                         if m:
852                                 pkg = m.group(1)
853                                 fd = open(os.path.join(dir, file))
854                                 lines = fd.readlines()
855                                 fd.close()
856                                 pkgconfig_provided[pkg] = []
857                                 for l in lines:
858                                         pkgconfig_provided[pkg].append(l.rstrip())
859
860         for pkg in packages.split():
861                 deps = []
862                 for n in pkgconfig_needed[pkg]:
863                         found = False
864                         for k in pkgconfig_provided.keys():
865                                 if n in pkgconfig_provided[k]:
866                                         if k != pkg and not (k in deps):
867                                                 deps.append(k)
868                                         found = True
869                         if found == False:
870                                 bb.note("couldn't find pkgconfig module '%s' in any package" % n)
871                 deps_file = os.path.join(pkgdest, pkg + ".pcdeps")
872                 if os.path.exists(deps_file):
873                         os.remove(deps_file)
874                 if len(deps):
875                         fd = open(deps_file, 'w')
876                         for dep in deps:
877                                 fd.write(dep + '\n')
878                         fd.close()
879                         package_stagefile(deps_file, d)
880
881         if pstageactive == "1":
882                 bb.utils.unlockfile(lf)
883 }
884
885 python read_shlibdeps () {
886         packages = bb.data.getVar('PACKAGES', d, True).split()
887         for pkg in packages:
888                 rdepends = explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, 0) or bb.data.getVar('RDEPENDS', d, 0) or "")
889                 for extension in ".shlibdeps", ".pcdeps", ".clilibdeps":
890                         depsfile = bb.data.expand("${PKGDEST}/" + pkg + extension, d)
891                         if os.access(depsfile, os.R_OK):
892                                 fd = file(depsfile)
893                                 lines = fd.readlines()
894                                 fd.close()
895                                 for l in lines:
896                                         rdepends.append(l.rstrip())
897                 bb.data.setVar('RDEPENDS_' + pkg, " " + " ".join(rdepends), d)
898 }
899
900 python package_depchains() {
901         """
902         For a given set of prefix and postfix modifiers, make those packages
903         RRECOMMENDS on the corresponding packages for its RDEPENDS.
904
905         Example:  If package A depends upon package B, and A's .bb emits an
906         A-dev package, this would make A-dev Recommends: B-dev.
907
908         If only one of a given suffix is specified, it will take the RRECOMMENDS
909         based on the RDEPENDS of *all* other packages. If more than one of a given 
910         suffix is specified, its will only use the RDEPENDS of the single parent 
911         package.
912         """
913
914         packages  = bb.data.getVar('PACKAGES', d, True)
915         postfixes = (bb.data.getVar('DEPCHAIN_POST', d, True) or '').split()
916         prefixes  = (bb.data.getVar('DEPCHAIN_PRE', d, True) or '').split()
917
918         def pkg_adddeprrecs(pkg, base, suffix, getname, depends, d):
919
920                 #bb.note('depends for %s is %s' % (base, depends))
921                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, True) or bb.data.getVar('RRECOMMENDS', d, True) or "")
922
923                 for depend in depends:
924                         if depend.find('-native') != -1 or depend.find('-cross') != -1 or depend.startswith('virtual/'):
925                                 #bb.note("Skipping %s" % depend)
926                                 continue
927                         if depend.endswith('-dev'):
928                                 depend = depend.replace('-dev', '')
929                         if depend.endswith('-dbg'):
930                                 depend = depend.replace('-dbg', '')
931                         pkgname = getname(depend, suffix)
932                         #bb.note("Adding %s for %s" % (pkgname, depend))
933                         if not pkgname in rreclist:
934                                 rreclist.append(pkgname)
935
936                 #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
937                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
938
939         def pkg_addrrecs(pkg, base, suffix, getname, rdepends, d):
940
941                 #bb.note('rdepends for %s is %s' % (base, rdepends))
942                 rreclist = explode_deps(bb.data.getVar('RRECOMMENDS_' + pkg, d, True) or bb.data.getVar('RRECOMMENDS', d, True) or "")
943
944                 for depend in rdepends:
945                         if depend.endswith('-dev'):
946                                 depend = depend.replace('-dev', '')
947                         if depend.endswith('-dbg'):
948                                 depend = depend.replace('-dbg', '')
949                         pkgname = getname(depend, suffix)
950                         if not pkgname in rreclist:
951                                 rreclist.append(pkgname)
952
953                 #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
954                 bb.data.setVar('RRECOMMENDS_%s' % pkg, ' '.join(rreclist), d)
955
956         def add_dep(list, dep):
957                 dep = dep.split(' (')[0].strip()
958                 if dep not in list:
959                         list.append(dep)
960
961         depends = []
962         for dep in explode_deps(bb.data.getVar('DEPENDS', d, True) or ""):
963                 add_dep(depends, dep)
964
965         rdepends = []
966         for dep in explode_deps(bb.data.getVar('RDEPENDS', d, True) or ""):
967                 add_dep(rdepends, dep)
968
969         for pkg in packages.split():
970                 for dep in explode_deps(bb.data.getVar('RDEPENDS_' + pkg, d, True) or ""):
971                         add_dep(rdepends, dep)
972
973         #bb.note('rdepends is %s' % rdepends)
974
975         def post_getname(name, suffix):
976                 return '%s%s' % (name, suffix)
977         def pre_getname(name, suffix):
978                 return '%s%s' % (suffix, name)
979
980         pkgs = {}
981         for pkg in packages.split():
982                 for postfix in postfixes:
983                         if pkg.endswith(postfix):
984                                 if not postfix in pkgs:
985                                         pkgs[postfix] = {}
986                                 pkgs[postfix][pkg] = (pkg[:-len(postfix)], post_getname)
987
988                 for prefix in prefixes:
989                         if pkg.startswith(prefix):
990                                 if not prefix in pkgs:
991                                         pkgs[prefix] = {}
992                                 pkgs[prefix][pkg] = (pkg[:-len(prefix)], pre_getname)
993
994         for suffix in pkgs:
995                 for pkg in pkgs[suffix]:
996                         (base, func) = pkgs[suffix][pkg]
997                         if suffix == "-dev" and not pkg.startswith("kernel-module-"):
998                                 pkg_adddeprrecs(pkg, base, suffix, func, depends, d)
999                         if len(pkgs[suffix]) == 1:
1000                                 pkg_addrrecs(pkg, base, suffix, func, rdepends, d)
1001                         else:
1002                                 rdeps = []
1003                                 for dep in explode_deps(bb.data.getVar('RDEPENDS_' + base, d, True) or bb.data.getVar('RDEPENDS', d, True) or ""):
1004                                         add_dep(rdeps, dep)
1005                                 pkg_addrrecs(pkg, base, suffix, func, rdeps, d)
1006 }
1007
1008 PACKAGE_PREPROCESS_FUNCS ?= ""
1009 PACKAGEFUNCS ?= "perform_packagecopy \
1010                 ${PACKAGE_PREPROCESS_FUNCS} \
1011                 package_do_split_locales \
1012                 populate_packages \
1013                 package_do_shlibs \
1014                 package_do_pkgconfig \
1015                 read_shlibdeps \
1016                 package_depchains \
1017                 emit_pkgdata"
1018
1019 def package_run_hooks(f, d):
1020         import bb, os
1021         staging = bb.data.getVar('PKGDATA_DIR', d, True)
1022         dn = os.path.join(staging, 'hooks', f)
1023         if os.access(dn, os.R_OK):
1024                 for f in os.listdir(dn):
1025                         fn = os.path.join(dn, f)
1026                         fp = open(fn, 'r')
1027                         line = 0
1028                         for l in fp.readlines():
1029                                 l = l.rstrip()
1030                                 bb.parse.parse_py.BBHandler.feeder(line, l, fn, os.path.basename(fn), d)
1031                                 line += 1
1032                         fp.close()
1033                         anonqueue = bb.data.getVar("__anonqueue", d, True) or []
1034                         body = [x['content'] for x in anonqueue]
1035                         flag = { 'python' : 1, 'func' : 1 }
1036                         bb.data.setVar("__anonfunc", "\n".join(body), d)
1037                         bb.data.setVarFlags("__anonfunc", flag, d)
1038                         try:
1039                                 t = bb.data.getVar('T', d)
1040                                 bb.data.setVar('T', '${TMPDIR}/', d)
1041                                 bb.build.exec_func("__anonfunc", d)
1042                                 bb.data.delVar('T', d)
1043                                 if t:
1044                                         bb.data.setVar('T', t, d)
1045                         except Exception, e:
1046                                 bb.msg.debug(1, bb.msg.domain.Parsing, "Exception when executing anonymous function: %s" % e)
1047                                 raise
1048                         bb.data.delVar("__anonqueue", d)
1049                         bb.data.delVar("__anonfunc", d)
1050
1051 python package_do_package () {
1052         packages = (bb.data.getVar('PACKAGES', d, True) or "").split()
1053         if len(packages) < 1:
1054                 bb.debug(1, "No packages to build, skipping do_package")
1055                 return
1056
1057         workdir = bb.data.getVar('WORKDIR', d, True)
1058         outdir = bb.data.getVar('DEPLOY_DIR', d, True)
1059         dest = bb.data.getVar('D', d, True)
1060         dvar = bb.data.getVar('PKGD', d, True)
1061         pn = bb.data.getVar('PN', d, True)
1062
1063         if not workdir or not outdir or not dest or not dvar or not pn or not packages:
1064                 bb.error("WORKDIR, DEPLOY_DIR, D, PN and PKGD all must be defined, unable to package")
1065                 return
1066
1067         for f in (bb.data.getVar('PACKAGEFUNCS', d, True) or '').split():
1068                 bb.build.exec_func(f, d)
1069                 package_run_hooks(f, d)
1070 }
1071 do_package[dirs] = "${D}"
1072 addtask package before do_build after do_install
1073
1074 # Dummy task to mark when all packaging is complete
1075 do_package_write () {
1076         :
1077 }
1078 addtask package_write before do_build after do_package
1079
1080 EXPORT_FUNCTIONS do_package do_package_write
1081
1082 #
1083 # Helper functions for the package writing classes
1084 #
1085
1086 python package_mapping_rename_hook () {
1087         """
1088         Rewrite variables to account for package renaming in things
1089         like debian.bbclass or manual PKG variable name changes
1090         """
1091         runtime_mapping_rename("RDEPENDS", d)
1092         runtime_mapping_rename("RRECOMMENDS", d)
1093         runtime_mapping_rename("RSUGGESTS", d)
1094         runtime_mapping_rename("RPROVIDES", d)
1095         runtime_mapping_rename("RREPLACES", d)
1096         runtime_mapping_rename("RCONFLICTS", d)
1097 }
1098
1099 EXPORT_FUNCTIONS mapping_rename_hook