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