package.bbclass 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482
  1. #
  2. # Packaging process
  3. #
  4. # Executive summary: This class iterates over the functions listed in PACKAGEFUNCS
  5. # Taking D and splitting it up into the packages listed in PACKAGES, placing the
  6. # resulting output in PKGDEST.
  7. #
  8. # There are the following default steps but PACKAGEFUNCS can be extended:
  9. #
  10. # a) package_convert_pr_autoinc - convert AUTOINC in PKGV to ${PRSERV_PV_AUTOINC}
  11. #
  12. # b) perform_packagecopy - Copy D into PKGD
  13. #
  14. # c) package_do_split_locales - Split out the locale files, updates FILES and PACKAGES
  15. #
  16. # d) split_and_strip_files - split the files into runtime and debug and strip them.
  17. # Debug files include debug info split, and associated sources that end up in -dbg packages
  18. #
  19. # e) fixup_perms - Fix up permissions in the package before we split it.
  20. #
  21. # f) populate_packages - Split the files in PKGD into separate packages in PKGDEST/<pkgname>
  22. # Also triggers the binary stripping code to put files in -dbg packages.
  23. #
  24. # g) package_do_filedeps - Collect perfile run-time dependency metadata
  25. # The data is stores in FILER{PROVIDES,DEPENDS}_file_pkg variables with
  26. # a list of affected files in FILER{PROVIDES,DEPENDS}FLIST_pkg
  27. #
  28. # h) package_do_shlibs - Look at the shared libraries generated and autotmatically add any
  29. # dependencies found. Also stores the package name so anyone else using this library
  30. # knows which package to depend on.
  31. #
  32. # i) package_do_pkgconfig - Keep track of which packages need and provide which .pc files
  33. #
  34. # j) read_shlibdeps - Reads the stored shlibs information into the metadata
  35. #
  36. # k) package_depchains - Adds automatic dependencies to -dbg and -dev packages
  37. #
  38. # l) emit_pkgdata - saves the packaging data into PKGDATA_DIR for use in later
  39. # packaging steps
  40. inherit packagedata
  41. inherit chrpath
  42. inherit package_pkgdata
  43. # Need the package_qa_handle_error() in insane.bbclass
  44. inherit insane
  45. PKGD = "${WORKDIR}/package"
  46. PKGDEST = "${WORKDIR}/packages-split"
  47. LOCALE_SECTION ?= ''
  48. ALL_MULTILIB_PACKAGE_ARCHS = "${@all_multilib_tune_values(d, 'PACKAGE_ARCHS')}"
  49. # rpm is used for the per-file dependency identification
  50. # dwarfsrcfiles is used to determine the list of debug source files
  51. PACKAGE_DEPENDS += "rpm-native dwarfsrcfiles-native"
  52. # If your postinstall can execute at rootfs creation time rather than on
  53. # target but depends on a native/cross tool in order to execute, you need to
  54. # list that tool in PACKAGE_WRITE_DEPS. Target package dependencies belong
  55. # in the package dependencies as normal, this is just for native/cross support
  56. # tools at rootfs build time.
  57. PACKAGE_WRITE_DEPS ??= ""
  58. def legitimize_package_name(s):
  59. """
  60. Make sure package names are legitimate strings
  61. """
  62. import re
  63. def fixutf(m):
  64. cp = m.group(1)
  65. if cp:
  66. return ('\\u%s' % cp).encode('latin-1').decode('unicode_escape')
  67. # Handle unicode codepoints encoded as <U0123>, as in glibc locale files.
  68. s = re.sub(r'<U([0-9A-Fa-f]{1,4})>', fixutf, s)
  69. # Remaining package name validity fixes
  70. return s.lower().replace('_', '-').replace('@', '+').replace(',', '+').replace('/', '-')
  71. 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, summary=None):
  72. """
  73. Used in .bb files to split up dynamically generated subpackages of a
  74. given package, usually plugins or modules.
  75. Arguments:
  76. root -- the path in which to search
  77. file_regex -- regular expression to match searched files. Use
  78. parentheses () to mark the part of this expression
  79. that should be used to derive the module name (to be
  80. substituted where %s is used in other function
  81. arguments as noted below)
  82. output_pattern -- pattern to use for the package names. Must include %s.
  83. description -- description to set for each package. Must include %s.
  84. postinst -- postinstall script to use for all packages (as a
  85. string)
  86. recursive -- True to perform a recursive search - default False
  87. hook -- a hook function to be called for every match. The
  88. function will be called with the following arguments
  89. (in the order listed):
  90. f: full path to the file/directory match
  91. pkg: the package name
  92. file_regex: as above
  93. output_pattern: as above
  94. modulename: the module name derived using file_regex
  95. extra_depends -- extra runtime dependencies (RDEPENDS) to be set for
  96. all packages. The default value of None causes a
  97. dependency on the main package (${PN}) - if you do
  98. not want this, pass '' for this parameter.
  99. aux_files_pattern -- extra item(s) to be added to FILES for each
  100. package. Can be a single string item or a list of
  101. strings for multiple items. Must include %s.
  102. postrm -- postrm script to use for all packages (as a string)
  103. allow_dirs -- True allow directories to be matched - default False
  104. prepend -- if True, prepend created packages to PACKAGES instead
  105. of the default False which appends them
  106. match_path -- match file_regex on the whole relative path to the
  107. root rather than just the file name
  108. aux_files_pattern_verbatim -- extra item(s) to be added to FILES for
  109. each package, using the actual derived module name
  110. rather than converting it to something legal for a
  111. package name. Can be a single string item or a list
  112. of strings for multiple items. Must include %s.
  113. allow_links -- True to allow symlinks to be matched - default False
  114. summary -- Summary to set for each package. Must include %s;
  115. defaults to description if not set.
  116. """
  117. dvar = d.getVar('PKGD')
  118. root = d.expand(root)
  119. output_pattern = d.expand(output_pattern)
  120. extra_depends = d.expand(extra_depends)
  121. # If the root directory doesn't exist, don't error out later but silently do
  122. # no splitting.
  123. if not os.path.exists(dvar + root):
  124. return []
  125. ml = d.getVar("MLPREFIX")
  126. if ml:
  127. if not output_pattern.startswith(ml):
  128. output_pattern = ml + output_pattern
  129. newdeps = []
  130. for dep in (extra_depends or "").split():
  131. if dep.startswith(ml):
  132. newdeps.append(dep)
  133. else:
  134. newdeps.append(ml + dep)
  135. if newdeps:
  136. extra_depends = " ".join(newdeps)
  137. packages = d.getVar('PACKAGES').split()
  138. split_packages = set()
  139. if postinst:
  140. postinst = '#!/bin/sh\n' + postinst + '\n'
  141. if postrm:
  142. postrm = '#!/bin/sh\n' + postrm + '\n'
  143. if not recursive:
  144. objs = os.listdir(dvar + root)
  145. else:
  146. objs = []
  147. for walkroot, dirs, files in os.walk(dvar + root):
  148. for file in files:
  149. relpath = os.path.join(walkroot, file).replace(dvar + root + '/', '', 1)
  150. if relpath:
  151. objs.append(relpath)
  152. if extra_depends == None:
  153. extra_depends = d.getVar("PN")
  154. if not summary:
  155. summary = description
  156. for o in sorted(objs):
  157. import re, stat
  158. if match_path:
  159. m = re.match(file_regex, o)
  160. else:
  161. m = re.match(file_regex, os.path.basename(o))
  162. if not m:
  163. continue
  164. f = os.path.join(dvar + root, o)
  165. mode = os.lstat(f).st_mode
  166. if not (stat.S_ISREG(mode) or (allow_links and stat.S_ISLNK(mode)) or (allow_dirs and stat.S_ISDIR(mode))):
  167. continue
  168. on = legitimize_package_name(m.group(1))
  169. pkg = output_pattern % on
  170. split_packages.add(pkg)
  171. if not pkg in packages:
  172. if prepend:
  173. packages = [pkg] + packages
  174. else:
  175. packages.append(pkg)
  176. oldfiles = d.getVar('FILES_' + pkg)
  177. newfile = os.path.join(root, o)
  178. # These names will be passed through glob() so if the filename actually
  179. # contains * or ? (rare, but possible) we need to handle that specially
  180. newfile = newfile.replace('*', '[*]')
  181. newfile = newfile.replace('?', '[?]')
  182. if not oldfiles:
  183. the_files = [newfile]
  184. if aux_files_pattern:
  185. if type(aux_files_pattern) is list:
  186. for fp in aux_files_pattern:
  187. the_files.append(fp % on)
  188. else:
  189. the_files.append(aux_files_pattern % on)
  190. if aux_files_pattern_verbatim:
  191. if type(aux_files_pattern_verbatim) is list:
  192. for fp in aux_files_pattern_verbatim:
  193. the_files.append(fp % m.group(1))
  194. else:
  195. the_files.append(aux_files_pattern_verbatim % m.group(1))
  196. d.setVar('FILES_' + pkg, " ".join(the_files))
  197. else:
  198. d.setVar('FILES_' + pkg, oldfiles + " " + newfile)
  199. if extra_depends != '':
  200. d.appendVar('RDEPENDS_' + pkg, ' ' + extra_depends)
  201. if not d.getVar('DESCRIPTION_' + pkg):
  202. d.setVar('DESCRIPTION_' + pkg, description % on)
  203. if not d.getVar('SUMMARY_' + pkg):
  204. d.setVar('SUMMARY_' + pkg, summary % on)
  205. if postinst:
  206. d.setVar('pkg_postinst_' + pkg, postinst)
  207. if postrm:
  208. d.setVar('pkg_postrm_' + pkg, postrm)
  209. if callable(hook):
  210. hook(f, pkg, file_regex, output_pattern, m.group(1))
  211. d.setVar('PACKAGES', ' '.join(packages))
  212. return list(split_packages)
  213. PACKAGE_DEPENDS += "file-native"
  214. python () {
  215. if d.getVar('PACKAGES') != '':
  216. deps = ""
  217. for dep in (d.getVar('PACKAGE_DEPENDS') or "").split():
  218. deps += " %s:do_populate_sysroot" % dep
  219. if d.getVar('PACKAGE_MINIDEBUGINFO') == '1':
  220. deps += ' xz-native:do_populate_sysroot'
  221. d.appendVarFlag('do_package', 'depends', deps)
  222. # shlibs requires any DEPENDS to have already packaged for the *.list files
  223. d.appendVarFlag('do_package', 'deptask', " do_packagedata")
  224. }
  225. # Get a list of files from file vars by searching files under current working directory
  226. # The list contains symlinks, directories and normal files.
  227. def files_from_filevars(filevars):
  228. import os,glob
  229. cpath = oe.cachedpath.CachedPath()
  230. files = []
  231. for f in filevars:
  232. if os.path.isabs(f):
  233. f = '.' + f
  234. if not f.startswith("./"):
  235. f = './' + f
  236. globbed = glob.glob(f)
  237. if globbed:
  238. if [ f ] != globbed:
  239. files += globbed
  240. continue
  241. files.append(f)
  242. symlink_paths = []
  243. for ind, f in enumerate(files):
  244. # Handle directory symlinks. Truncate path to the lowest level symlink
  245. parent = ''
  246. for dirname in f.split('/')[:-1]:
  247. parent = os.path.join(parent, dirname)
  248. if dirname == '.':
  249. continue
  250. if cpath.islink(parent):
  251. bb.warn("FILES contains file '%s' which resides under a "
  252. "directory symlink. Please fix the recipe and use the "
  253. "real path for the file." % f[1:])
  254. symlink_paths.append(f)
  255. files[ind] = parent
  256. f = parent
  257. break
  258. if not cpath.islink(f):
  259. if cpath.isdir(f):
  260. newfiles = [ os.path.join(f,x) for x in os.listdir(f) ]
  261. if newfiles:
  262. files += newfiles
  263. return files, symlink_paths
  264. # Called in package_<rpm,ipk,deb>.bbclass to get the correct list of configuration files
  265. def get_conffiles(pkg, d):
  266. pkgdest = d.getVar('PKGDEST')
  267. root = os.path.join(pkgdest, pkg)
  268. cwd = os.getcwd()
  269. os.chdir(root)
  270. conffiles = d.getVar('CONFFILES_%s' % pkg);
  271. if conffiles == None:
  272. conffiles = d.getVar('CONFFILES')
  273. if conffiles == None:
  274. conffiles = ""
  275. conffiles = conffiles.split()
  276. conf_orig_list = files_from_filevars(conffiles)[0]
  277. # Remove links and directories from conf_orig_list to get conf_list which only contains normal files
  278. conf_list = []
  279. for f in conf_orig_list:
  280. if os.path.isdir(f):
  281. continue
  282. if os.path.islink(f):
  283. continue
  284. if not os.path.exists(f):
  285. continue
  286. conf_list.append(f)
  287. # Remove the leading './'
  288. for i in range(0, len(conf_list)):
  289. conf_list[i] = conf_list[i][1:]
  290. os.chdir(cwd)
  291. return conf_list
  292. def checkbuildpath(file, d):
  293. tmpdir = d.getVar('TMPDIR')
  294. with open(file) as f:
  295. file_content = f.read()
  296. if tmpdir in file_content:
  297. return True
  298. return False
  299. def parse_debugsources_from_dwarfsrcfiles_output(dwarfsrcfiles_output):
  300. debugfiles = {}
  301. for line in dwarfsrcfiles_output.splitlines():
  302. if line.startswith("\t"):
  303. debugfiles[os.path.normpath(line.split()[0])] = ""
  304. return debugfiles.keys()
  305. def source_info(file, d, fatal=True):
  306. import subprocess
  307. cmd = ["dwarfsrcfiles", file]
  308. try:
  309. output = subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.STDOUT)
  310. retval = 0
  311. except subprocess.CalledProcessError as exc:
  312. output = exc.output
  313. retval = exc.returncode
  314. # 255 means a specific file wasn't fully parsed to get the debug file list, which is not a fatal failure
  315. if retval != 0 and retval != 255:
  316. msg = "dwarfsrcfiles failed with exit code %s (cmd was %s)%s" % (retval, cmd, ":\n%s" % output if output else "")
  317. if fatal:
  318. bb.fatal(msg)
  319. bb.note(msg)
  320. debugsources = parse_debugsources_from_dwarfsrcfiles_output(output)
  321. return list(debugsources)
  322. def splitdebuginfo(file, dvar, debugdir, debuglibdir, debugappend, debugsrcdir, d):
  323. # Function to split a single file into two components, one is the stripped
  324. # target system binary, the other contains any debugging information. The
  325. # two files are linked to reference each other.
  326. #
  327. # return a mapping of files:debugsources
  328. import stat
  329. import subprocess
  330. src = file[len(dvar):]
  331. dest = debuglibdir + os.path.dirname(src) + debugdir + "/" + os.path.basename(src) + debugappend
  332. debugfile = dvar + dest
  333. sources = []
  334. # Split the file...
  335. bb.utils.mkdirhier(os.path.dirname(debugfile))
  336. #bb.note("Split %s -> %s" % (file, debugfile))
  337. # Only store off the hard link reference if we successfully split!
  338. dvar = d.getVar('PKGD')
  339. objcopy = d.getVar("OBJCOPY")
  340. # We ignore kernel modules, we don't generate debug info files.
  341. if file.find("/lib/modules/") != -1 and file.endswith(".ko"):
  342. return (file, sources)
  343. newmode = None
  344. if not os.access(file, os.W_OK) or os.access(file, os.R_OK):
  345. origmode = os.stat(file)[stat.ST_MODE]
  346. newmode = origmode | stat.S_IWRITE | stat.S_IREAD
  347. os.chmod(file, newmode)
  348. # We need to extract the debug src information here...
  349. if debugsrcdir:
  350. sources = source_info(file, d)
  351. bb.utils.mkdirhier(os.path.dirname(debugfile))
  352. subprocess.check_output([objcopy, '--only-keep-debug', file, debugfile], stderr=subprocess.STDOUT)
  353. # Set the debuglink to have the view of the file path on the target
  354. subprocess.check_output([objcopy, '--add-gnu-debuglink', debugfile, file], stderr=subprocess.STDOUT)
  355. if newmode:
  356. os.chmod(file, origmode)
  357. return (file, sources)
  358. def splitstaticdebuginfo(file, dvar, debugstaticdir, debugstaticlibdir, debugstaticappend, debugsrcdir, d):
  359. # Unlike the function above, there is no way to split a static library
  360. # two components. So to get similar results we will copy the unmodified
  361. # static library (containing the debug symbols) into a new directory.
  362. # We will then strip (preserving symbols) the static library in the
  363. # typical location.
  364. #
  365. # return a mapping of files:debugsources
  366. import stat
  367. import shutil
  368. src = file[len(dvar):]
  369. dest = debugstaticlibdir + os.path.dirname(src) + debugstaticdir + "/" + os.path.basename(src) + debugstaticappend
  370. debugfile = dvar + dest
  371. sources = []
  372. # Copy the file...
  373. bb.utils.mkdirhier(os.path.dirname(debugfile))
  374. #bb.note("Copy %s -> %s" % (file, debugfile))
  375. dvar = d.getVar('PKGD')
  376. newmode = None
  377. if not os.access(file, os.W_OK) or os.access(file, os.R_OK):
  378. origmode = os.stat(file)[stat.ST_MODE]
  379. newmode = origmode | stat.S_IWRITE | stat.S_IREAD
  380. os.chmod(file, newmode)
  381. # We need to extract the debug src information here...
  382. if debugsrcdir:
  383. sources = source_info(file, d)
  384. bb.utils.mkdirhier(os.path.dirname(debugfile))
  385. # Copy the unmodified item to the debug directory
  386. shutil.copy2(file, debugfile)
  387. if newmode:
  388. os.chmod(file, origmode)
  389. return (file, sources)
  390. def inject_minidebuginfo(file, dvar, debugdir, debuglibdir, debugappend, debugsrcdir, d):
  391. # Extract just the symbols from debuginfo into minidebuginfo,
  392. # compress it with xz and inject it back into the binary in a .gnu_debugdata section.
  393. # https://sourceware.org/gdb/onlinedocs/gdb/MiniDebugInfo.html
  394. import subprocess
  395. readelf = d.getVar('READELF')
  396. nm = d.getVar('NM')
  397. objcopy = d.getVar('OBJCOPY')
  398. minidebuginfodir = d.expand('${WORKDIR}/minidebuginfo')
  399. src = file[len(dvar):]
  400. dest = debuglibdir + os.path.dirname(src) + debugdir + "/" + os.path.basename(src) + debugappend
  401. debugfile = dvar + dest
  402. minidebugfile = minidebuginfodir + src + '.minidebug'
  403. bb.utils.mkdirhier(os.path.dirname(minidebugfile))
  404. # If we didn't produce debuginfo for any reason, we can't produce minidebuginfo either
  405. # so skip it.
  406. if not os.path.exists(debugfile):
  407. bb.debug(1, 'ELF file {} has no debuginfo, skipping minidebuginfo injection'.format(file))
  408. return
  409. # Find non-allocated PROGBITS, NOTE, and NOBITS sections in the debuginfo.
  410. # We will exclude all of these from minidebuginfo to save space.
  411. remove_section_names = []
  412. for line in subprocess.check_output([readelf, '-W', '-S', debugfile], universal_newlines=True).splitlines():
  413. fields = line.split()
  414. if len(fields) < 8:
  415. continue
  416. name = fields[0]
  417. type = fields[1]
  418. flags = fields[7]
  419. # .debug_ sections will be removed by objcopy -S so no need to explicitly remove them
  420. if name.startswith('.debug_'):
  421. continue
  422. if 'A' not in flags and type in ['PROGBITS', 'NOTE', 'NOBITS']:
  423. remove_section_names.append(name)
  424. # List dynamic symbols in the binary. We can exclude these from minidebuginfo
  425. # because they are always present in the binary.
  426. dynsyms = set()
  427. for line in subprocess.check_output([nm, '-D', file, '--format=posix', '--defined-only'], universal_newlines=True).splitlines():
  428. dynsyms.add(line.split()[0])
  429. # Find all function symbols from debuginfo which aren't in the dynamic symbols table.
  430. # These are the ones we want to keep in minidebuginfo.
  431. keep_symbols_file = minidebugfile + '.symlist'
  432. found_any_symbols = False
  433. with open(keep_symbols_file, 'w') as f:
  434. for line in subprocess.check_output([nm, debugfile, '--format=sysv', '--defined-only'], universal_newlines=True).splitlines():
  435. fields = line.split('|')
  436. if len(fields) < 7:
  437. continue
  438. name = fields[0].strip()
  439. type = fields[3].strip()
  440. if type == 'FUNC' and name not in dynsyms:
  441. f.write('{}\n'.format(name))
  442. found_any_symbols = True
  443. if not found_any_symbols:
  444. bb.debug(1, 'ELF file {} contains no symbols, skipping minidebuginfo injection'.format(file))
  445. return
  446. bb.utils.remove(minidebugfile)
  447. bb.utils.remove(minidebugfile + '.xz')
  448. subprocess.check_call([objcopy, '-S'] +
  449. ['--remove-section={}'.format(s) for s in remove_section_names] +
  450. ['--keep-symbols={}'.format(keep_symbols_file), debugfile, minidebugfile])
  451. subprocess.check_call(['xz', '--keep', minidebugfile])
  452. subprocess.check_call([objcopy, '--add-section', '.gnu_debugdata={}.xz'.format(minidebugfile), file])
  453. def copydebugsources(debugsrcdir, sources, d):
  454. # The debug src information written out to sourcefile is further processed
  455. # and copied to the destination here.
  456. import stat
  457. import subprocess
  458. if debugsrcdir and sources:
  459. sourcefile = d.expand("${WORKDIR}/debugsources.list")
  460. bb.utils.remove(sourcefile)
  461. # filenames are null-separated - this is an artefact of the previous use
  462. # of rpm's debugedit, which was writing them out that way, and the code elsewhere
  463. # is still assuming that.
  464. debuglistoutput = '\0'.join(sources) + '\0'
  465. with open(sourcefile, 'a') as sf:
  466. sf.write(debuglistoutput)
  467. dvar = d.getVar('PKGD')
  468. strip = d.getVar("STRIP")
  469. objcopy = d.getVar("OBJCOPY")
  470. workdir = d.getVar("WORKDIR")
  471. workparentdir = os.path.dirname(os.path.dirname(workdir))
  472. workbasedir = os.path.basename(os.path.dirname(workdir)) + "/" + os.path.basename(workdir)
  473. # If build path exists in sourcefile, it means toolchain did not use
  474. # -fdebug-prefix-map to compile
  475. if checkbuildpath(sourcefile, d):
  476. localsrc_prefix = workparentdir + "/"
  477. else:
  478. localsrc_prefix = "/usr/src/debug/"
  479. nosuchdir = []
  480. basepath = dvar
  481. for p in debugsrcdir.split("/"):
  482. basepath = basepath + "/" + p
  483. if not cpath.exists(basepath):
  484. nosuchdir.append(basepath)
  485. bb.utils.mkdirhier(basepath)
  486. cpath.updatecache(basepath)
  487. # Ignore files from the recipe sysroots (target and native)
  488. processdebugsrc = "LC_ALL=C ; sort -z -u '%s' | egrep -v -z '((<internal>|<built-in>)$|/.*recipe-sysroot.*/)' | "
  489. # We need to ignore files that are not actually ours
  490. # we do this by only paying attention to items from this package
  491. processdebugsrc += "fgrep -zw '%s' | "
  492. # Remove prefix in the source paths
  493. processdebugsrc += "sed 's#%s##g' | "
  494. processdebugsrc += "(cd '%s' ; cpio -pd0mlL --no-preserve-owner '%s%s' 2>/dev/null)"
  495. cmd = processdebugsrc % (sourcefile, workbasedir, localsrc_prefix, workparentdir, dvar, debugsrcdir)
  496. try:
  497. subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
  498. except subprocess.CalledProcessError:
  499. # Can "fail" if internal headers/transient sources are attempted
  500. pass
  501. # cpio seems to have a bug with -lL together and symbolic links are just copied, not dereferenced.
  502. # Work around this by manually finding and copying any symbolic links that made it through.
  503. cmd = "find %s%s -type l -print0 -delete | sed s#%s%s/##g | (cd '%s' ; cpio -pd0mL --no-preserve-owner '%s%s')" % \
  504. (dvar, debugsrcdir, dvar, debugsrcdir, workparentdir, dvar, debugsrcdir)
  505. subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
  506. # The copy by cpio may have resulted in some empty directories! Remove these
  507. cmd = "find %s%s -empty -type d -delete" % (dvar, debugsrcdir)
  508. subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
  509. # Also remove debugsrcdir if its empty
  510. for p in nosuchdir[::-1]:
  511. if os.path.exists(p) and not os.listdir(p):
  512. os.rmdir(p)
  513. #
  514. # Package data handling routines
  515. #
  516. def get_package_mapping (pkg, basepkg, d, depversions=None):
  517. import oe.packagedata
  518. data = oe.packagedata.read_subpkgdata(pkg, d)
  519. key = "PKG_%s" % pkg
  520. if key in data:
  521. # Have to avoid undoing the write_extra_pkgs(global_variants...)
  522. if bb.data.inherits_class('allarch', d) and not d.getVar('MULTILIB_VARIANTS') \
  523. and data[key] == basepkg:
  524. return pkg
  525. if depversions == []:
  526. # Avoid returning a mapping if the renamed package rprovides its original name
  527. rprovkey = "RPROVIDES_%s" % pkg
  528. if rprovkey in data:
  529. if pkg in bb.utils.explode_dep_versions2(data[rprovkey]):
  530. bb.note("%s rprovides %s, not replacing the latter" % (data[key], pkg))
  531. return pkg
  532. # Do map to rewritten package name
  533. return data[key]
  534. return pkg
  535. def get_package_additional_metadata (pkg_type, d):
  536. base_key = "PACKAGE_ADD_METADATA"
  537. for key in ("%s_%s" % (base_key, pkg_type.upper()), base_key):
  538. if d.getVar(key, False) is None:
  539. continue
  540. d.setVarFlag(key, "type", "list")
  541. if d.getVarFlag(key, "separator") is None:
  542. d.setVarFlag(key, "separator", "\\n")
  543. metadata_fields = [field.strip() for field in oe.data.typed_value(key, d)]
  544. return "\n".join(metadata_fields).strip()
  545. def runtime_mapping_rename (varname, pkg, d):
  546. #bb.note("%s before: %s" % (varname, d.getVar(varname)))
  547. new_depends = {}
  548. deps = bb.utils.explode_dep_versions2(d.getVar(varname) or "")
  549. for depend, depversions in deps.items():
  550. new_depend = get_package_mapping(depend, pkg, d, depversions)
  551. if depend != new_depend:
  552. bb.note("package name mapping done: %s -> %s" % (depend, new_depend))
  553. new_depends[new_depend] = deps[depend]
  554. d.setVar(varname, bb.utils.join_deps(new_depends, commasep=False))
  555. #bb.note("%s after: %s" % (varname, d.getVar(varname)))
  556. #
  557. # Used by do_packagedata (and possibly other routines post do_package)
  558. #
  559. package_get_auto_pr[vardepsexclude] = "BB_TASKDEPDATA"
  560. python package_get_auto_pr() {
  561. import oe.prservice
  562. def get_do_package_hash(pn):
  563. if d.getVar("BB_RUNTASK") != "do_package":
  564. taskdepdata = d.getVar("BB_TASKDEPDATA", False)
  565. for dep in taskdepdata:
  566. if taskdepdata[dep][1] == "do_package" and taskdepdata[dep][0] == pn:
  567. return taskdepdata[dep][6]
  568. return None
  569. # Support per recipe PRSERV_HOST
  570. pn = d.getVar('PN')
  571. host = d.getVar("PRSERV_HOST_" + pn)
  572. if not (host is None):
  573. d.setVar("PRSERV_HOST", host)
  574. pkgv = d.getVar("PKGV")
  575. # PR Server not active, handle AUTOINC
  576. if not d.getVar('PRSERV_HOST'):
  577. d.setVar("PRSERV_PV_AUTOINC", "0")
  578. return
  579. auto_pr = None
  580. pv = d.getVar("PV")
  581. version = d.getVar("PRAUTOINX")
  582. pkgarch = d.getVar("PACKAGE_ARCH")
  583. checksum = get_do_package_hash(pn)
  584. # If do_package isn't in the dependencies, we can't get the checksum...
  585. if not checksum:
  586. bb.warn('Task %s requested do_package unihash, but it was not available.' % d.getVar('BB_RUNTASK'))
  587. #taskdepdata = d.getVar("BB_TASKDEPDATA", False)
  588. #for dep in taskdepdata:
  589. # bb.warn('%s:%s = %s' % (taskdepdata[dep][0], taskdepdata[dep][1], taskdepdata[dep][6]))
  590. return
  591. if d.getVar('PRSERV_LOCKDOWN'):
  592. auto_pr = d.getVar('PRAUTO_' + version + '_' + pkgarch) or d.getVar('PRAUTO_' + version) or None
  593. if auto_pr is None:
  594. bb.fatal("Can NOT get PRAUTO from lockdown exported file")
  595. d.setVar('PRAUTO',str(auto_pr))
  596. return
  597. try:
  598. conn = d.getVar("__PRSERV_CONN")
  599. if conn is None:
  600. conn = oe.prservice.prserv_make_conn(d)
  601. if conn is not None:
  602. if "AUTOINC" in pkgv:
  603. srcpv = bb.fetch2.get_srcrev(d)
  604. base_ver = "AUTOINC-%s" % version[:version.find(srcpv)]
  605. value = conn.getPR(base_ver, pkgarch, srcpv)
  606. d.setVar("PRSERV_PV_AUTOINC", str(value))
  607. auto_pr = conn.getPR(version, pkgarch, checksum)
  608. except Exception as e:
  609. bb.fatal("Can NOT get PRAUTO, exception %s" % str(e))
  610. if auto_pr is None:
  611. bb.fatal("Can NOT get PRAUTO from remote PR service")
  612. d.setVar('PRAUTO',str(auto_pr))
  613. }
  614. #
  615. # Package functions suitable for inclusion in PACKAGEFUNCS
  616. #
  617. python package_convert_pr_autoinc() {
  618. pkgv = d.getVar("PKGV")
  619. # Adjust pkgv as necessary...
  620. if 'AUTOINC' in pkgv:
  621. d.setVar("PKGV", pkgv.replace("AUTOINC", "${PRSERV_PV_AUTOINC}"))
  622. # Change PRSERV_PV_AUTOINC and EXTENDPRAUTO usage to special values
  623. d.setVar('PRSERV_PV_AUTOINC', '@PRSERV_PV_AUTOINC@')
  624. d.setVar('EXTENDPRAUTO', '@EXTENDPRAUTO@')
  625. }
  626. LOCALEBASEPN ??= "${PN}"
  627. python package_do_split_locales() {
  628. if (d.getVar('PACKAGE_NO_LOCALE') == '1'):
  629. bb.debug(1, "package requested not splitting locales")
  630. return
  631. packages = (d.getVar('PACKAGES') or "").split()
  632. datadir = d.getVar('datadir')
  633. if not datadir:
  634. bb.note("datadir not defined")
  635. return
  636. dvar = d.getVar('PKGD')
  637. pn = d.getVar('LOCALEBASEPN')
  638. if pn + '-locale' in packages:
  639. packages.remove(pn + '-locale')
  640. localedir = os.path.join(dvar + datadir, 'locale')
  641. if not cpath.isdir(localedir):
  642. bb.debug(1, "No locale files in this package")
  643. return
  644. locales = os.listdir(localedir)
  645. summary = d.getVar('SUMMARY') or pn
  646. description = d.getVar('DESCRIPTION') or ""
  647. locale_section = d.getVar('LOCALE_SECTION')
  648. mlprefix = d.getVar('MLPREFIX') or ""
  649. for l in sorted(locales):
  650. ln = legitimize_package_name(l)
  651. pkg = pn + '-locale-' + ln
  652. packages.append(pkg)
  653. d.setVar('FILES_' + pkg, os.path.join(datadir, 'locale', l))
  654. d.setVar('RRECOMMENDS_' + pkg, '%svirtual-locale-%s' % (mlprefix, ln))
  655. d.setVar('RPROVIDES_' + pkg, '%s-locale %s%s-translation' % (pn, mlprefix, ln))
  656. d.setVar('SUMMARY_' + pkg, '%s - %s translations' % (summary, l))
  657. d.setVar('DESCRIPTION_' + pkg, '%s This package contains language translation files for the %s locale.' % (description, l))
  658. if locale_section:
  659. d.setVar('SECTION_' + pkg, locale_section)
  660. d.setVar('PACKAGES', ' '.join(packages))
  661. # Disabled by RP 18/06/07
  662. # Wildcards aren't supported in debian
  663. # They break with ipkg since glibc-locale* will mean that
  664. # glibc-localedata-translit* won't install as a dependency
  665. # for some other package which breaks meta-toolchain
  666. # Probably breaks since virtual-locale- isn't provided anywhere
  667. #rdep = (d.getVar('RDEPENDS_%s' % pn) or "").split()
  668. #rdep.append('%s-locale*' % pn)
  669. #d.setVar('RDEPENDS_%s' % pn, ' '.join(rdep))
  670. }
  671. python perform_packagecopy () {
  672. import subprocess
  673. dest = d.getVar('D')
  674. dvar = d.getVar('PKGD')
  675. # Start by package population by taking a copy of the installed
  676. # files to operate on
  677. # Preserve sparse files and hard links
  678. cmd = 'tar -cf - -C %s -p -S . | tar -xf - -C %s' % (dest, dvar)
  679. subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
  680. # replace RPATHs for the nativesdk binaries, to make them relocatable
  681. if bb.data.inherits_class('nativesdk', d) or bb.data.inherits_class('cross-canadian', d):
  682. rpath_replace (dvar, d)
  683. }
  684. perform_packagecopy[cleandirs] = "${PKGD}"
  685. perform_packagecopy[dirs] = "${PKGD}"
  686. # We generate a master list of directories to process, we start by
  687. # seeding this list with reasonable defaults, then load from
  688. # the fs-perms.txt files
  689. python fixup_perms () {
  690. import pwd, grp
  691. # init using a string with the same format as a line as documented in
  692. # the fs-perms.txt file
  693. # <path> <mode> <uid> <gid> <walk> <fmode> <fuid> <fgid>
  694. # <path> link <link target>
  695. #
  696. # __str__ can be used to print out an entry in the input format
  697. #
  698. # if fs_perms_entry.path is None:
  699. # an error occurred
  700. # if fs_perms_entry.link, you can retrieve:
  701. # fs_perms_entry.path = path
  702. # fs_perms_entry.link = target of link
  703. # if not fs_perms_entry.link, you can retrieve:
  704. # fs_perms_entry.path = path
  705. # fs_perms_entry.mode = expected dir mode or None
  706. # fs_perms_entry.uid = expected uid or -1
  707. # fs_perms_entry.gid = expected gid or -1
  708. # fs_perms_entry.walk = 'true' or something else
  709. # fs_perms_entry.fmode = expected file mode or None
  710. # fs_perms_entry.fuid = expected file uid or -1
  711. # fs_perms_entry_fgid = expected file gid or -1
  712. class fs_perms_entry():
  713. def __init__(self, line):
  714. lsplit = line.split()
  715. if len(lsplit) == 3 and lsplit[1].lower() == "link":
  716. self._setlink(lsplit[0], lsplit[2])
  717. elif len(lsplit) == 8:
  718. self._setdir(lsplit[0], lsplit[1], lsplit[2], lsplit[3], lsplit[4], lsplit[5], lsplit[6], lsplit[7])
  719. else:
  720. msg = "Fixup Perms: invalid config line %s" % line
  721. package_qa_handle_error("perm-config", msg, d)
  722. self.path = None
  723. self.link = None
  724. def _setdir(self, path, mode, uid, gid, walk, fmode, fuid, fgid):
  725. self.path = os.path.normpath(path)
  726. self.link = None
  727. self.mode = self._procmode(mode)
  728. self.uid = self._procuid(uid)
  729. self.gid = self._procgid(gid)
  730. self.walk = walk.lower()
  731. self.fmode = self._procmode(fmode)
  732. self.fuid = self._procuid(fuid)
  733. self.fgid = self._procgid(fgid)
  734. def _setlink(self, path, link):
  735. self.path = os.path.normpath(path)
  736. self.link = link
  737. def _procmode(self, mode):
  738. if not mode or (mode and mode == "-"):
  739. return None
  740. else:
  741. return int(mode,8)
  742. # Note uid/gid -1 has special significance in os.lchown
  743. def _procuid(self, uid):
  744. if uid is None or uid == "-":
  745. return -1
  746. elif uid.isdigit():
  747. return int(uid)
  748. else:
  749. return pwd.getpwnam(uid).pw_uid
  750. def _procgid(self, gid):
  751. if gid is None or gid == "-":
  752. return -1
  753. elif gid.isdigit():
  754. return int(gid)
  755. else:
  756. return grp.getgrnam(gid).gr_gid
  757. # Use for debugging the entries
  758. def __str__(self):
  759. if self.link:
  760. return "%s link %s" % (self.path, self.link)
  761. else:
  762. mode = "-"
  763. if self.mode:
  764. mode = "0%o" % self.mode
  765. fmode = "-"
  766. if self.fmode:
  767. fmode = "0%o" % self.fmode
  768. uid = self._mapugid(self.uid)
  769. gid = self._mapugid(self.gid)
  770. fuid = self._mapugid(self.fuid)
  771. fgid = self._mapugid(self.fgid)
  772. return "%s %s %s %s %s %s %s %s" % (self.path, mode, uid, gid, self.walk, fmode, fuid, fgid)
  773. def _mapugid(self, id):
  774. if id is None or id == -1:
  775. return "-"
  776. else:
  777. return "%d" % id
  778. # Fix the permission, owner and group of path
  779. def fix_perms(path, mode, uid, gid, dir):
  780. if mode and not os.path.islink(path):
  781. #bb.note("Fixup Perms: chmod 0%o %s" % (mode, dir))
  782. os.chmod(path, mode)
  783. # -1 is a special value that means don't change the uid/gid
  784. # if they are BOTH -1, don't bother to lchown
  785. if not (uid == -1 and gid == -1):
  786. #bb.note("Fixup Perms: lchown %d:%d %s" % (uid, gid, dir))
  787. os.lchown(path, uid, gid)
  788. # Return a list of configuration files based on either the default
  789. # files/fs-perms.txt or the contents of FILESYSTEM_PERMS_TABLES
  790. # paths are resolved via BBPATH
  791. def get_fs_perms_list(d):
  792. str = ""
  793. bbpath = d.getVar('BBPATH')
  794. fs_perms_tables = d.getVar('FILESYSTEM_PERMS_TABLES') or ""
  795. for conf_file in fs_perms_tables.split():
  796. confpath = bb.utils.which(bbpath, conf_file)
  797. if confpath:
  798. str += " %s" % bb.utils.which(bbpath, conf_file)
  799. else:
  800. bb.warn("cannot find %s specified in FILESYSTEM_PERMS_TABLES" % conf_file)
  801. return str
  802. dvar = d.getVar('PKGD')
  803. fs_perms_table = {}
  804. fs_link_table = {}
  805. # By default all of the standard directories specified in
  806. # bitbake.conf will get 0755 root:root.
  807. target_path_vars = [ 'base_prefix',
  808. 'prefix',
  809. 'exec_prefix',
  810. 'base_bindir',
  811. 'base_sbindir',
  812. 'base_libdir',
  813. 'datadir',
  814. 'sysconfdir',
  815. 'servicedir',
  816. 'sharedstatedir',
  817. 'localstatedir',
  818. 'infodir',
  819. 'mandir',
  820. 'docdir',
  821. 'bindir',
  822. 'sbindir',
  823. 'libexecdir',
  824. 'libdir',
  825. 'includedir',
  826. 'oldincludedir' ]
  827. for path in target_path_vars:
  828. dir = d.getVar(path) or ""
  829. if dir == "":
  830. continue
  831. fs_perms_table[dir] = fs_perms_entry(d.expand("%s 0755 root root false - - -" % (dir)))
  832. # Now we actually load from the configuration files
  833. for conf in get_fs_perms_list(d).split():
  834. if not os.path.exists(conf):
  835. continue
  836. with open(conf) as f:
  837. for line in f:
  838. if line.startswith('#'):
  839. continue
  840. lsplit = line.split()
  841. if len(lsplit) == 0:
  842. continue
  843. if len(lsplit) != 8 and not (len(lsplit) == 3 and lsplit[1].lower() == "link"):
  844. msg = "Fixup perms: %s invalid line: %s" % (conf, line)
  845. package_qa_handle_error("perm-line", msg, d)
  846. continue
  847. entry = fs_perms_entry(d.expand(line))
  848. if entry and entry.path:
  849. if entry.link:
  850. fs_link_table[entry.path] = entry
  851. if entry.path in fs_perms_table:
  852. fs_perms_table.pop(entry.path)
  853. else:
  854. fs_perms_table[entry.path] = entry
  855. if entry.path in fs_link_table:
  856. fs_link_table.pop(entry.path)
  857. # Debug -- list out in-memory table
  858. #for dir in fs_perms_table:
  859. # bb.note("Fixup Perms: %s: %s" % (dir, str(fs_perms_table[dir])))
  860. #for link in fs_link_table:
  861. # bb.note("Fixup Perms: %s: %s" % (link, str(fs_link_table[link])))
  862. # We process links first, so we can go back and fixup directory ownership
  863. # for any newly created directories
  864. # Process in sorted order so /run gets created before /run/lock, etc.
  865. for entry in sorted(fs_link_table.values(), key=lambda x: x.link):
  866. link = entry.link
  867. dir = entry.path
  868. origin = dvar + dir
  869. if not (cpath.exists(origin) and cpath.isdir(origin) and not cpath.islink(origin)):
  870. continue
  871. if link[0] == "/":
  872. target = dvar + link
  873. ptarget = link
  874. else:
  875. target = os.path.join(os.path.dirname(origin), link)
  876. ptarget = os.path.join(os.path.dirname(dir), link)
  877. if os.path.exists(target):
  878. msg = "Fixup Perms: Unable to correct directory link, target already exists: %s -> %s" % (dir, ptarget)
  879. package_qa_handle_error("perm-link", msg, d)
  880. continue
  881. # Create path to move directory to, move it, and then setup the symlink
  882. bb.utils.mkdirhier(os.path.dirname(target))
  883. #bb.note("Fixup Perms: Rename %s -> %s" % (dir, ptarget))
  884. os.rename(origin, target)
  885. #bb.note("Fixup Perms: Link %s -> %s" % (dir, link))
  886. os.symlink(link, origin)
  887. for dir in fs_perms_table:
  888. origin = dvar + dir
  889. if not (cpath.exists(origin) and cpath.isdir(origin)):
  890. continue
  891. fix_perms(origin, fs_perms_table[dir].mode, fs_perms_table[dir].uid, fs_perms_table[dir].gid, dir)
  892. if fs_perms_table[dir].walk == 'true':
  893. for root, dirs, files in os.walk(origin):
  894. for dr in dirs:
  895. each_dir = os.path.join(root, dr)
  896. fix_perms(each_dir, fs_perms_table[dir].mode, fs_perms_table[dir].uid, fs_perms_table[dir].gid, dir)
  897. for f in files:
  898. each_file = os.path.join(root, f)
  899. fix_perms(each_file, fs_perms_table[dir].fmode, fs_perms_table[dir].fuid, fs_perms_table[dir].fgid, dir)
  900. }
  901. python split_and_strip_files () {
  902. import stat, errno
  903. import subprocess
  904. dvar = d.getVar('PKGD')
  905. pn = d.getVar('PN')
  906. hostos = d.getVar('HOST_OS')
  907. oldcwd = os.getcwd()
  908. os.chdir(dvar)
  909. # We default to '.debug' style
  910. if d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-file-directory':
  911. # Single debug-file-directory style debug info
  912. debugappend = ".debug"
  913. debugstaticappend = ""
  914. debugdir = ""
  915. debugstaticdir = ""
  916. debuglibdir = "/usr/lib/debug"
  917. debugstaticlibdir = "/usr/lib/debug-static"
  918. debugsrcdir = "/usr/src/debug"
  919. elif d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-without-src':
  920. # Original OE-core, a.k.a. ".debug", style debug info, but without sources in /usr/src/debug
  921. debugappend = ""
  922. debugstaticappend = ""
  923. debugdir = "/.debug"
  924. debugstaticdir = "/.debug-static"
  925. debuglibdir = ""
  926. debugstaticlibdir = ""
  927. debugsrcdir = ""
  928. elif d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-with-srcpkg':
  929. debugappend = ""
  930. debugstaticappend = ""
  931. debugdir = "/.debug"
  932. debugstaticdir = "/.debug-static"
  933. debuglibdir = ""
  934. debugstaticlibdir = ""
  935. debugsrcdir = "/usr/src/debug"
  936. else:
  937. # Original OE-core, a.k.a. ".debug", style debug info
  938. debugappend = ""
  939. debugstaticappend = ""
  940. debugdir = "/.debug"
  941. debugstaticdir = "/.debug-static"
  942. debuglibdir = ""
  943. debugstaticlibdir = ""
  944. debugsrcdir = "/usr/src/debug"
  945. #
  946. # First lets figure out all of the files we may have to process ... do this only once!
  947. #
  948. elffiles = {}
  949. symlinks = {}
  950. kernmods = []
  951. staticlibs = []
  952. inodes = {}
  953. libdir = os.path.abspath(dvar + os.sep + d.getVar("libdir"))
  954. baselibdir = os.path.abspath(dvar + os.sep + d.getVar("base_libdir"))
  955. skipfiles = (d.getVar("INHIBIT_PACKAGE_STRIP_FILES") or "").split()
  956. if (d.getVar('INHIBIT_PACKAGE_STRIP') != '1' or \
  957. d.getVar('INHIBIT_PACKAGE_DEBUG_SPLIT') != '1'):
  958. checkelf = {}
  959. checkelflinks = {}
  960. for root, dirs, files in cpath.walk(dvar):
  961. for f in files:
  962. file = os.path.join(root, f)
  963. # Skip debug files
  964. if debugappend and file.endswith(debugappend):
  965. continue
  966. if debugdir and debugdir in os.path.dirname(file[len(dvar):]):
  967. continue
  968. if file in skipfiles:
  969. continue
  970. if file.endswith(".ko") and file.find("/lib/modules/") != -1:
  971. kernmods.append(file)
  972. continue
  973. if oe.package.is_static_lib(file):
  974. staticlibs.append(file)
  975. continue
  976. try:
  977. ltarget = cpath.realpath(file, dvar, False)
  978. s = cpath.lstat(ltarget)
  979. except OSError as e:
  980. (err, strerror) = e.args
  981. if err != errno.ENOENT:
  982. raise
  983. # Skip broken symlinks
  984. continue
  985. if not s:
  986. continue
  987. # Check its an executable
  988. if (s[stat.ST_MODE] & stat.S_IXUSR) or (s[stat.ST_MODE] & stat.S_IXGRP) or (s[stat.ST_MODE] & stat.S_IXOTH) \
  989. or ((file.startswith(libdir) or file.startswith(baselibdir)) and (".so" in f or ".node" in f)):
  990. if cpath.islink(file):
  991. checkelflinks[file] = ltarget
  992. continue
  993. # Use a reference of device ID and inode number to identify files
  994. file_reference = "%d_%d" % (s.st_dev, s.st_ino)
  995. checkelf[file] = (file, file_reference)
  996. results = oe.utils.multiprocess_launch(oe.package.is_elf, checkelflinks.values(), d)
  997. results_map = {}
  998. for (ltarget, elf_file) in results:
  999. results_map[ltarget] = elf_file
  1000. for file in checkelflinks:
  1001. ltarget = checkelflinks[file]
  1002. # If it's a symlink, and points to an ELF file, we capture the readlink target
  1003. if results_map[ltarget]:
  1004. target = os.readlink(file)
  1005. #bb.note("Sym: %s (%d)" % (ltarget, results_map[ltarget]))
  1006. symlinks[file] = target
  1007. results = oe.utils.multiprocess_launch(oe.package.is_elf, checkelf.keys(), d)
  1008. # Sort results by file path. This ensures that the files are always
  1009. # processed in the same order, which is important to make sure builds
  1010. # are reproducible when dealing with hardlinks
  1011. results.sort(key=lambda x: x[0])
  1012. for (file, elf_file) in results:
  1013. # It's a file (or hardlink), not a link
  1014. # ...but is it ELF, and is it already stripped?
  1015. if elf_file & 1:
  1016. if elf_file & 2:
  1017. if 'already-stripped' in (d.getVar('INSANE_SKIP_' + pn) or "").split():
  1018. bb.note("Skipping file %s from %s for already-stripped QA test" % (file[len(dvar):], pn))
  1019. else:
  1020. msg = "File '%s' from %s was already stripped, this will prevent future debugging!" % (file[len(dvar):], pn)
  1021. package_qa_handle_error("already-stripped", msg, d)
  1022. continue
  1023. # At this point we have an unstripped elf file. We need to:
  1024. # a) Make sure any file we strip is not hardlinked to anything else outside this tree
  1025. # b) Only strip any hardlinked file once (no races)
  1026. # c) Track any hardlinks between files so that we can reconstruct matching debug file hardlinks
  1027. # Use a reference of device ID and inode number to identify files
  1028. file_reference = checkelf[file][1]
  1029. if file_reference in inodes:
  1030. os.unlink(file)
  1031. os.link(inodes[file_reference][0], file)
  1032. inodes[file_reference].append(file)
  1033. else:
  1034. inodes[file_reference] = [file]
  1035. # break hardlink
  1036. bb.utils.break_hardlinks(file)
  1037. elffiles[file] = elf_file
  1038. # Modified the file so clear the cache
  1039. cpath.updatecache(file)
  1040. #
  1041. # First lets process debug splitting
  1042. #
  1043. if (d.getVar('INHIBIT_PACKAGE_DEBUG_SPLIT') != '1'):
  1044. results = oe.utils.multiprocess_launch(splitdebuginfo, list(elffiles), d, extraargs=(dvar, debugdir, debuglibdir, debugappend, debugsrcdir, d))
  1045. if debugsrcdir and not hostos.startswith("mingw"):
  1046. if (d.getVar('PACKAGE_DEBUG_STATIC_SPLIT') == '1'):
  1047. results = oe.utils.multiprocess_launch(splitstaticdebuginfo, staticlibs, d, extraargs=(dvar, debugstaticdir, debugstaticlibdir, debugstaticappend, debugsrcdir, d))
  1048. else:
  1049. for file in staticlibs:
  1050. results.append( (file,source_info(file, d)) )
  1051. sources = set()
  1052. for r in results:
  1053. sources.update(r[1])
  1054. # Hardlink our debug symbols to the other hardlink copies
  1055. for ref in inodes:
  1056. if len(inodes[ref]) == 1:
  1057. continue
  1058. target = inodes[ref][0][len(dvar):]
  1059. for file in inodes[ref][1:]:
  1060. src = file[len(dvar):]
  1061. dest = debuglibdir + os.path.dirname(src) + debugdir + "/" + os.path.basename(target) + debugappend
  1062. fpath = dvar + dest
  1063. ftarget = dvar + debuglibdir + os.path.dirname(target) + debugdir + "/" + os.path.basename(target) + debugappend
  1064. bb.utils.mkdirhier(os.path.dirname(fpath))
  1065. # Only one hardlink of separated debug info file in each directory
  1066. if not os.access(fpath, os.R_OK):
  1067. #bb.note("Link %s -> %s" % (fpath, ftarget))
  1068. os.link(ftarget, fpath)
  1069. # Create symlinks for all cases we were able to split symbols
  1070. for file in symlinks:
  1071. src = file[len(dvar):]
  1072. dest = debuglibdir + os.path.dirname(src) + debugdir + "/" + os.path.basename(src) + debugappend
  1073. fpath = dvar + dest
  1074. # Skip it if the target doesn't exist
  1075. try:
  1076. s = os.stat(fpath)
  1077. except OSError as e:
  1078. (err, strerror) = e.args
  1079. if err != errno.ENOENT:
  1080. raise
  1081. continue
  1082. ltarget = symlinks[file]
  1083. lpath = os.path.dirname(ltarget)
  1084. lbase = os.path.basename(ltarget)
  1085. ftarget = ""
  1086. if lpath and lpath != ".":
  1087. ftarget += lpath + debugdir + "/"
  1088. ftarget += lbase + debugappend
  1089. if lpath.startswith(".."):
  1090. ftarget = os.path.join("..", ftarget)
  1091. bb.utils.mkdirhier(os.path.dirname(fpath))
  1092. #bb.note("Symlink %s -> %s" % (fpath, ftarget))
  1093. os.symlink(ftarget, fpath)
  1094. # Process the debugsrcdir if requested...
  1095. # This copies and places the referenced sources for later debugging...
  1096. copydebugsources(debugsrcdir, sources, d)
  1097. #
  1098. # End of debug splitting
  1099. #
  1100. #
  1101. # Now lets go back over things and strip them
  1102. #
  1103. if (d.getVar('INHIBIT_PACKAGE_STRIP') != '1'):
  1104. strip = d.getVar("STRIP")
  1105. sfiles = []
  1106. for file in elffiles:
  1107. elf_file = int(elffiles[file])
  1108. #bb.note("Strip %s" % file)
  1109. sfiles.append((file, elf_file, strip))
  1110. for f in kernmods:
  1111. sfiles.append((f, 16, strip))
  1112. if (d.getVar('PACKAGE_STRIP_STATIC') == '1' or d.getVar('PACKAGE_DEBUG_STATIC_SPLIT') == '1'):
  1113. for f in staticlibs:
  1114. sfiles.append((f, 16, strip))
  1115. oe.utils.multiprocess_launch(oe.package.runstrip, sfiles, d)
  1116. # Build "minidebuginfo" and reinject it back into the stripped binaries
  1117. if d.getVar('PACKAGE_MINIDEBUGINFO') == '1':
  1118. oe.utils.multiprocess_launch(inject_minidebuginfo, list(elffiles), d,
  1119. extraargs=(dvar, debugdir, debuglibdir, debugappend, debugsrcdir, d))
  1120. #
  1121. # End of strip
  1122. #
  1123. os.chdir(oldcwd)
  1124. }
  1125. python populate_packages () {
  1126. import glob, re
  1127. workdir = d.getVar('WORKDIR')
  1128. outdir = d.getVar('DEPLOY_DIR')
  1129. dvar = d.getVar('PKGD')
  1130. packages = d.getVar('PACKAGES').split()
  1131. pn = d.getVar('PN')
  1132. bb.utils.mkdirhier(outdir)
  1133. os.chdir(dvar)
  1134. autodebug = not (d.getVar("NOAUTOPACKAGEDEBUG") or False)
  1135. split_source_package = (d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-with-srcpkg')
  1136. # If debug-with-srcpkg mode is enabled then add the source package if it
  1137. # doesn't exist and add the source file contents to the source package.
  1138. if split_source_package:
  1139. src_package_name = ('%s-src' % d.getVar('PN'))
  1140. if not src_package_name in packages:
  1141. packages.append(src_package_name)
  1142. d.setVar('FILES_%s' % src_package_name, '/usr/src/debug')
  1143. # Sanity check PACKAGES for duplicates
  1144. # Sanity should be moved to sanity.bbclass once we have the infrastructure
  1145. package_dict = {}
  1146. for i, pkg in enumerate(packages):
  1147. if pkg in package_dict:
  1148. msg = "%s is listed in PACKAGES multiple times, this leads to packaging errors." % pkg
  1149. package_qa_handle_error("packages-list", msg, d)
  1150. # Ensure the source package gets the chance to pick up the source files
  1151. # before the debug package by ordering it first in PACKAGES. Whether it
  1152. # actually picks up any source files is controlled by
  1153. # PACKAGE_DEBUG_SPLIT_STYLE.
  1154. elif pkg.endswith("-src"):
  1155. package_dict[pkg] = (10, i)
  1156. elif autodebug and pkg.endswith("-dbg"):
  1157. package_dict[pkg] = (30, i)
  1158. else:
  1159. package_dict[pkg] = (50, i)
  1160. packages = sorted(package_dict.keys(), key=package_dict.get)
  1161. d.setVar('PACKAGES', ' '.join(packages))
  1162. pkgdest = d.getVar('PKGDEST')
  1163. seen = []
  1164. # os.mkdir masks the permissions with umask so we have to unset it first
  1165. oldumask = os.umask(0)
  1166. debug = []
  1167. for root, dirs, files in cpath.walk(dvar):
  1168. dir = root[len(dvar):]
  1169. if not dir:
  1170. dir = os.sep
  1171. for f in (files + dirs):
  1172. path = "." + os.path.join(dir, f)
  1173. if "/.debug/" in path or "/.debug-static/" in path or path.endswith("/.debug"):
  1174. debug.append(path)
  1175. for pkg in packages:
  1176. root = os.path.join(pkgdest, pkg)
  1177. bb.utils.mkdirhier(root)
  1178. filesvar = d.getVar('FILES_%s' % pkg) or ""
  1179. if "//" in filesvar:
  1180. msg = "FILES variable for package %s contains '//' which is invalid. Attempting to fix this but you should correct the metadata.\n" % pkg
  1181. package_qa_handle_error("files-invalid", msg, d)
  1182. filesvar.replace("//", "/")
  1183. origfiles = filesvar.split()
  1184. files, symlink_paths = files_from_filevars(origfiles)
  1185. if autodebug and pkg.endswith("-dbg"):
  1186. files.extend(debug)
  1187. for file in files:
  1188. if (not cpath.islink(file)) and (not cpath.exists(file)):
  1189. continue
  1190. if file in seen:
  1191. continue
  1192. seen.append(file)
  1193. def mkdir(src, dest, p):
  1194. src = os.path.join(src, p)
  1195. dest = os.path.join(dest, p)
  1196. fstat = cpath.stat(src)
  1197. os.mkdir(dest)
  1198. os.chmod(dest, fstat.st_mode)
  1199. os.chown(dest, fstat.st_uid, fstat.st_gid)
  1200. if p not in seen:
  1201. seen.append(p)
  1202. cpath.updatecache(dest)
  1203. def mkdir_recurse(src, dest, paths):
  1204. if cpath.exists(dest + '/' + paths):
  1205. return
  1206. while paths.startswith("./"):
  1207. paths = paths[2:]
  1208. p = "."
  1209. for c in paths.split("/"):
  1210. p = os.path.join(p, c)
  1211. if not cpath.exists(os.path.join(dest, p)):
  1212. mkdir(src, dest, p)
  1213. if cpath.isdir(file) and not cpath.islink(file):
  1214. mkdir_recurse(dvar, root, file)
  1215. continue
  1216. mkdir_recurse(dvar, root, os.path.dirname(file))
  1217. fpath = os.path.join(root,file)
  1218. if not cpath.islink(file):
  1219. if not os.path.exists(fpath):
  1220. os.link(file, fpath)
  1221. continue
  1222. ret = bb.utils.copyfile(file, fpath)
  1223. if ret is False or ret == 0:
  1224. bb.fatal("File population failed")
  1225. # Check if symlink paths exist
  1226. for file in symlink_paths:
  1227. if not os.path.exists(os.path.join(root,file)):
  1228. bb.fatal("File '%s' cannot be packaged into '%s' because its "
  1229. "parent directory structure does not exist. One of "
  1230. "its parent directories is a symlink whose target "
  1231. "directory is not included in the package." %
  1232. (file, pkg))
  1233. os.umask(oldumask)
  1234. os.chdir(workdir)
  1235. # Handle LICENSE_EXCLUSION
  1236. package_list = []
  1237. for pkg in packages:
  1238. licenses = d.getVar('LICENSE_EXCLUSION-' + pkg)
  1239. if licenses:
  1240. msg = "Excluding %s from packaging as it has incompatible license(s): %s" % (pkg, licenses)
  1241. package_qa_handle_error("incompatible-license", msg, d)
  1242. else:
  1243. package_list.append(pkg)
  1244. d.setVar('PACKAGES', ' '.join(package_list))
  1245. unshipped = []
  1246. for root, dirs, files in cpath.walk(dvar):
  1247. dir = root[len(dvar):]
  1248. if not dir:
  1249. dir = os.sep
  1250. for f in (files + dirs):
  1251. path = os.path.join(dir, f)
  1252. if ('.' + path) not in seen:
  1253. unshipped.append(path)
  1254. if unshipped != []:
  1255. msg = pn + ": Files/directories were installed but not shipped in any package:"
  1256. if "installed-vs-shipped" in (d.getVar('INSANE_SKIP_' + pn) or "").split():
  1257. bb.note("Package %s skipping QA tests: installed-vs-shipped" % pn)
  1258. else:
  1259. for f in unshipped:
  1260. msg = msg + "\n " + f
  1261. msg = msg + "\nPlease set FILES such that these items are packaged. Alternatively if they are unneeded, avoid installing them or delete them within do_install.\n"
  1262. msg = msg + "%s: %d installed and not shipped files." % (pn, len(unshipped))
  1263. package_qa_handle_error("installed-vs-shipped", msg, d)
  1264. }
  1265. populate_packages[dirs] = "${D}"
  1266. python package_fixsymlinks () {
  1267. import errno
  1268. pkgdest = d.getVar('PKGDEST')
  1269. packages = d.getVar("PACKAGES", False).split()
  1270. dangling_links = {}
  1271. pkg_files = {}
  1272. for pkg in packages:
  1273. dangling_links[pkg] = []
  1274. pkg_files[pkg] = []
  1275. inst_root = os.path.join(pkgdest, pkg)
  1276. for path in pkgfiles[pkg]:
  1277. rpath = path[len(inst_root):]
  1278. pkg_files[pkg].append(rpath)
  1279. rtarget = cpath.realpath(path, inst_root, True, assume_dir = True)
  1280. if not cpath.lexists(rtarget):
  1281. dangling_links[pkg].append(os.path.normpath(rtarget[len(inst_root):]))
  1282. newrdepends = {}
  1283. for pkg in dangling_links:
  1284. for l in dangling_links[pkg]:
  1285. found = False
  1286. bb.debug(1, "%s contains dangling link %s" % (pkg, l))
  1287. for p in packages:
  1288. if l in pkg_files[p]:
  1289. found = True
  1290. bb.debug(1, "target found in %s" % p)
  1291. if p == pkg:
  1292. break
  1293. if pkg not in newrdepends:
  1294. newrdepends[pkg] = []
  1295. newrdepends[pkg].append(p)
  1296. break
  1297. if found == False:
  1298. bb.note("%s contains dangling symlink to %s" % (pkg, l))
  1299. for pkg in newrdepends:
  1300. rdepends = bb.utils.explode_dep_versions2(d.getVar('RDEPENDS_' + pkg) or "")
  1301. for p in newrdepends[pkg]:
  1302. if p not in rdepends:
  1303. rdepends[p] = []
  1304. d.setVar('RDEPENDS_' + pkg, bb.utils.join_deps(rdepends, commasep=False))
  1305. }
  1306. python package_package_name_hook() {
  1307. """
  1308. A package_name_hook function can be used to rewrite the package names by
  1309. changing PKG. For an example, see debian.bbclass.
  1310. """
  1311. pass
  1312. }
  1313. EXPORT_FUNCTIONS package_name_hook
  1314. PKGDESTWORK = "${WORKDIR}/pkgdata"
  1315. PKGDATA_VARS = "PN PE PV PR PKGE PKGV PKGR LICENSE DESCRIPTION SUMMARY RDEPENDS RPROVIDES RRECOMMENDS RSUGGESTS RREPLACES RCONFLICTS SECTION PKG ALLOW_EMPTY FILES CONFFILES FILES_INFO PACKAGE_ADD_METADATA pkg_postinst pkg_postrm pkg_preinst pkg_prerm"
  1316. python emit_pkgdata() {
  1317. from glob import glob
  1318. import json
  1319. def process_postinst_on_target(pkg, mlprefix):
  1320. pkgval = d.getVar('PKG_%s' % pkg)
  1321. if pkgval is None:
  1322. pkgval = pkg
  1323. defer_fragment = """
  1324. if [ -n "$D" ]; then
  1325. $INTERCEPT_DIR/postinst_intercept delay_to_first_boot %s mlprefix=%s
  1326. exit 0
  1327. fi
  1328. """ % (pkgval, mlprefix)
  1329. postinst = d.getVar('pkg_postinst_%s' % pkg)
  1330. postinst_ontarget = d.getVar('pkg_postinst_ontarget_%s' % pkg)
  1331. if postinst_ontarget:
  1332. bb.debug(1, 'adding deferred pkg_postinst_ontarget() to pkg_postinst() for %s' % pkg)
  1333. if not postinst:
  1334. postinst = '#!/bin/sh\n'
  1335. postinst += defer_fragment
  1336. postinst += postinst_ontarget
  1337. d.setVar('pkg_postinst_%s' % pkg, postinst)
  1338. def add_set_e_to_scriptlets(pkg):
  1339. for scriptlet_name in ('pkg_preinst', 'pkg_postinst', 'pkg_prerm', 'pkg_postrm'):
  1340. scriptlet = d.getVar('%s_%s' % (scriptlet_name, pkg))
  1341. if scriptlet:
  1342. scriptlet_split = scriptlet.split('\n')
  1343. if scriptlet_split[0].startswith("#!"):
  1344. scriptlet = scriptlet_split[0] + "\nset -e\n" + "\n".join(scriptlet_split[1:])
  1345. else:
  1346. scriptlet = "set -e\n" + "\n".join(scriptlet_split[0:])
  1347. d.setVar('%s_%s' % (scriptlet_name, pkg), scriptlet)
  1348. def write_if_exists(f, pkg, var):
  1349. def encode(str):
  1350. import codecs
  1351. c = codecs.getencoder("unicode_escape")
  1352. return c(str)[0].decode("latin1")
  1353. val = d.getVar('%s_%s' % (var, pkg))
  1354. if val:
  1355. f.write('%s_%s: %s\n' % (var, pkg, encode(val)))
  1356. return val
  1357. val = d.getVar('%s' % (var))
  1358. if val:
  1359. f.write('%s: %s\n' % (var, encode(val)))
  1360. return val
  1361. def write_extra_pkgs(variants, pn, packages, pkgdatadir):
  1362. for variant in variants:
  1363. with open("%s/%s-%s" % (pkgdatadir, variant, pn), 'w') as fd:
  1364. fd.write("PACKAGES: %s\n" % ' '.join(
  1365. map(lambda pkg: '%s-%s' % (variant, pkg), packages.split())))
  1366. def write_extra_runtime_pkgs(variants, packages, pkgdatadir):
  1367. for variant in variants:
  1368. for pkg in packages.split():
  1369. ml_pkg = "%s-%s" % (variant, pkg)
  1370. subdata_file = "%s/runtime/%s" % (pkgdatadir, ml_pkg)
  1371. with open(subdata_file, 'w') as fd:
  1372. fd.write("PKG_%s: %s" % (ml_pkg, pkg))
  1373. packages = d.getVar('PACKAGES')
  1374. pkgdest = d.getVar('PKGDEST')
  1375. pkgdatadir = d.getVar('PKGDESTWORK')
  1376. data_file = pkgdatadir + d.expand("/${PN}")
  1377. with open(data_file, 'w') as fd:
  1378. fd.write("PACKAGES: %s\n" % packages)
  1379. pn = d.getVar('PN')
  1380. global_variants = (d.getVar('MULTILIB_GLOBAL_VARIANTS') or "").split()
  1381. variants = (d.getVar('MULTILIB_VARIANTS') or "").split()
  1382. if bb.data.inherits_class('kernel', d) or bb.data.inherits_class('module-base', d):
  1383. write_extra_pkgs(variants, pn, packages, pkgdatadir)
  1384. if bb.data.inherits_class('allarch', d) and not variants \
  1385. and not bb.data.inherits_class('packagegroup', d):
  1386. write_extra_pkgs(global_variants, pn, packages, pkgdatadir)
  1387. workdir = d.getVar('WORKDIR')
  1388. for pkg in packages.split():
  1389. pkgval = d.getVar('PKG_%s' % pkg)
  1390. if pkgval is None:
  1391. pkgval = pkg
  1392. d.setVar('PKG_%s' % pkg, pkg)
  1393. pkgdestpkg = os.path.join(pkgdest, pkg)
  1394. files = {}
  1395. total_size = 0
  1396. seen = set()
  1397. for f in pkgfiles[pkg]:
  1398. relpth = os.path.relpath(f, pkgdestpkg)
  1399. fstat = os.lstat(f)
  1400. files[os.sep + relpth] = fstat.st_size
  1401. if fstat.st_ino not in seen:
  1402. seen.add(fstat.st_ino)
  1403. total_size += fstat.st_size
  1404. d.setVar('FILES_INFO', json.dumps(files, sort_keys=True))
  1405. process_postinst_on_target(pkg, d.getVar("MLPREFIX"))
  1406. add_set_e_to_scriptlets(pkg)
  1407. subdata_file = pkgdatadir + "/runtime/%s" % pkg
  1408. with open(subdata_file, 'w') as sf:
  1409. for var in (d.getVar('PKGDATA_VARS') or "").split():
  1410. val = write_if_exists(sf, pkg, var)
  1411. write_if_exists(sf, pkg, 'FILERPROVIDESFLIST')
  1412. for dfile in (d.getVar('FILERPROVIDESFLIST_' + pkg) or "").split():
  1413. write_if_exists(sf, pkg, 'FILERPROVIDES_' + dfile)
  1414. write_if_exists(sf, pkg, 'FILERDEPENDSFLIST')
  1415. for dfile in (d.getVar('FILERDEPENDSFLIST_' + pkg) or "").split():
  1416. write_if_exists(sf, pkg, 'FILERDEPENDS_' + dfile)
  1417. sf.write('%s_%s: %d\n' % ('PKGSIZE', pkg, total_size))
  1418. # Symlinks needed for rprovides lookup
  1419. rprov = d.getVar('RPROVIDES_%s' % pkg) or d.getVar('RPROVIDES')
  1420. if rprov:
  1421. for p in bb.utils.explode_deps(rprov):
  1422. subdata_sym = pkgdatadir + "/runtime-rprovides/%s/%s" % (p, pkg)
  1423. bb.utils.mkdirhier(os.path.dirname(subdata_sym))
  1424. oe.path.symlink("../../runtime/%s" % pkg, subdata_sym, True)
  1425. allow_empty = d.getVar('ALLOW_EMPTY_%s' % pkg)
  1426. if not allow_empty:
  1427. allow_empty = d.getVar('ALLOW_EMPTY')
  1428. root = "%s/%s" % (pkgdest, pkg)
  1429. os.chdir(root)
  1430. g = glob('*')
  1431. if g or allow_empty == "1":
  1432. # Symlinks needed for reverse lookups (from the final package name)
  1433. subdata_sym = pkgdatadir + "/runtime-reverse/%s" % pkgval
  1434. oe.path.symlink("../runtime/%s" % pkg, subdata_sym, True)
  1435. packagedfile = pkgdatadir + '/runtime/%s.packaged' % pkg
  1436. open(packagedfile, 'w').close()
  1437. if bb.data.inherits_class('kernel', d) or bb.data.inherits_class('module-base', d):
  1438. write_extra_runtime_pkgs(variants, packages, pkgdatadir)
  1439. if bb.data.inherits_class('allarch', d) and not variants \
  1440. and not bb.data.inherits_class('packagegroup', d):
  1441. write_extra_runtime_pkgs(global_variants, packages, pkgdatadir)
  1442. }
  1443. emit_pkgdata[dirs] = "${PKGDESTWORK}/runtime ${PKGDESTWORK}/runtime-reverse ${PKGDESTWORK}/runtime-rprovides"
  1444. ldconfig_postinst_fragment() {
  1445. if [ x"$D" = "x" ]; then
  1446. if [ -x /sbin/ldconfig ]; then /sbin/ldconfig ; fi
  1447. fi
  1448. }
  1449. RPMDEPS = "${STAGING_LIBDIR_NATIVE}/rpm/rpmdeps --alldeps"
  1450. # Collect perfile run-time dependency metadata
  1451. # Output:
  1452. # FILERPROVIDESFLIST_pkg - list of all files w/ deps
  1453. # FILERPROVIDES_filepath_pkg - per file dep
  1454. #
  1455. # FILERDEPENDSFLIST_pkg - list of all files w/ deps
  1456. # FILERDEPENDS_filepath_pkg - per file dep
  1457. python package_do_filedeps() {
  1458. if d.getVar('SKIP_FILEDEPS') == '1':
  1459. return
  1460. pkgdest = d.getVar('PKGDEST')
  1461. packages = d.getVar('PACKAGES')
  1462. rpmdeps = d.getVar('RPMDEPS')
  1463. def chunks(files, n):
  1464. return [files[i:i+n] for i in range(0, len(files), n)]
  1465. pkglist = []
  1466. for pkg in packages.split():
  1467. if d.getVar('SKIP_FILEDEPS_' + pkg) == '1':
  1468. continue
  1469. if pkg.endswith('-dbg') or pkg.endswith('-doc') or pkg.find('-locale-') != -1 or pkg.find('-localedata-') != -1 or pkg.find('-gconv-') != -1 or pkg.find('-charmap-') != -1 or pkg.startswith('kernel-module-') or pkg.endswith('-src'):
  1470. continue
  1471. for files in chunks(pkgfiles[pkg], 100):
  1472. pkglist.append((pkg, files, rpmdeps, pkgdest))
  1473. processed = oe.utils.multiprocess_launch(oe.package.filedeprunner, pkglist, d)
  1474. provides_files = {}
  1475. requires_files = {}
  1476. for result in processed:
  1477. (pkg, provides, requires) = result
  1478. if pkg not in provides_files:
  1479. provides_files[pkg] = []
  1480. if pkg not in requires_files:
  1481. requires_files[pkg] = []
  1482. for file in sorted(provides):
  1483. provides_files[pkg].append(file)
  1484. key = "FILERPROVIDES_" + file + "_" + pkg
  1485. d.appendVar(key, " " + " ".join(provides[file]))
  1486. for file in sorted(requires):
  1487. requires_files[pkg].append(file)
  1488. key = "FILERDEPENDS_" + file + "_" + pkg
  1489. d.appendVar(key, " " + " ".join(requires[file]))
  1490. for pkg in requires_files:
  1491. d.setVar("FILERDEPENDSFLIST_" + pkg, " ".join(requires_files[pkg]))
  1492. for pkg in provides_files:
  1493. d.setVar("FILERPROVIDESFLIST_" + pkg, " ".join(provides_files[pkg]))
  1494. }
  1495. SHLIBSDIRS = "${WORKDIR_PKGDATA}/${MLPREFIX}shlibs2"
  1496. SHLIBSWORKDIR = "${PKGDESTWORK}/${MLPREFIX}shlibs2"
  1497. python package_do_shlibs() {
  1498. import itertools
  1499. import re, pipes
  1500. import subprocess
  1501. exclude_shlibs = d.getVar('EXCLUDE_FROM_SHLIBS', False)
  1502. if exclude_shlibs:
  1503. bb.note("not generating shlibs")
  1504. return
  1505. lib_re = re.compile(r"^.*\.so")
  1506. libdir_re = re.compile(r".*/%s$" % d.getVar('baselib'))
  1507. packages = d.getVar('PACKAGES')
  1508. shlib_pkgs = []
  1509. exclusion_list = d.getVar("EXCLUDE_PACKAGES_FROM_SHLIBS")
  1510. if exclusion_list:
  1511. for pkg in packages.split():
  1512. if pkg not in exclusion_list.split():
  1513. shlib_pkgs.append(pkg)
  1514. else:
  1515. bb.note("not generating shlibs for %s" % pkg)
  1516. else:
  1517. shlib_pkgs = packages.split()
  1518. hostos = d.getVar('HOST_OS')
  1519. workdir = d.getVar('WORKDIR')
  1520. ver = d.getVar('PKGV')
  1521. if not ver:
  1522. msg = "PKGV not defined"
  1523. package_qa_handle_error("pkgv-undefined", msg, d)
  1524. return
  1525. pkgdest = d.getVar('PKGDEST')
  1526. shlibswork_dir = d.getVar('SHLIBSWORKDIR')
  1527. def linux_so(file, pkg, pkgver, d):
  1528. needs_ldconfig = False
  1529. needed = set()
  1530. sonames = set()
  1531. renames = []
  1532. ldir = os.path.dirname(file).replace(pkgdest + "/" + pkg, '')
  1533. cmd = d.getVar('OBJDUMP') + " -p " + pipes.quote(file) + " 2>/dev/null"
  1534. fd = os.popen(cmd)
  1535. lines = fd.readlines()
  1536. fd.close()
  1537. rpath = tuple()
  1538. for l in lines:
  1539. m = re.match(r"\s+RPATH\s+([^\s]*)", l)
  1540. if m:
  1541. rpaths = m.group(1).replace("$ORIGIN", ldir).split(":")
  1542. rpath = tuple(map(os.path.normpath, rpaths))
  1543. for l in lines:
  1544. m = re.match(r"\s+NEEDED\s+([^\s]*)", l)
  1545. if m:
  1546. dep = m.group(1)
  1547. if dep not in needed:
  1548. needed.add((dep, file, rpath))
  1549. m = re.match(r"\s+SONAME\s+([^\s]*)", l)
  1550. if m:
  1551. this_soname = m.group(1)
  1552. prov = (this_soname, ldir, pkgver)
  1553. if not prov in sonames:
  1554. # if library is private (only used by package) then do not build shlib for it
  1555. import fnmatch
  1556. if not private_libs or len([i for i in private_libs if fnmatch.fnmatch(this_soname, i)]) == 0:
  1557. sonames.add(prov)
  1558. if libdir_re.match(os.path.dirname(file)):
  1559. needs_ldconfig = True
  1560. if snap_symlinks and (os.path.basename(file) != this_soname):
  1561. renames.append((file, os.path.join(os.path.dirname(file), this_soname)))
  1562. return (needs_ldconfig, needed, sonames, renames)
  1563. def darwin_so(file, needed, sonames, renames, pkgver):
  1564. if not os.path.exists(file):
  1565. return
  1566. ldir = os.path.dirname(file).replace(pkgdest + "/" + pkg, '')
  1567. def get_combinations(base):
  1568. #
  1569. # Given a base library name, find all combinations of this split by "." and "-"
  1570. #
  1571. combos = []
  1572. options = base.split(".")
  1573. for i in range(1, len(options) + 1):
  1574. combos.append(".".join(options[0:i]))
  1575. options = base.split("-")
  1576. for i in range(1, len(options) + 1):
  1577. combos.append("-".join(options[0:i]))
  1578. return combos
  1579. if (file.endswith('.dylib') or file.endswith('.so')) and not pkg.endswith('-dev') and not pkg.endswith('-dbg') and not pkg.endswith('-src'):
  1580. # Drop suffix
  1581. name = os.path.basename(file).rsplit(".",1)[0]
  1582. # Find all combinations
  1583. combos = get_combinations(name)
  1584. for combo in combos:
  1585. if not combo in sonames:
  1586. prov = (combo, ldir, pkgver)
  1587. sonames.add(prov)
  1588. if file.endswith('.dylib') or file.endswith('.so'):
  1589. rpath = []
  1590. p = subprocess.Popen([d.expand("${HOST_PREFIX}otool"), '-l', file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1591. out, err = p.communicate()
  1592. # If returned successfully, process stdout for results
  1593. if p.returncode == 0:
  1594. for l in out.split("\n"):
  1595. l = l.strip()
  1596. if l.startswith('path '):
  1597. rpath.append(l.split()[1])
  1598. p = subprocess.Popen([d.expand("${HOST_PREFIX}otool"), '-L', file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1599. out, err = p.communicate()
  1600. # If returned successfully, process stdout for results
  1601. if p.returncode == 0:
  1602. for l in out.split("\n"):
  1603. l = l.strip()
  1604. if not l or l.endswith(":"):
  1605. continue
  1606. if "is not an object file" in l:
  1607. continue
  1608. name = os.path.basename(l.split()[0]).rsplit(".", 1)[0]
  1609. if name and name not in needed[pkg]:
  1610. needed[pkg].add((name, file, tuple()))
  1611. def mingw_dll(file, needed, sonames, renames, pkgver):
  1612. if not os.path.exists(file):
  1613. return
  1614. if file.endswith(".dll"):
  1615. # assume all dlls are shared objects provided by the package
  1616. sonames.add((os.path.basename(file), os.path.dirname(file).replace(pkgdest + "/" + pkg, ''), pkgver))
  1617. if (file.endswith(".dll") or file.endswith(".exe")):
  1618. # use objdump to search for "DLL Name: .*\.dll"
  1619. p = subprocess.Popen([d.expand("${HOST_PREFIX}objdump"), "-p", file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1620. out, err = p.communicate()
  1621. # process the output, grabbing all .dll names
  1622. if p.returncode == 0:
  1623. for m in re.finditer(r"DLL Name: (.*?\.dll)$", out.decode(), re.MULTILINE | re.IGNORECASE):
  1624. dllname = m.group(1)
  1625. if dllname:
  1626. needed[pkg].add((dllname, file, tuple()))
  1627. if d.getVar('PACKAGE_SNAP_LIB_SYMLINKS') == "1":
  1628. snap_symlinks = True
  1629. else:
  1630. snap_symlinks = False
  1631. needed = {}
  1632. shlib_provider = oe.package.read_shlib_providers(d)
  1633. for pkg in shlib_pkgs:
  1634. private_libs = d.getVar('PRIVATE_LIBS_' + pkg) or d.getVar('PRIVATE_LIBS') or ""
  1635. private_libs = private_libs.split()
  1636. needs_ldconfig = False
  1637. bb.debug(2, "calculating shlib provides for %s" % pkg)
  1638. pkgver = d.getVar('PKGV_' + pkg)
  1639. if not pkgver:
  1640. pkgver = d.getVar('PV_' + pkg)
  1641. if not pkgver:
  1642. pkgver = ver
  1643. needed[pkg] = set()
  1644. sonames = set()
  1645. renames = []
  1646. linuxlist = []
  1647. for file in pkgfiles[pkg]:
  1648. soname = None
  1649. if cpath.islink(file):
  1650. continue
  1651. if hostos == "darwin" or hostos == "darwin8":
  1652. darwin_so(file, needed, sonames, renames, pkgver)
  1653. elif hostos.startswith("mingw"):
  1654. mingw_dll(file, needed, sonames, renames, pkgver)
  1655. elif os.access(file, os.X_OK) or lib_re.match(file):
  1656. linuxlist.append(file)
  1657. if linuxlist:
  1658. results = oe.utils.multiprocess_launch(linux_so, linuxlist, d, extraargs=(pkg, pkgver, d))
  1659. for r in results:
  1660. ldconfig = r[0]
  1661. needed[pkg] |= r[1]
  1662. sonames |= r[2]
  1663. renames.extend(r[3])
  1664. needs_ldconfig = needs_ldconfig or ldconfig
  1665. for (old, new) in renames:
  1666. bb.note("Renaming %s to %s" % (old, new))
  1667. os.rename(old, new)
  1668. pkgfiles[pkg].remove(old)
  1669. shlibs_file = os.path.join(shlibswork_dir, pkg + ".list")
  1670. if len(sonames):
  1671. with open(shlibs_file, 'w') as fd:
  1672. for s in sorted(sonames):
  1673. if s[0] in shlib_provider and s[1] in shlib_provider[s[0]]:
  1674. (old_pkg, old_pkgver) = shlib_provider[s[0]][s[1]]
  1675. if old_pkg != pkg:
  1676. bb.warn('%s-%s was registered as shlib provider for %s, changing it to %s-%s because it was built later' % (old_pkg, old_pkgver, s[0], pkg, pkgver))
  1677. bb.debug(1, 'registering %s-%s as shlib provider for %s' % (pkg, pkgver, s[0]))
  1678. fd.write(s[0] + ':' + s[1] + ':' + s[2] + '\n')
  1679. if s[0] not in shlib_provider:
  1680. shlib_provider[s[0]] = {}
  1681. shlib_provider[s[0]][s[1]] = (pkg, pkgver)
  1682. if needs_ldconfig:
  1683. bb.debug(1, 'adding ldconfig call to postinst for %s' % pkg)
  1684. postinst = d.getVar('pkg_postinst_%s' % pkg)
  1685. if not postinst:
  1686. postinst = '#!/bin/sh\n'
  1687. postinst += d.getVar('ldconfig_postinst_fragment')
  1688. d.setVar('pkg_postinst_%s' % pkg, postinst)
  1689. bb.debug(1, 'LIBNAMES: pkg %s sonames %s' % (pkg, sonames))
  1690. assumed_libs = d.getVar('ASSUME_SHLIBS')
  1691. if assumed_libs:
  1692. libdir = d.getVar("libdir")
  1693. for e in assumed_libs.split():
  1694. l, dep_pkg = e.split(":")
  1695. lib_ver = None
  1696. dep_pkg = dep_pkg.rsplit("_", 1)
  1697. if len(dep_pkg) == 2:
  1698. lib_ver = dep_pkg[1]
  1699. dep_pkg = dep_pkg[0]
  1700. if l not in shlib_provider:
  1701. shlib_provider[l] = {}
  1702. shlib_provider[l][libdir] = (dep_pkg, lib_ver)
  1703. libsearchpath = [d.getVar('libdir'), d.getVar('base_libdir')]
  1704. for pkg in shlib_pkgs:
  1705. bb.debug(2, "calculating shlib requirements for %s" % pkg)
  1706. private_libs = d.getVar('PRIVATE_LIBS_' + pkg) or d.getVar('PRIVATE_LIBS') or ""
  1707. private_libs = private_libs.split()
  1708. deps = list()
  1709. for n in needed[pkg]:
  1710. # if n is in private libraries, don't try to search provider for it
  1711. # this could cause problem in case some abc.bb provides private
  1712. # /opt/abc/lib/libfoo.so.1 and contains /usr/bin/abc depending on system library libfoo.so.1
  1713. # but skipping it is still better alternative than providing own
  1714. # version and then adding runtime dependency for the same system library
  1715. import fnmatch
  1716. if private_libs and len([i for i in private_libs if fnmatch.fnmatch(n[0], i)]) > 0:
  1717. bb.debug(2, '%s: Dependency %s covered by PRIVATE_LIBS' % (pkg, n[0]))
  1718. continue
  1719. if n[0] in shlib_provider.keys():
  1720. shlib_provider_map = shlib_provider[n[0]]
  1721. matches = set()
  1722. for p in itertools.chain(list(n[2]), sorted(shlib_provider_map.keys()), libsearchpath):
  1723. if p in shlib_provider_map:
  1724. matches.add(p)
  1725. if len(matches) > 1:
  1726. matchpkgs = ', '.join([shlib_provider_map[match][0] for match in matches])
  1727. bb.error("%s: Multiple shlib providers for %s: %s (used by files: %s)" % (pkg, n[0], matchpkgs, n[1]))
  1728. elif len(matches) == 1:
  1729. (dep_pkg, ver_needed) = shlib_provider_map[matches.pop()]
  1730. bb.debug(2, '%s: Dependency %s requires package %s (used by files: %s)' % (pkg, n[0], dep_pkg, n[1]))
  1731. if dep_pkg == pkg:
  1732. continue
  1733. if ver_needed:
  1734. dep = "%s (>= %s)" % (dep_pkg, ver_needed)
  1735. else:
  1736. dep = dep_pkg
  1737. if not dep in deps:
  1738. deps.append(dep)
  1739. continue
  1740. bb.note("Couldn't find shared library provider for %s, used by files: %s" % (n[0], n[1]))
  1741. deps_file = os.path.join(pkgdest, pkg + ".shlibdeps")
  1742. if os.path.exists(deps_file):
  1743. os.remove(deps_file)
  1744. if deps:
  1745. with open(deps_file, 'w') as fd:
  1746. for dep in sorted(deps):
  1747. fd.write(dep + '\n')
  1748. }
  1749. python package_do_pkgconfig () {
  1750. import re
  1751. packages = d.getVar('PACKAGES')
  1752. workdir = d.getVar('WORKDIR')
  1753. pkgdest = d.getVar('PKGDEST')
  1754. shlibs_dirs = d.getVar('SHLIBSDIRS').split()
  1755. shlibswork_dir = d.getVar('SHLIBSWORKDIR')
  1756. pc_re = re.compile(r'(.*)\.pc$')
  1757. var_re = re.compile(r'(.*)=(.*)')
  1758. field_re = re.compile(r'(.*): (.*)')
  1759. pkgconfig_provided = {}
  1760. pkgconfig_needed = {}
  1761. for pkg in packages.split():
  1762. pkgconfig_provided[pkg] = []
  1763. pkgconfig_needed[pkg] = []
  1764. for file in pkgfiles[pkg]:
  1765. m = pc_re.match(file)
  1766. if m:
  1767. pd = bb.data.init()
  1768. name = m.group(1)
  1769. pkgconfig_provided[pkg].append(name)
  1770. if not os.access(file, os.R_OK):
  1771. continue
  1772. with open(file, 'r') as f:
  1773. lines = f.readlines()
  1774. for l in lines:
  1775. m = var_re.match(l)
  1776. if m:
  1777. name = m.group(1)
  1778. val = m.group(2)
  1779. pd.setVar(name, pd.expand(val))
  1780. continue
  1781. m = field_re.match(l)
  1782. if m:
  1783. hdr = m.group(1)
  1784. exp = pd.expand(m.group(2))
  1785. if hdr == 'Requires':
  1786. pkgconfig_needed[pkg] += exp.replace(',', ' ').split()
  1787. for pkg in packages.split():
  1788. pkgs_file = os.path.join(shlibswork_dir, pkg + ".pclist")
  1789. if pkgconfig_provided[pkg] != []:
  1790. with open(pkgs_file, 'w') as f:
  1791. for p in pkgconfig_provided[pkg]:
  1792. f.write('%s\n' % p)
  1793. # Go from least to most specific since the last one found wins
  1794. for dir in reversed(shlibs_dirs):
  1795. if not os.path.exists(dir):
  1796. continue
  1797. for file in sorted(os.listdir(dir)):
  1798. m = re.match(r'^(.*)\.pclist$', file)
  1799. if m:
  1800. pkg = m.group(1)
  1801. with open(os.path.join(dir, file)) as fd:
  1802. lines = fd.readlines()
  1803. pkgconfig_provided[pkg] = []
  1804. for l in lines:
  1805. pkgconfig_provided[pkg].append(l.rstrip())
  1806. for pkg in packages.split():
  1807. deps = []
  1808. for n in pkgconfig_needed[pkg]:
  1809. found = False
  1810. for k in pkgconfig_provided.keys():
  1811. if n in pkgconfig_provided[k]:
  1812. if k != pkg and not (k in deps):
  1813. deps.append(k)
  1814. found = True
  1815. if found == False:
  1816. bb.note("couldn't find pkgconfig module '%s' in any package" % n)
  1817. deps_file = os.path.join(pkgdest, pkg + ".pcdeps")
  1818. if len(deps):
  1819. with open(deps_file, 'w') as fd:
  1820. for dep in deps:
  1821. fd.write(dep + '\n')
  1822. }
  1823. def read_libdep_files(d):
  1824. pkglibdeps = {}
  1825. packages = d.getVar('PACKAGES').split()
  1826. for pkg in packages:
  1827. pkglibdeps[pkg] = {}
  1828. for extension in ".shlibdeps", ".pcdeps", ".clilibdeps":
  1829. depsfile = d.expand("${PKGDEST}/" + pkg + extension)
  1830. if os.access(depsfile, os.R_OK):
  1831. with open(depsfile) as fd:
  1832. lines = fd.readlines()
  1833. for l in lines:
  1834. l.rstrip()
  1835. deps = bb.utils.explode_dep_versions2(l)
  1836. for dep in deps:
  1837. if not dep in pkglibdeps[pkg]:
  1838. pkglibdeps[pkg][dep] = deps[dep]
  1839. return pkglibdeps
  1840. python read_shlibdeps () {
  1841. pkglibdeps = read_libdep_files(d)
  1842. packages = d.getVar('PACKAGES').split()
  1843. for pkg in packages:
  1844. rdepends = bb.utils.explode_dep_versions2(d.getVar('RDEPENDS_' + pkg) or "")
  1845. for dep in sorted(pkglibdeps[pkg]):
  1846. # Add the dep if it's not already there, or if no comparison is set
  1847. if dep not in rdepends:
  1848. rdepends[dep] = []
  1849. for v in pkglibdeps[pkg][dep]:
  1850. if v not in rdepends[dep]:
  1851. rdepends[dep].append(v)
  1852. d.setVar('RDEPENDS_' + pkg, bb.utils.join_deps(rdepends, commasep=False))
  1853. }
  1854. python package_depchains() {
  1855. """
  1856. For a given set of prefix and postfix modifiers, make those packages
  1857. RRECOMMENDS on the corresponding packages for its RDEPENDS.
  1858. Example: If package A depends upon package B, and A's .bb emits an
  1859. A-dev package, this would make A-dev Recommends: B-dev.
  1860. If only one of a given suffix is specified, it will take the RRECOMMENDS
  1861. based on the RDEPENDS of *all* other packages. If more than one of a given
  1862. suffix is specified, its will only use the RDEPENDS of the single parent
  1863. package.
  1864. """
  1865. packages = d.getVar('PACKAGES')
  1866. postfixes = (d.getVar('DEPCHAIN_POST') or '').split()
  1867. prefixes = (d.getVar('DEPCHAIN_PRE') or '').split()
  1868. def pkg_adddeprrecs(pkg, base, suffix, getname, depends, d):
  1869. #bb.note('depends for %s is %s' % (base, depends))
  1870. rreclist = bb.utils.explode_dep_versions2(d.getVar('RRECOMMENDS_' + pkg) or "")
  1871. for depend in sorted(depends):
  1872. if depend.find('-native') != -1 or depend.find('-cross') != -1 or depend.startswith('virtual/'):
  1873. #bb.note("Skipping %s" % depend)
  1874. continue
  1875. if depend.endswith('-dev'):
  1876. depend = depend[:-4]
  1877. if depend.endswith('-dbg'):
  1878. depend = depend[:-4]
  1879. pkgname = getname(depend, suffix)
  1880. #bb.note("Adding %s for %s" % (pkgname, depend))
  1881. if pkgname not in rreclist and pkgname != pkg:
  1882. rreclist[pkgname] = []
  1883. #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
  1884. d.setVar('RRECOMMENDS_%s' % pkg, bb.utils.join_deps(rreclist, commasep=False))
  1885. def pkg_addrrecs(pkg, base, suffix, getname, rdepends, d):
  1886. #bb.note('rdepends for %s is %s' % (base, rdepends))
  1887. rreclist = bb.utils.explode_dep_versions2(d.getVar('RRECOMMENDS_' + pkg) or "")
  1888. for depend in sorted(rdepends):
  1889. if depend.find('virtual-locale-') != -1:
  1890. #bb.note("Skipping %s" % depend)
  1891. continue
  1892. if depend.endswith('-dev'):
  1893. depend = depend[:-4]
  1894. if depend.endswith('-dbg'):
  1895. depend = depend[:-4]
  1896. pkgname = getname(depend, suffix)
  1897. #bb.note("Adding %s for %s" % (pkgname, depend))
  1898. if pkgname not in rreclist and pkgname != pkg:
  1899. rreclist[pkgname] = []
  1900. #bb.note('setting: RRECOMMENDS_%s=%s' % (pkg, ' '.join(rreclist)))
  1901. d.setVar('RRECOMMENDS_%s' % pkg, bb.utils.join_deps(rreclist, commasep=False))
  1902. def add_dep(list, dep):
  1903. if dep not in list:
  1904. list.append(dep)
  1905. depends = []
  1906. for dep in bb.utils.explode_deps(d.getVar('DEPENDS') or ""):
  1907. add_dep(depends, dep)
  1908. rdepends = []
  1909. for pkg in packages.split():
  1910. for dep in bb.utils.explode_deps(d.getVar('RDEPENDS_' + pkg) or ""):
  1911. add_dep(rdepends, dep)
  1912. #bb.note('rdepends is %s' % rdepends)
  1913. def post_getname(name, suffix):
  1914. return '%s%s' % (name, suffix)
  1915. def pre_getname(name, suffix):
  1916. return '%s%s' % (suffix, name)
  1917. pkgs = {}
  1918. for pkg in packages.split():
  1919. for postfix in postfixes:
  1920. if pkg.endswith(postfix):
  1921. if not postfix in pkgs:
  1922. pkgs[postfix] = {}
  1923. pkgs[postfix][pkg] = (pkg[:-len(postfix)], post_getname)
  1924. for prefix in prefixes:
  1925. if pkg.startswith(prefix):
  1926. if not prefix in pkgs:
  1927. pkgs[prefix] = {}
  1928. pkgs[prefix][pkg] = (pkg[:-len(prefix)], pre_getname)
  1929. if "-dbg" in pkgs:
  1930. pkglibdeps = read_libdep_files(d)
  1931. pkglibdeplist = []
  1932. for pkg in pkglibdeps:
  1933. for k in pkglibdeps[pkg]:
  1934. add_dep(pkglibdeplist, k)
  1935. dbgdefaultdeps = ((d.getVar('DEPCHAIN_DBGDEFAULTDEPS') == '1') or (bb.data.inherits_class('packagegroup', d)))
  1936. for suffix in pkgs:
  1937. for pkg in pkgs[suffix]:
  1938. if d.getVarFlag('RRECOMMENDS_' + pkg, 'nodeprrecs'):
  1939. continue
  1940. (base, func) = pkgs[suffix][pkg]
  1941. if suffix == "-dev":
  1942. pkg_adddeprrecs(pkg, base, suffix, func, depends, d)
  1943. elif suffix == "-dbg":
  1944. if not dbgdefaultdeps:
  1945. pkg_addrrecs(pkg, base, suffix, func, pkglibdeplist, d)
  1946. continue
  1947. if len(pkgs[suffix]) == 1:
  1948. pkg_addrrecs(pkg, base, suffix, func, rdepends, d)
  1949. else:
  1950. rdeps = []
  1951. for dep in bb.utils.explode_deps(d.getVar('RDEPENDS_' + base) or ""):
  1952. add_dep(rdeps, dep)
  1953. pkg_addrrecs(pkg, base, suffix, func, rdeps, d)
  1954. }
  1955. # Since bitbake can't determine which variables are accessed during package
  1956. # iteration, we need to list them here:
  1957. PACKAGEVARS = "FILES RDEPENDS RRECOMMENDS SUMMARY DESCRIPTION RSUGGESTS RPROVIDES RCONFLICTS PKG ALLOW_EMPTY pkg_postinst pkg_postrm pkg_postinst_ontarget INITSCRIPT_NAME INITSCRIPT_PARAMS DEBIAN_NOAUTONAME ALTERNATIVE PKGE PKGV PKGR USERADD_PARAM GROUPADD_PARAM CONFFILES SYSTEMD_SERVICE LICENSE SECTION pkg_preinst pkg_prerm RREPLACES GROUPMEMS_PARAM SYSTEMD_AUTO_ENABLE SKIP_FILEDEPS PRIVATE_LIBS PACKAGE_ADD_METADATA"
  1958. def gen_packagevar(d, pkgvars="PACKAGEVARS"):
  1959. ret = []
  1960. pkgs = (d.getVar("PACKAGES") or "").split()
  1961. vars = (d.getVar(pkgvars) or "").split()
  1962. for v in vars:
  1963. ret.append(v)
  1964. for p in pkgs:
  1965. for v in vars:
  1966. ret.append(v + "_" + p)
  1967. # Ensure that changes to INCOMPATIBLE_LICENSE re-run do_package for
  1968. # affected recipes.
  1969. ret.append('LICENSE_EXCLUSION-%s' % p)
  1970. return " ".join(ret)
  1971. PACKAGE_PREPROCESS_FUNCS ?= ""
  1972. # Functions for setting up PKGD
  1973. PACKAGEBUILDPKGD ?= " \
  1974. package_prepare_pkgdata \
  1975. perform_packagecopy \
  1976. ${PACKAGE_PREPROCESS_FUNCS} \
  1977. split_and_strip_files \
  1978. fixup_perms \
  1979. "
  1980. # Functions which split PKGD up into separate packages
  1981. PACKAGESPLITFUNCS ?= " \
  1982. package_do_split_locales \
  1983. populate_packages"
  1984. # Functions which process metadata based on split packages
  1985. PACKAGEFUNCS += " \
  1986. package_fixsymlinks \
  1987. package_name_hook \
  1988. package_do_filedeps \
  1989. package_do_shlibs \
  1990. package_do_pkgconfig \
  1991. read_shlibdeps \
  1992. package_depchains \
  1993. emit_pkgdata"
  1994. python do_package () {
  1995. # Change the following version to cause sstate to invalidate the package
  1996. # cache. This is useful if an item this class depends on changes in a
  1997. # way that the output of this class changes. rpmdeps is a good example
  1998. # as any change to rpmdeps requires this to be rerun.
  1999. # PACKAGE_BBCLASS_VERSION = "2"
  2000. # Init cachedpath
  2001. global cpath
  2002. cpath = oe.cachedpath.CachedPath()
  2003. ###########################################################################
  2004. # Sanity test the setup
  2005. ###########################################################################
  2006. packages = (d.getVar('PACKAGES') or "").split()
  2007. if len(packages) < 1:
  2008. bb.debug(1, "No packages to build, skipping do_package")
  2009. return
  2010. workdir = d.getVar('WORKDIR')
  2011. outdir = d.getVar('DEPLOY_DIR')
  2012. dest = d.getVar('D')
  2013. dvar = d.getVar('PKGD')
  2014. pn = d.getVar('PN')
  2015. if not workdir or not outdir or not dest or not dvar or not pn:
  2016. msg = "WORKDIR, DEPLOY_DIR, D, PN and PKGD all must be defined, unable to package"
  2017. package_qa_handle_error("var-undefined", msg, d)
  2018. return
  2019. bb.build.exec_func("package_convert_pr_autoinc", d)
  2020. ###########################################################################
  2021. # Optimisations
  2022. ###########################################################################
  2023. # Continually expanding complex expressions is inefficient, particularly
  2024. # when we write to the datastore and invalidate the expansion cache. This
  2025. # code pre-expands some frequently used variables
  2026. def expandVar(x, d):
  2027. d.setVar(x, d.getVar(x))
  2028. for x in 'PN', 'PV', 'BPN', 'TARGET_SYS', 'EXTENDPRAUTO':
  2029. expandVar(x, d)
  2030. ###########################################################################
  2031. # Setup PKGD (from D)
  2032. ###########################################################################
  2033. for f in (d.getVar('PACKAGEBUILDPKGD') or '').split():
  2034. bb.build.exec_func(f, d)
  2035. ###########################################################################
  2036. # Split up PKGD into PKGDEST
  2037. ###########################################################################
  2038. cpath = oe.cachedpath.CachedPath()
  2039. for f in (d.getVar('PACKAGESPLITFUNCS') or '').split():
  2040. bb.build.exec_func(f, d)
  2041. ###########################################################################
  2042. # Process PKGDEST
  2043. ###########################################################################
  2044. # Build global list of files in each split package
  2045. global pkgfiles
  2046. pkgfiles = {}
  2047. packages = d.getVar('PACKAGES').split()
  2048. pkgdest = d.getVar('PKGDEST')
  2049. for pkg in packages:
  2050. pkgfiles[pkg] = []
  2051. for walkroot, dirs, files in cpath.walk(pkgdest + "/" + pkg):
  2052. for file in files:
  2053. pkgfiles[pkg].append(walkroot + os.sep + file)
  2054. for f in (d.getVar('PACKAGEFUNCS') or '').split():
  2055. bb.build.exec_func(f, d)
  2056. qa_sane = d.getVar("QA_SANE")
  2057. if not qa_sane:
  2058. bb.fatal("Fatal QA errors found, failing task.")
  2059. }
  2060. do_package[dirs] = "${SHLIBSWORKDIR} ${PKGDESTWORK} ${D}"
  2061. do_package[vardeps] += "${PACKAGEBUILDPKGD} ${PACKAGESPLITFUNCS} ${PACKAGEFUNCS} ${@gen_packagevar(d)}"
  2062. addtask package after do_install
  2063. SSTATETASKS += "do_package"
  2064. do_package[cleandirs] = "${PKGDEST} ${PKGDESTWORK}"
  2065. do_package[sstate-plaindirs] = "${PKGD} ${PKGDEST} ${PKGDESTWORK}"
  2066. do_package_setscene[dirs] = "${STAGING_DIR}"
  2067. python do_package_setscene () {
  2068. sstate_setscene(d)
  2069. }
  2070. addtask do_package_setscene
  2071. # Copy from PKGDESTWORK to tempdirectory as tempdirectory can be cleaned at both
  2072. # do_package_setscene and do_packagedata_setscene leading to races
  2073. python do_packagedata () {
  2074. bb.build.exec_func("package_get_auto_pr", d)
  2075. src = d.expand("${PKGDESTWORK}")
  2076. dest = d.expand("${WORKDIR}/pkgdata-pdata-input")
  2077. oe.path.copyhardlinktree(src, dest)
  2078. bb.build.exec_func("packagedata_translate_pr_autoinc", d)
  2079. }
  2080. # Translate the EXTENDPRAUTO and AUTOINC to the final values
  2081. packagedata_translate_pr_autoinc() {
  2082. find ${WORKDIR}/pkgdata-pdata-input -type f | xargs --no-run-if-empty \
  2083. sed -e 's,@PRSERV_PV_AUTOINC@,${PRSERV_PV_AUTOINC},g' \
  2084. -e 's,@EXTENDPRAUTO@,${EXTENDPRAUTO},g' -i
  2085. }
  2086. addtask packagedata before do_build after do_package
  2087. SSTATETASKS += "do_packagedata"
  2088. do_packagedata[sstate-inputdirs] = "${WORKDIR}/pkgdata-pdata-input"
  2089. do_packagedata[sstate-outputdirs] = "${PKGDATA_DIR}"
  2090. do_packagedata[stamp-extra-info] = "${MACHINE_ARCH}"
  2091. python do_packagedata_setscene () {
  2092. sstate_setscene(d)
  2093. }
  2094. addtask do_packagedata_setscene
  2095. #
  2096. # Helper functions for the package writing classes
  2097. #
  2098. def mapping_rename_hook(d):
  2099. """
  2100. Rewrite variables to account for package renaming in things
  2101. like debian.bbclass or manual PKG variable name changes
  2102. """
  2103. pkg = d.getVar("PKG")
  2104. runtime_mapping_rename("RDEPENDS", pkg, d)
  2105. runtime_mapping_rename("RRECOMMENDS", pkg, d)
  2106. runtime_mapping_rename("RSUGGESTS", pkg, d)