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