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