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