1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7IMAGE_CLASSES ??= ""
8
9# rootfs bootstrap install
10# warning -  image-container resets this
11ROOTFS_BOOTSTRAP_INSTALL = "run-postinsts"
12
13# Handle inherits of any of the image classes we need
14IMGCLASSES = "rootfs_${IMAGE_PKGTYPE} image_types ${IMAGE_CLASSES}"
15# Only Linux SDKs support populate_sdk_ext, fall back to populate_sdk_base
16# in the non-Linux SDK_OS case, such as mingw32
17inherit populate_sdk_base
18IMGCLASSES += "${@['', 'populate_sdk_ext']['linux' in d.getVar("SDK_OS")]}"
19IMGCLASSES += "${@bb.utils.contains_any('IMAGE_FSTYPES', 'live iso hddimg', 'image-live', '', d)}"
20IMGCLASSES += "${@bb.utils.contains('IMAGE_FSTYPES', 'container', 'image-container', '', d)}"
21IMGCLASSES += "image_types_wic"
22IMGCLASSES += "rootfs-postcommands"
23IMGCLASSES += "image-postinst-intercepts"
24IMGCLASSES += "overlayfs-etc"
25inherit_defer ${IMGCLASSES}
26
27TOOLCHAIN_TARGET_TASK += "${PACKAGE_INSTALL}"
28TOOLCHAIN_TARGET_TASK_ATTEMPTONLY += "${PACKAGE_INSTALL_ATTEMPTONLY}"
29POPULATE_SDK_POST_TARGET_COMMAND += "rootfs_sysroot_relativelinks"
30
31LICENSE ?= "MIT"
32PACKAGES = ""
33DEPENDS += "${@' '.join(["%s-qemuwrapper-cross" % m for m in d.getVar("MULTILIB_VARIANTS").split()])} qemuwrapper-cross depmodwrapper-cross cross-localedef-native"
34RDEPENDS += "${PACKAGE_INSTALL} ${LINGUAS_INSTALL} ${IMAGE_INSTALL_DEBUGFS}"
35RRECOMMENDS += "${PACKAGE_INSTALL_ATTEMPTONLY}"
36PATH:prepend = "${@":".join(all_multilib_tune_values(d, 'STAGING_BINDIR_CROSS').split())}:"
37
38INHIBIT_DEFAULT_DEPS = "1"
39
40# IMAGE_FEATURES may contain any available package group
41IMAGE_FEATURES ?= ""
42IMAGE_FEATURES[type] = "list"
43IMAGE_FEATURES[validitems] += "debug-tweaks read-only-rootfs read-only-rootfs-delayed-postinsts stateless-rootfs empty-root-password allow-empty-password allow-root-login serial-autologin-root post-install-logging overlayfs-etc"
44
45# Generate companion debugfs?
46IMAGE_GEN_DEBUGFS ?= "0"
47
48# These packages will be installed as additional into debug rootfs
49IMAGE_INSTALL_DEBUGFS ?= ""
50
51# These packages will be removed from a read-only rootfs after all other
52# packages have been installed
53ROOTFS_RO_UNNEEDED ??= "update-rc.d base-passwd shadow ${VIRTUAL-RUNTIME_update-alternatives} ${ROOTFS_BOOTSTRAP_INSTALL}"
54
55# packages to install from features
56FEATURE_INSTALL = "${@' '.join(oe.packagegroup.required_packages(oe.data.typed_value('IMAGE_FEATURES', d), d))}"
57FEATURE_INSTALL[vardepvalue] = "${FEATURE_INSTALL}"
58FEATURE_INSTALL_OPTIONAL = "${@' '.join(oe.packagegroup.optional_packages(oe.data.typed_value('IMAGE_FEATURES', d), d))}"
59FEATURE_INSTALL_OPTIONAL[vardepvalue] = "${FEATURE_INSTALL_OPTIONAL}"
60
61# Define some very basic feature package groups
62FEATURE_PACKAGES_package-management = "${ROOTFS_PKGMANAGE}"
63SPLASH ?= "${@bb.utils.contains("MACHINE_FEATURES", "screen", "psplash", "", d)}"
64FEATURE_PACKAGES_splash = "${SPLASH}"
65
66IMAGE_INSTALL_COMPLEMENTARY = '${@complementary_globs("IMAGE_FEATURES", d)}'
67
68def check_image_features(d):
69    valid_features = (d.getVarFlag('IMAGE_FEATURES', 'validitems') or "").split()
70    valid_features += d.getVarFlags('COMPLEMENTARY_GLOB').keys()
71    for var in d:
72       if var.startswith("FEATURE_PACKAGES_"):
73           valid_features.append(var[17:])
74    valid_features.sort()
75
76    features = set(oe.data.typed_value('IMAGE_FEATURES', d))
77    for feature in features:
78        if feature not in valid_features:
79            if bb.utils.contains('EXTRA_IMAGE_FEATURES', feature, True, False, d):
80                raise bb.parse.SkipRecipe("'%s' in IMAGE_FEATURES (added via EXTRA_IMAGE_FEATURES) is not a valid image feature. Valid features: %s" % (feature, ' '.join(valid_features)))
81            else:
82                raise bb.parse.SkipRecipe("'%s' in IMAGE_FEATURES is not a valid image feature. Valid features: %s" % (feature, ' '.join(valid_features)))
83
84IMAGE_INSTALL ?= ""
85IMAGE_INSTALL[type] = "list"
86export PACKAGE_INSTALL ?= "${IMAGE_INSTALL} ${ROOTFS_BOOTSTRAP_INSTALL} ${FEATURE_INSTALL}"
87PACKAGE_INSTALL_ATTEMPTONLY ?= "${FEATURE_INSTALL_OPTIONAL}"
88
89IMGDEPLOYDIR = "${WORKDIR}/deploy-${PN}-image-complete"
90
91# Images are generally built explicitly, do not need to be part of world.
92EXCLUDE_FROM_WORLD = "1"
93
94USE_DEVFS ?= "1"
95USE_DEPMOD ?= "1"
96
97PID = "${@os.getpid()}"
98
99PACKAGE_ARCH = "${MACHINE_ARCH}"
100SSTATE_ARCHS_TUNEPKG = "${@all_multilib_tune_values(d, 'TUNE_PKGARCH')}"
101
102LDCONFIGDEPEND ?= "ldconfig-native:do_populate_sysroot"
103LDCONFIGDEPEND:libc-musl = ""
104
105# This is needed to have depmod data in PKGDATA_DIR,
106# but if you're building small initramfs image
107# e.g. to include it in your kernel, you probably
108# don't want this dependency, which is causing dependency loop
109KERNELDEPMODDEPEND ?= "virtual/kernel:do_packagedata"
110
111do_rootfs[depends] += " \
112    makedevs-native:do_populate_sysroot virtual/fakeroot-native:do_populate_sysroot ${LDCONFIGDEPEND} \
113    virtual/update-alternatives-native:do_populate_sysroot update-rc.d-native:do_populate_sysroot \
114    ${KERNELDEPMODDEPEND} \
115"
116do_rootfs[recrdeptask] += "do_packagedata"
117
118def rootfs_command_variables(d):
119    return ['ROOTFS_POSTPROCESS_COMMAND','ROOTFS_PREPROCESS_COMMAND','ROOTFS_POSTINSTALL_COMMAND','ROOTFS_POSTUNINSTALL_COMMAND','OPKG_PREPROCESS_COMMANDS','OPKG_POSTPROCESS_COMMANDS','IMAGE_POSTPROCESS_COMMAND',
120            'IMAGE_PREPROCESS_COMMAND','RPM_PREPROCESS_COMMANDS','RPM_POSTPROCESS_COMMANDS','DEB_PREPROCESS_COMMANDS','DEB_POSTPROCESS_COMMANDS']
121
122python () {
123    variables = rootfs_command_variables(d)
124    for var in variables:
125        d.setVarFlag(var, 'vardeps', d.getVar(var))
126}
127
128def rootfs_variables(d):
129    from oe.rootfs import variable_depends
130    variables = ['IMAGE_DEVICE_TABLE','IMAGE_DEVICE_TABLES','BUILD_IMAGES_FROM_FEEDS','IMAGE_TYPES_MASKED','IMAGE_ROOTFS_ALIGNMENT','IMAGE_OVERHEAD_FACTOR','IMAGE_ROOTFS_SIZE','IMAGE_ROOTFS_EXTRA_SPACE',
131                 'IMAGE_ROOTFS_MAXSIZE','IMAGE_NAME','IMAGE_LINK_NAME','IMAGE_MANIFEST','DEPLOY_DIR_IMAGE','IMAGE_FSTYPES','IMAGE_INSTALL_COMPLEMENTARY','IMAGE_LINGUAS', 'IMAGE_LINGUAS_COMPLEMENTARY', 'IMAGE_LOCALES_ARCHIVE',
132                 'MULTILIBRE_ALLOW_REP','MULTILIB_TEMP_ROOTFS','MULTILIB_VARIANTS','MULTILIBS','ALL_MULTILIB_PACKAGE_ARCHS','MULTILIB_GLOBAL_VARIANTS','BAD_RECOMMENDATIONS','NO_RECOMMENDATIONS',
133                 'PACKAGE_ARCHS','PACKAGE_CLASSES','TARGET_VENDOR','TARGET_ARCH','TARGET_OS','OVERRIDES','BBEXTENDVARIANT','FEED_DEPLOYDIR_BASE_URI','INTERCEPT_DIR','USE_DEVFS',
134                 'CONVERSIONTYPES', 'IMAGE_GEN_DEBUGFS', 'ROOTFS_RO_UNNEEDED', 'IMGDEPLOYDIR', 'PACKAGE_EXCLUDE_COMPLEMENTARY', 'REPRODUCIBLE_TIMESTAMP_ROOTFS', 'IMAGE_INSTALL_DEBUGFS']
135    variables.extend(rootfs_command_variables(d))
136    variables.extend(variable_depends(d))
137    return " ".join(variables)
138
139do_rootfs[vardeps] += "${@rootfs_variables(d)}"
140
141# This is needed to have kernel image in DEPLOY_DIR.
142# This follows many common usecases and user expectations.
143# But if you are building an image which doesn't need the kernel image at all,
144# you can unset this variable manually.
145KERNEL_DEPLOY_DEPEND ?= "virtual/kernel:do_deploy"
146do_build[depends] += "${KERNEL_DEPLOY_DEPEND}"
147
148
149python () {
150    def extraimage_getdepends(task):
151        deps = ""
152        for dep in (d.getVar('EXTRA_IMAGEDEPENDS') or "").split():
153            if ":" in dep:
154                deps += " %s " % (dep)
155            else:
156                deps += " %s:%s" % (dep, task)
157        return deps
158
159    d.appendVarFlag('do_image_complete', 'depends', extraimage_getdepends('do_populate_sysroot'))
160
161    deps = " " + imagetypes_getdepends(d)
162    d.appendVarFlag('do_rootfs', 'depends', deps)
163
164    #process IMAGE_FEATURES, we must do this before runtime_mapping_rename
165    #Check for replaces image features
166    features = set(oe.data.typed_value('IMAGE_FEATURES', d))
167    remain_features = features.copy()
168    for feature in features:
169        replaces = set((d.getVar("IMAGE_FEATURES_REPLACES_%s" % feature) or "").split())
170        remain_features -= replaces
171
172    #Check for conflict image features
173    for feature in remain_features:
174        conflicts = set((d.getVar("IMAGE_FEATURES_CONFLICTS_%s" % feature) or "").split())
175        temp = conflicts & remain_features
176        if temp:
177            bb.fatal("%s contains conflicting IMAGE_FEATURES %s %s" % (d.getVar('PN'), feature, ' '.join(list(temp))))
178
179    d.setVar('IMAGE_FEATURES', ' '.join(sorted(list(remain_features))))
180
181    check_image_features(d)
182}
183
184IMAGE_POSTPROCESS_COMMAND ?= ""
185
186IMAGE_LINGUAS ??= ""
187
188LINGUAS_INSTALL ?= "${@" ".join(map(lambda s: "locale-base-%s" % s, d.getVar('IMAGE_LINGUAS').split()))}"
189
190# per default create a locale archive
191IMAGE_LOCALES_ARCHIVE ?= '1'
192
193# Prefer image, but use the fallback files for lookups if the image ones
194# aren't yet available.
195PSEUDO_PASSWD = "${IMAGE_ROOTFS}:${STAGING_DIR_NATIVE}"
196
197PSEUDO_IGNORE_PATHS .= ",${WORKDIR}/intercept_scripts,${WORKDIR}/oe-rootfs-repo,${WORKDIR}/sstate-build-image_complete"
198
199PACKAGE_EXCLUDE ??= ""
200PACKAGE_EXCLUDE[type] = "list"
201
202fakeroot python do_rootfs () {
203    from oe.rootfs import create_rootfs
204    from oe.manifest import create_manifest
205    import logging
206    import oe.packagedata
207
208    logger = d.getVar('BB_TASK_LOGGER', False)
209    if logger:
210        logcatcher = bb.utils.LogCatcher()
211        logger.addHandler(logcatcher)
212    else:
213        logcatcher = None
214
215    # NOTE: if you add, remove or significantly refactor the stages of this
216    # process then you should recalculate the weightings here. This is quite
217    # easy to do - just change the MultiStageProgressReporter line temporarily
218    # to pass debug=True as the last parameter and you'll get a printout of
219    # the weightings as well as a map to the lines where next_stage() was
220    # called. Of course this isn't critical, but it helps to keep the progress
221    # reporting accurate.
222    stage_weights = [1, 203, 354, 186, 65, 4228, 1, 353, 49, 330, 382, 23, 1]
223    progress_reporter = bb.progress.MultiStageProgressReporter(d, stage_weights)
224    progress_reporter.next_stage()
225
226    # Handle package exclusions
227    excl_pkgs = d.getVar("PACKAGE_EXCLUDE").split()
228    inst_pkgs = d.getVar("PACKAGE_INSTALL").split()
229    inst_attempt_pkgs = d.getVar("PACKAGE_INSTALL_ATTEMPTONLY").split()
230
231    d.setVar('PACKAGE_INSTALL_ORIG', ' '.join(inst_pkgs))
232    d.setVar('PACKAGE_INSTALL_ATTEMPTONLY', ' '.join(inst_attempt_pkgs))
233
234    for pkg in excl_pkgs:
235        if pkg in inst_pkgs:
236            bb.warn("Package %s, set to be excluded, is in %s PACKAGE_INSTALL (%s).  It will be removed from the list." % (pkg, d.getVar('PN'), inst_pkgs))
237            inst_pkgs.remove(pkg)
238
239        if pkg in inst_attempt_pkgs:
240            bb.warn("Package %s, set to be excluded, is in %s PACKAGE_INSTALL_ATTEMPTONLY (%s).  It will be removed from the list." % (pkg, d.getVar('PN'), inst_pkgs))
241            inst_attempt_pkgs.remove(pkg)
242
243    d.setVar("PACKAGE_INSTALL", ' '.join(inst_pkgs))
244    d.setVar("PACKAGE_INSTALL_ATTEMPTONLY", ' '.join(inst_attempt_pkgs))
245
246    # Ensure we handle package name remapping
247    # We have to delay the runtime_mapping_rename until just before rootfs runs
248    # otherwise, the multilib renaming could step in and squash any fixups that
249    # may have occurred.
250    pn = d.getVar('PN')
251    oe.packagedata.runtime_mapping_rename("PACKAGE_INSTALL", pn, d)
252    oe.packagedata.runtime_mapping_rename("PACKAGE_INSTALL_ATTEMPTONLY", pn, d)
253    oe.packagedata.runtime_mapping_rename("BAD_RECOMMENDATIONS", pn, d)
254
255    # Generate the initial manifest
256    create_manifest(d)
257
258    progress_reporter.next_stage()
259
260    # generate rootfs
261    d.setVarFlag('REPRODUCIBLE_TIMESTAMP_ROOTFS', 'export', '1')
262    create_rootfs(d, progress_reporter=progress_reporter, logcatcher=logcatcher)
263
264    progress_reporter.finish()
265}
266do_rootfs[dirs] = "${TOPDIR}"
267do_rootfs[cleandirs] += "${IMAGE_ROOTFS} ${IMGDEPLOYDIR} ${S}"
268do_rootfs[file-checksums] += "${POSTINST_INTERCEPT_CHECKSUMS}"
269addtask rootfs after do_prepare_recipe_sysroot
270
271fakeroot python do_image () {
272    from oe.utils import execute_pre_post_process
273
274    d.setVarFlag('REPRODUCIBLE_TIMESTAMP_ROOTFS', 'export', '1')
275    pre_process_cmds = d.getVar("IMAGE_PREPROCESS_COMMAND")
276
277    execute_pre_post_process(d, pre_process_cmds)
278}
279do_image[dirs] = "${TOPDIR}"
280addtask do_image after do_rootfs
281
282fakeroot python do_image_complete () {
283    from oe.utils import execute_pre_post_process
284
285    post_process_cmds = d.getVar("IMAGE_POSTPROCESS_COMMAND")
286
287    execute_pre_post_process(d, post_process_cmds)
288}
289do_image_complete[dirs] = "${TOPDIR}"
290SSTATETASKS += "do_image_complete"
291SSTATE_SKIP_CREATION:task-image-complete = '1'
292do_image_complete[sstate-inputdirs] = "${IMGDEPLOYDIR}"
293do_image_complete[sstate-outputdirs] = "${DEPLOY_DIR_IMAGE}"
294do_image_complete[stamp-extra-info] = "${MACHINE_ARCH}"
295addtask do_image_complete after do_image before do_build
296python do_image_complete_setscene () {
297    sstate_setscene(d)
298}
299addtask do_image_complete_setscene
300
301# Add image-level QA/sanity checks to IMAGE_QA_COMMANDS
302#
303# IMAGE_QA_COMMANDS += " \
304#     image_check_everything_ok \
305# "
306# This task runs all functions in IMAGE_QA_COMMANDS after the rootfs
307# construction has completed in order to validate the resulting image.
308#
309# The functions should use ${IMAGE_ROOTFS} to find the unpacked rootfs
310# directory, which if QA passes will be the basis for the images.
311fakeroot python do_image_qa () {
312    from oe.utils import ImageQAFailed
313
314    qa_cmds = (d.getVar('IMAGE_QA_COMMANDS') or '').split()
315    qamsg = ""
316
317    for cmd in qa_cmds:
318        try:
319            bb.build.exec_func(cmd, d)
320        except oe.utils.ImageQAFailed as e:
321            qamsg = qamsg + '\tImage QA function %s failed: %s\n' % (e.name, e.description)
322        except Exception as e:
323            qamsg = qamsg + '\tImage QA function %s failed: %s\n' % (cmd, e)
324
325    if qamsg:
326        imgname = d.getVar('IMAGE_NAME')
327        bb.fatal("QA errors found whilst validating image: %s\n%s" % (imgname, qamsg))
328}
329addtask do_image_qa after do_rootfs before do_image
330
331SSTATETASKS += "do_image_qa"
332SSTATE_SKIP_CREATION:task-image-qa = '1'
333do_image_qa[sstate-inputdirs] = ""
334do_image_qa[sstate-outputdirs] = ""
335python do_image_qa_setscene () {
336    sstate_setscene(d)
337}
338addtask do_image_qa_setscene
339
340def setup_debugfs_variables(d):
341    d.appendVar('IMAGE_ROOTFS', '-dbg')
342    if d.getVar('IMAGE_LINK_NAME'):
343        d.appendVar('IMAGE_LINK_NAME', '-dbg')
344    d.appendVar('IMAGE_NAME','-dbg')
345    d.setVar('IMAGE_BUILDING_DEBUGFS', 'true')
346    debugfs_image_fstypes = d.getVar('IMAGE_FSTYPES_DEBUGFS')
347    if debugfs_image_fstypes:
348        d.setVar('IMAGE_FSTYPES', debugfs_image_fstypes)
349
350python setup_debugfs () {
351    setup_debugfs_variables(d)
352}
353
354python () {
355    vardeps = set()
356    # We allow CONVERSIONTYPES to have duplicates. That avoids breaking
357    # derived distros when OE-core or some other layer independently adds
358    # the same type. There is still only one command for each type, but
359    # presumably the commands will do the same when the type is the same,
360    # even when added in different places.
361    #
362    # Without de-duplication, gen_conversion_cmds() below
363    # would create the same compression command multiple times.
364    ctypes = set(d.getVar('CONVERSIONTYPES').split())
365    old_overrides = d.getVar('OVERRIDES', False)
366
367    def _image_base_type(type):
368        basetype = type
369        for ctype in ctypes:
370            if type.endswith("." + ctype):
371                basetype = type[:-len("." + ctype)]
372                break
373
374        if basetype != type:
375            # New base type itself might be generated by a conversion command.
376            basetype = _image_base_type(basetype)
377
378        return basetype
379
380    basetypes = {}
381    alltypes = d.getVar('IMAGE_FSTYPES').split()
382    typedeps = {}
383
384    if d.getVar('IMAGE_GEN_DEBUGFS') == "1":
385        debugfs_fstypes = d.getVar('IMAGE_FSTYPES_DEBUGFS').split()
386        for t in debugfs_fstypes:
387            alltypes.append("debugfs_" + t)
388
389    def _add_type(t):
390        baset = _image_base_type(t)
391        input_t = t
392        if baset not in basetypes:
393            basetypes[baset]= []
394        if t not in basetypes[baset]:
395            basetypes[baset].append(t)
396        debug = ""
397        if t.startswith("debugfs_"):
398            t = t[8:]
399            debug = "debugfs_"
400        deps = (d.getVar('IMAGE_TYPEDEP:' + t) or "").split()
401        vardeps.add('IMAGE_TYPEDEP:' + t)
402        if baset not in typedeps:
403            typedeps[baset] = set()
404        deps = [debug + dep for dep in deps]
405        for dep in deps:
406            if dep not in alltypes:
407                alltypes.append(dep)
408            _add_type(dep)
409            basedep = _image_base_type(dep)
410            typedeps[baset].add(basedep)
411
412        if baset != input_t:
413            _add_type(baset)
414
415    for t in alltypes[:]:
416        _add_type(t)
417
418    d.appendVarFlag('do_image', 'vardeps', ' '.join(vardeps))
419
420    maskedtypes = (d.getVar('IMAGE_TYPES_MASKED') or "").split()
421    maskedtypes = [dbg + t for t in maskedtypes for dbg in ("", "debugfs_")]
422
423    for t in basetypes:
424        vardeps = set()
425        cmds = []
426        subimages = []
427        realt = t
428
429        if t in maskedtypes:
430            continue
431
432        localdata = bb.data.createCopy(d)
433        debug = ""
434        if t.startswith("debugfs_"):
435            setup_debugfs_variables(localdata)
436            debug = "setup_debugfs "
437            realt = t[8:]
438        localdata.setVar('OVERRIDES', '%s:%s' % (realt, old_overrides))
439        localdata.setVar('type', realt)
440        # Delete DATETIME so we don't expand any references to it now
441        # This means the task's hash can be stable rather than having hardcoded
442        # date/time values. It will get expanded at execution time.
443        # Similarly TMPDIR since otherwise we see QA stamp comparision problems
444        # Expand PV else it can trigger get_srcrev which can fail due to these variables being unset
445        localdata.setVar('PV', d.getVar('PV'))
446        localdata.delVar('DATETIME')
447        localdata.delVar('DATE')
448        localdata.delVar('TMPDIR')
449        localdata.delVar('IMAGE_VERSION_SUFFIX')
450        vardepsexclude = (d.getVarFlag('IMAGE_CMD:' + realt, 'vardepsexclude') or '').split()
451        for dep in vardepsexclude:
452            localdata.delVar(dep)
453
454        image_cmd = localdata.getVar("IMAGE_CMD")
455        vardeps.add('IMAGE_CMD:' + realt)
456        if image_cmd:
457            cmds.append("\t" + image_cmd)
458        else:
459            bb.fatal("No IMAGE_CMD defined for IMAGE_FSTYPES entry '%s' - possibly invalid type name or missing support class" % t)
460        cmds.append(localdata.expand("\tcd ${IMGDEPLOYDIR}"))
461
462        # Since a copy of IMAGE_CMD:xxx will be inlined within do_image_xxx,
463        # prevent a redundant copy of IMAGE_CMD:xxx being emitted as a function.
464        d.delVarFlag('IMAGE_CMD:' + realt, 'func')
465
466        rm_tmp_images = set()
467        def gen_conversion_cmds(bt):
468            for ctype in sorted(ctypes):
469                if bt.endswith("." + ctype):
470                    type = bt[0:-len(ctype) - 1]
471                    if type.startswith("debugfs_"):
472                        type = type[8:]
473                    # Create input image first.
474                    gen_conversion_cmds(type)
475                    localdata.setVar('type', type)
476                    cmd = "\t" + localdata.getVar("CONVERSION_CMD:" + ctype)
477                    if cmd not in cmds:
478                        cmds.append(cmd)
479                    vardeps.add('CONVERSION_CMD:' + ctype)
480                    subimage = type + "." + ctype
481                    if subimage not in subimages:
482                        subimages.append(subimage)
483                    if type not in alltypes:
484                        rm_tmp_images.add(localdata.expand("${IMAGE_NAME}.${type}"))
485
486        for bt in basetypes[t]:
487            gen_conversion_cmds(bt)
488
489        localdata.setVar('type', realt)
490        if t not in alltypes:
491            rm_tmp_images.add(localdata.expand("${IMAGE_NAME}.${type}"))
492        else:
493            subimages.append(realt)
494
495        # Clean up after applying all conversion commands. Some of them might
496        # use the same input, therefore we cannot delete sooner without applying
497        # some complex dependency analysis.
498        for image in sorted(rm_tmp_images):
499            cmds.append("\trm " + image)
500
501        after = 'do_image'
502        for dep in typedeps[t]:
503            after += ' do_image_%s' % dep.replace("-", "_").replace(".", "_")
504
505        task = "do_image_%s" % t.replace("-", "_").replace(".", "_")
506
507        d.setVar(task, '\n'.join(cmds))
508        d.setVarFlag(task, 'func', '1')
509        d.setVarFlag(task, 'fakeroot', '1')
510
511        d.appendVarFlag(task, 'prefuncs', ' ' + debug + ' set_image_size')
512        d.prependVarFlag(task, 'postfuncs', 'create_symlinks ')
513        d.appendVarFlag(task, 'subimages', ' ' + ' '.join(subimages))
514        d.appendVarFlag(task, 'vardeps', ' ' + ' '.join(vardeps))
515        d.appendVarFlag(task, 'vardepsexclude', ' DATETIME DATE ' + ' '.join(vardepsexclude))
516
517        bb.debug(2, "Adding task %s before %s, after %s" % (task, 'do_image_complete', after))
518        bb.build.addtask(task, 'do_image_complete', after, d)
519}
520
521#
522# Compute the rootfs size
523#
524def get_rootfs_size(d):
525    import subprocess, oe.utils
526
527    rootfs_alignment = int(d.getVar('IMAGE_ROOTFS_ALIGNMENT'))
528    overhead_factor = float(d.getVar('IMAGE_OVERHEAD_FACTOR'))
529    rootfs_req_size = int(d.getVar('IMAGE_ROOTFS_SIZE'))
530    rootfs_extra_space = eval(d.getVar('IMAGE_ROOTFS_EXTRA_SPACE'))
531    rootfs_maxsize = d.getVar('IMAGE_ROOTFS_MAXSIZE')
532    image_fstypes = d.getVar('IMAGE_FSTYPES') or ''
533    initramfs_fstypes = d.getVar('INITRAMFS_FSTYPES') or ''
534    initramfs_maxsize = d.getVar('INITRAMFS_MAXSIZE')
535
536    size_kb = oe.utils.directory_size(d.getVar("IMAGE_ROOTFS")) / 1024
537
538    base_size = size_kb * overhead_factor
539    bb.debug(1, '%f = %d * %f' % (base_size, size_kb, overhead_factor))
540    base_size2 = max(base_size, rootfs_req_size) + rootfs_extra_space
541    bb.debug(1, '%f = max(%f, %d)[%f] + %d' % (base_size2, base_size, rootfs_req_size, max(base_size, rootfs_req_size), rootfs_extra_space))
542
543    base_size = base_size2
544    if base_size != int(base_size):
545        base_size = int(base_size + 1)
546    else:
547        base_size = int(base_size)
548    bb.debug(1, '%f = int(%f)' % (base_size, base_size2))
549
550    base_size_saved = base_size
551    base_size += rootfs_alignment - 1
552    base_size -= base_size % rootfs_alignment
553    bb.debug(1, '%d = aligned(%d)' % (base_size, base_size_saved))
554
555    # Do not check image size of the debugfs image. This is not supposed
556    # to be deployed, etc. so it doesn't make sense to limit the size
557    # of the debug.
558    if (d.getVar('IMAGE_BUILDING_DEBUGFS') or "") == "true":
559        bb.debug(1, 'returning debugfs size %d' % (base_size))
560        return base_size
561
562    # Check the rootfs size against IMAGE_ROOTFS_MAXSIZE (if set)
563    if rootfs_maxsize:
564        rootfs_maxsize_int = int(rootfs_maxsize)
565        if base_size > rootfs_maxsize_int:
566            bb.fatal("The rootfs size %d(K) exceeds IMAGE_ROOTFS_MAXSIZE: %d(K)" % \
567                (base_size, rootfs_maxsize_int))
568
569    # Check the initramfs size against INITRAMFS_MAXSIZE (if set)
570    if image_fstypes == initramfs_fstypes != ''  and initramfs_maxsize:
571        initramfs_maxsize_int = int(initramfs_maxsize)
572        if base_size > initramfs_maxsize_int:
573            bb.error("The initramfs size %d(K) exceeds INITRAMFS_MAXSIZE: %d(K)" % \
574                (base_size, initramfs_maxsize_int))
575            bb.error("You can set INITRAMFS_MAXSIZE a larger value. Usually, it should")
576            bb.fatal("be less than 1/2 of ram size, or you may fail to boot it.\n")
577
578    bb.debug(1, 'returning %d' % (base_size))
579    return base_size
580
581python set_image_size () {
582        rootfs_size = get_rootfs_size(d)
583        d.setVar('ROOTFS_SIZE', str(rootfs_size))
584        d.setVarFlag('ROOTFS_SIZE', 'export', '1')
585}
586
587#
588# Create symlinks to the newly created image
589#
590python create_symlinks() {
591
592    deploy_dir = d.getVar('IMGDEPLOYDIR')
593    img_name = d.getVar('IMAGE_NAME')
594    link_name = d.getVar('IMAGE_LINK_NAME')
595    manifest_name = d.getVar('IMAGE_MANIFEST')
596    taskname = d.getVar("BB_CURRENTTASK")
597    subimages = (d.getVarFlag("do_" + taskname, 'subimages', False) or "").split()
598
599    if not link_name:
600        return
601    for type in subimages:
602        dst = os.path.join(deploy_dir, link_name + "." + type)
603        src = img_name + "." + type
604        if os.path.exists(os.path.join(deploy_dir, src)):
605            bb.note("Creating symlink: %s -> %s" % (dst, src))
606            if os.path.islink(dst):
607                os.remove(dst)
608            os.symlink(src, dst)
609        else:
610            bb.note("Skipping symlink, source does not exist: %s -> %s" % (dst, src))
611}
612
613MULTILIBRE_ALLOW_REP += "${base_bindir} ${base_sbindir} ${bindir} ${sbindir} ${libexecdir} ${sysconfdir} ${nonarch_base_libdir}/udev /lib/modules/[^/]*/modules.*"
614MULTILIB_CHECK_FILE = "${WORKDIR}/multilib_check.py"
615MULTILIB_TEMP_ROOTFS = "${WORKDIR}/multilib"
616
617do_fetch[noexec] = "1"
618do_unpack[noexec] = "1"
619do_patch[noexec] = "1"
620do_configure[noexec] = "1"
621do_compile[noexec] = "1"
622do_install[noexec] = "1"
623deltask do_populate_lic
624deltask do_populate_sysroot
625do_package[noexec] = "1"
626deltask do_package_qa
627deltask do_packagedata
628deltask do_package_write_ipk
629deltask do_package_write_deb
630deltask do_package_write_rpm
631
632# Prepare the root links to point to the /usr counterparts.
633create_merged_usr_symlinks() {
634    root="$1"
635    install -d $root${base_bindir} $root${base_sbindir} $root${base_libdir}
636    ln -rs $root${base_bindir} $root/bin
637    ln -rs $root${base_sbindir} $root/sbin
638    ln -rs $root${base_libdir} $root/${baselib}
639
640    if [ "${nonarch_base_libdir}" != "${base_libdir}" ]; then
641       install -d $root${nonarch_base_libdir}
642       ln -rs $root${nonarch_base_libdir} $root/lib
643    fi
644
645    # create base links for multilibs
646    multi_libdirs="${@d.getVar('MULTILIB_VARIANTS')}"
647    for d in $multi_libdirs; do
648        install -d $root${exec_prefix}/$d
649        ln -rs $root${exec_prefix}/$d $root/$d
650    done
651}
652
653create_merged_usr_symlinks_rootfs() {
654    create_merged_usr_symlinks ${IMAGE_ROOTFS}
655}
656
657create_merged_usr_symlinks_sdk() {
658    create_merged_usr_symlinks ${SDK_OUTPUT}${SDKTARGETSYSROOT}
659}
660
661ROOTFS_PREPROCESS_COMMAND += "${@bb.utils.contains('DISTRO_FEATURES', 'usrmerge', 'create_merged_usr_symlinks_rootfs', '',d)}"
662POPULATE_SDK_PRE_TARGET_COMMAND += "${@bb.utils.contains('DISTRO_FEATURES', 'usrmerge', 'create_merged_usr_symlinks_sdk', '',d)}"
663
664reproducible_final_image_task () {
665    if [ "$REPRODUCIBLE_TIMESTAMP_ROOTFS" = "" ]; then
666        REPRODUCIBLE_TIMESTAMP_ROOTFS=`git -C "${COREBASE}" log -1 --pretty=%ct 2>/dev/null` || true
667        if [ "$REPRODUCIBLE_TIMESTAMP_ROOTFS" = "" ]; then
668            REPRODUCIBLE_TIMESTAMP_ROOTFS=`stat -c%Y ${@bb.utils.which(d.getVar("BBPATH"), "conf/bitbake.conf")}`
669        fi
670    fi
671    # Set mtime of all files to a reproducible value
672    bbnote "reproducible_final_image_task: mtime set to $REPRODUCIBLE_TIMESTAMP_ROOTFS"
673    find  ${IMAGE_ROOTFS} -print0 | xargs -0 touch -h  --date=@$REPRODUCIBLE_TIMESTAMP_ROOTFS
674}
675
676systemd_preset_all () {
677    if [ -e ${IMAGE_ROOTFS}${root_prefix}/lib/systemd/systemd ]; then
678	systemctl --root="${IMAGE_ROOTFS}" --preset-mode=enable-only preset-all
679    fi
680}
681
682IMAGE_PREPROCESS_COMMAND:append = " ${@ 'systemd_preset_all' if bb.utils.contains('DISTRO_FEATURES', 'systemd', True, False, d) and not bb.utils.contains('IMAGE_FEATURES', 'stateless-rootfs', True, False, d) else ''} reproducible_final_image_task "
683
684CVE_PRODUCT = ""
685