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