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