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