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