1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7# Zap the root password if debug-tweaks and empty-root-password features are not enabled
8ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains_any("IMAGE_FEATURES", [ 'debug-tweaks', 'empty-root-password' ], "", "zap_empty_root_password; ",d)}'
9
10# Allow dropbear/openssh to accept logins from accounts with an empty password string if debug-tweaks or allow-empty-password is enabled
11ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains_any("IMAGE_FEATURES", [ 'debug-tweaks', 'allow-empty-password' ], "ssh_allow_empty_password; ", "",d)}'
12
13# Allow dropbear/openssh to accept root logins if debug-tweaks or allow-root-login is enabled
14ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains_any("IMAGE_FEATURES", [ 'debug-tweaks', 'allow-root-login' ], "ssh_allow_root_login; ", "",d)}'
15
16# Autologin the root user on the serial console, if empty-root-password and serial-autologin-root are active
17ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", [ 'empty-root-password', 'serial-autologin-root' ], "serial_autologin_root; ", "",d)}'
18
19# Enable postinst logging if debug-tweaks or post-install-logging is enabled
20ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains_any("IMAGE_FEATURES", [ 'debug-tweaks', 'post-install-logging' ], "postinst_enable_logging; ", "",d)}'
21
22# Create /etc/timestamp during image construction to give a reasonably sane default time setting
23ROOTFS_POSTPROCESS_COMMAND += "rootfs_update_timestamp; "
24
25# Tweak files in /etc if read-only-rootfs is enabled
26ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs", "read_only_rootfs_hook; ", "",d)}'
27
28# We also need to do the same for the kernel boot parameters,
29# otherwise kernel or initramfs end up mounting the rootfs read/write
30# (the default) if supported by the underlying storage.
31#
32# We do this with :append because the default value might get set later with ?=
33# and we don't want to disable such a default that by setting a value here.
34APPEND:append = '${@bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs", " ro", "", d)}'
35
36# Generates test data file with data store variables expanded in json format
37ROOTFS_POSTPROCESS_COMMAND += "write_image_test_data; "
38
39# Write manifest
40IMAGE_MANIFEST = "${IMGDEPLOYDIR}/${IMAGE_NAME}.manifest"
41ROOTFS_POSTUNINSTALL_COMMAND =+ "write_image_manifest ; "
42# Set default postinst log file
43POSTINST_LOGFILE ?= "${localstatedir}/log/postinstall.log"
44# Set default target for systemd images
45SYSTEMD_DEFAULT_TARGET ?= '${@bb.utils.contains_any("IMAGE_FEATURES", [ "x11-base", "weston" ], "graphical.target", "multi-user.target", d)}'
46ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("DISTRO_FEATURES", "systemd", "set_systemd_default_target; systemd_sysusers_check;", "", d)}'
47
48ROOTFS_POSTPROCESS_COMMAND += 'empty_var_volatile;'
49
50ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("DISTRO_FEATURES", "overlayfs", "overlayfs_qa_check; overlayfs_postprocess;", "", d)}'
51
52inherit image-artifact-names
53
54# Sort the user and group entries in /etc by ID in order to make the content
55# deterministic. Package installs are not deterministic, causing the ordering
56# of entries to change between builds. In case that this isn't desired,
57# the command can be overridden.
58#
59# Note that useradd-staticids.bbclass has to be used to ensure that
60# the numeric IDs of dynamically created entries remain stable.
61#
62# We want this to run as late as possible, in particular after
63# systemd_sysusers_create and set_user_group. Using :append is not
64# enough for that, set_user_group is added that way and would end
65# up running after us.
66SORT_PASSWD_POSTPROCESS_COMMAND ??= " tidy_shadowutils_files; "
67python () {
68    d.appendVar('ROOTFS_POSTPROCESS_COMMAND', '${SORT_PASSWD_POSTPROCESS_COMMAND}')
69    d.appendVar('ROOTFS_POSTPROCESS_COMMAND', 'rootfs_reproducible;')
70}
71
72# Resolve the ID as described in the sysusers.d(5) manual: ID can be a numeric
73# uid, a couple uid:gid or uid:groupname or it is '-' meaning leaving it
74# automatic or it can be a path. In the latter, the uid/gid matches the
75# user/group owner of that file.
76def resolve_sysusers_id(d, sid):
77    # If the id is a path, the uid/gid matchs to the target's uid/gid in the
78    # rootfs.
79    if '/' in sid:
80        try:
81            osstat = os.stat(os.path.join(d.getVar('IMAGE_ROOTFS'), sid))
82        except FileNotFoundError:
83            bb.error('sysusers.d: file %s is required but it does not exist in the rootfs', sid)
84            return ('-', '-')
85        return (osstat.st_uid, osstat.st_gid)
86    # Else it is a uid:gid or uid:groupname syntax
87    if ':' in sid:
88        return sid.split(':')
89    else:
90        return (sid, '-')
91
92# Check a user exists in the rootfs password file and return its properties
93def check_user_exists(d, uname=None, uid=None):
94    with open(os.path.join(d.getVar('IMAGE_ROOTFS'), 'etc/passwd'), 'r') as pwfile:
95        for line in pwfile:
96            (name, _, u_id, gid, comment, homedir, ushell) = line.strip().split(':')
97            if uname == name or uid == u_id:
98                return (name, u_id, gid, comment or '-', homedir or '/', ushell or '-')
99    return None
100
101# Check a group exists in the rootfs group file and return its properties
102def check_group_exists(d, gname=None, gid=None):
103    with open(os.path.join(d.getVar('IMAGE_ROOTFS'), 'etc/group'), 'r') as gfile:
104        for line in gfile:
105            (name, _, g_id, _) = line.strip().split(':')
106            if name == gname or g_id == gid:
107                return (name, g_id)
108    return None
109
110def compare_users(user, e_user):
111    # user and e_user must not have None values. Unset values must be '-'.
112    (name, uid, gid, comment, homedir, ushell) = user
113    (e_name, e_uid, e_gid, e_comment, e_homedir, e_ushell) = e_user
114    # Ignore 'uid', 'gid' or 'comment' if they are not set
115    # Ignore 'shell' and 'ushell' if one is not set
116    return name == e_name \
117        and (uid == '-' or uid == e_uid) \
118        and (gid == '-' or gid == e_gid) \
119        and (comment == '-' or e_comment == '-' or comment.lower() == e_comment.lower()) \
120        and (homedir == '-' or e_homedir == '-' or homedir == e_homedir) \
121        and (ushell == '-' or e_ushell == '-' or ushell == e_ushell)
122
123# Open sysusers.d configuration files and parse each line to check the users and
124# groups are already defined in /etc/passwd and /etc/groups with similar
125# properties. Refer to the sysusers.d(5) manual for its syntax.
126python systemd_sysusers_check() {
127    import glob
128    import re
129
130    pattern_comment = r'(-|\"[^:\"]+\")'
131    pattern_word    = r'[^\s]+'
132    pattern_line   = r'(' + pattern_word + r')\s+(' + pattern_word + r')\s+(' + pattern_word + r')(\s+' \
133        + pattern_comment + r')?' + r'(\s+(' + pattern_word + r'))?' + r'(\s+(' + pattern_word + r'))?'
134
135    for conffile in glob.glob(os.path.join(d.getVar('IMAGE_ROOTFS'), 'usr/lib/sysusers.d/*.conf')):
136        with open(conffile, 'r') as f:
137            for line in f:
138                line = line.strip()
139                if not len(line) or line[0] == '#': continue
140                ret = re.fullmatch(pattern_line, line.strip())
141                if not ret: continue
142                (stype, sname, sid, _, scomment, _, shomedir, _, sshell) = ret.groups()
143                if stype == 'u':
144                    if sid:
145                        (suid, sgid) = resolve_sysusers_id(d, sid)
146                        if sgid.isalpha():
147                            sgid = check_group_exists(d, gname=sgid)
148                        elif sgid.isdigit():
149                            check_group_exists(d, gid=sgid)
150                        else:
151                            sgid = '-'
152                    else:
153                        suid = '-'
154                        sgid = '-'
155                    scomment = scomment.replace('"', '') if scomment else '-'
156                    shomedir = shomedir or '-'
157                    sshell = sshell or '-'
158                    e_user = check_user_exists(d, uname=sname)
159                    if not e_user:
160                        bb.warn('User %s has never been defined' % sname)
161                    elif not compare_users((sname, suid, sgid, scomment, shomedir, sshell), e_user):
162                        bb.warn('User %s has been defined as (%s) but sysusers.d expects it as (%s)'
163                                % (sname, ', '.join(e_user),
164                                ', '.join((sname, suid, sgid, scomment, shomedir, sshell))))
165                elif stype == 'g':
166                    gid = sid or '-'
167                    if '/' in gid:
168                        (_, gid) = resolve_sysusers_id(d, sid)
169                    e_group = check_group_exists(d, gname=sname)
170                    if not e_group:
171                        bb.warn('Group %s has never been defined' % sname)
172                    elif gid != '-':
173                        (_, e_gid) = e_group
174                        if gid != e_gid:
175                            bb.warn('Group %s has been defined with id (%s) but sysusers.d expects gid (%s)'
176                                    % (sname, e_gid, gid))
177                elif stype == 'm':
178                    check_user_exists(d, sname)
179                    check_group_exists(d, sid)
180}
181
182#
183# A hook function to support read-only-rootfs IMAGE_FEATURES
184#
185read_only_rootfs_hook () {
186	# Tweak the mount option and fs_passno for rootfs in fstab
187	if [ -f ${IMAGE_ROOTFS}/etc/fstab ]; then
188		sed -i -e '/^[#[:space:]]*\/dev\/root/{s/defaults/ro/;s/\([[:space:]]*[[:digit:]]\)\([[:space:]]*\)[[:digit:]]$/\1\20/}' ${IMAGE_ROOTFS}/etc/fstab
189	fi
190
191	# Tweak the "mount -o remount,rw /" command in busybox-inittab inittab
192	if [ -f ${IMAGE_ROOTFS}/etc/inittab ]; then
193		sed -i 's|/bin/mount -o remount,rw /|/bin/mount -o remount,ro /|' ${IMAGE_ROOTFS}/etc/inittab
194	fi
195
196	# If we're using openssh and the /etc/ssh directory has no pre-generated keys,
197	# we should configure openssh to use the configuration file /etc/ssh/sshd_config_readonly
198	# and the keys under /var/run/ssh.
199	# If overlayfs-etc is used this is not done as /etc is treated as writable
200	# If stateless-rootfs is enabled this is always done as we don't want to save keys then
201	if ${@ 'true' if not bb.utils.contains('IMAGE_FEATURES', 'overlayfs-etc', True, False, d) or bb.utils.contains('IMAGE_FEATURES', 'stateless-rootfs', True, False, d) else 'false'}; then
202		if [ -d ${IMAGE_ROOTFS}/etc/ssh ]; then
203			if [ -e ${IMAGE_ROOTFS}/etc/ssh/ssh_host_rsa_key ]; then
204				echo "SYSCONFDIR=\${SYSCONFDIR:-/etc/ssh}" >> ${IMAGE_ROOTFS}/etc/default/ssh
205				echo "SSHD_OPTS=" >> ${IMAGE_ROOTFS}/etc/default/ssh
206			else
207				echo "SYSCONFDIR=\${SYSCONFDIR:-/var/run/ssh}" >> ${IMAGE_ROOTFS}/etc/default/ssh
208				echo "SSHD_OPTS='-f /etc/ssh/sshd_config_readonly'" >> ${IMAGE_ROOTFS}/etc/default/ssh
209			fi
210		fi
211
212		# Also tweak the key location for dropbear in the same way.
213		if [ -d ${IMAGE_ROOTFS}/etc/dropbear ]; then
214			if [ ! -e ${IMAGE_ROOTFS}/etc/dropbear/dropbear_rsa_host_key ]; then
215				echo "DROPBEAR_RSAKEY_DIR=/var/lib/dropbear" >> ${IMAGE_ROOTFS}/etc/default/dropbear
216			fi
217		fi
218	fi
219
220	if ${@bb.utils.contains("DISTRO_FEATURES", "sysvinit", "true", "false", d)}; then
221		# Change the value of ROOTFS_READ_ONLY in /etc/default/rcS to yes
222		if [ -e ${IMAGE_ROOTFS}/etc/default/rcS ]; then
223			sed -i 's/ROOTFS_READ_ONLY=no/ROOTFS_READ_ONLY=yes/' ${IMAGE_ROOTFS}/etc/default/rcS
224		fi
225		# Run populate-volatile.sh at rootfs time to set up basic files
226		# and directories to support read-only rootfs.
227		if [ -x ${IMAGE_ROOTFS}/etc/init.d/populate-volatile.sh ]; then
228			${IMAGE_ROOTFS}/etc/init.d/populate-volatile.sh
229		fi
230	fi
231
232	if ${@bb.utils.contains("DISTRO_FEATURES", "systemd", "true", "false", d)}; then
233	# Create machine-id
234	# 20:12 < mezcalero> koen: you have three options: a) run systemd-machine-id-setup at install time, b) have / read-only and an empty file there (for stateless) and c) boot with / writable
235		touch ${IMAGE_ROOTFS}${sysconfdir}/machine-id
236	fi
237}
238
239#
240# This function disallows empty root passwords
241#
242zap_empty_root_password () {
243	if [ -e ${IMAGE_ROOTFS}/etc/shadow ]; then
244		sed -i 's%^root::%root:*:%' ${IMAGE_ROOTFS}/etc/shadow
245        fi
246	if [ -e ${IMAGE_ROOTFS}/etc/passwd ]; then
247		sed -i 's%^root::%root:*:%' ${IMAGE_ROOTFS}/etc/passwd
248	fi
249}
250
251#
252# allow dropbear/openssh to accept logins from accounts with an empty password string
253#
254ssh_allow_empty_password () {
255	for config in sshd_config sshd_config_readonly; do
256		if [ -e ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config ]; then
257			sed -i 's/^[#[:space:]]*PermitEmptyPasswords.*/PermitEmptyPasswords yes/' ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config
258		fi
259	done
260
261	if [ -e ${IMAGE_ROOTFS}${sbindir}/dropbear ] ; then
262		if grep -q DROPBEAR_EXTRA_ARGS ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear 2>/dev/null ; then
263			if ! grep -q "DROPBEAR_EXTRA_ARGS=.*-B" ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear ; then
264				sed -i 's/^DROPBEAR_EXTRA_ARGS="*\([^"]*\)"*/DROPBEAR_EXTRA_ARGS="\1 -B"/' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
265			fi
266		else
267			printf '\nDROPBEAR_EXTRA_ARGS="-B"\n' >> ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
268		fi
269	fi
270
271	if [ -d ${IMAGE_ROOTFS}${sysconfdir}/pam.d ] ; then
272		for f in `find ${IMAGE_ROOTFS}${sysconfdir}/pam.d/* -type f -exec test -e {} \; -print`
273		do
274			sed -i 's/nullok_secure/nullok/' $f
275		done
276	fi
277}
278
279#
280# allow dropbear/openssh to accept root logins
281#
282ssh_allow_root_login () {
283	for config in sshd_config sshd_config_readonly; do
284		if [ -e ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config ]; then
285			sed -i 's/^[#[:space:]]*PermitRootLogin.*/PermitRootLogin yes/' ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config
286		fi
287	done
288
289	if [ -e ${IMAGE_ROOTFS}${sbindir}/dropbear ] ; then
290		if grep -q DROPBEAR_EXTRA_ARGS ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear 2>/dev/null ; then
291			sed -i '/^DROPBEAR_EXTRA_ARGS=/ s/-w//' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
292			sed -i '/^# Disallow root/d' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
293		fi
294	fi
295}
296
297#
298# Autologin the 'root' user on the serial terminal,
299# if empty-root-password' AND 'serial-autologin-root are enabled
300#
301serial_autologin_root () {
302	if ${@bb.utils.contains("DISTRO_FEATURES", "sysvinit", "true", "false", d)}; then
303		# add autologin option to util-linux getty only
304		sed -i 's/options="/&--autologin root /' \
305			"${IMAGE_ROOTFS}${base_bindir}/start_getty"
306	elif ${@bb.utils.contains("DISTRO_FEATURES", "systemd", "true", "false", d)}; then
307		if [ -e ${IMAGE_ROOTFS}${systemd_system_unitdir}/serial-getty@.service ]; then
308			sed -i '/^\s*ExecStart\b/ s/getty /&--autologin root /' \
309				"${IMAGE_ROOTFS}${systemd_system_unitdir}/serial-getty@.service"
310		fi
311	fi
312}
313
314python tidy_shadowutils_files () {
315    import rootfspostcommands
316    rootfspostcommands.tidy_shadowutils_files(d.expand('${IMAGE_ROOTFS}${sysconfdir}'))
317}
318
319python sort_passwd () {
320    """
321    Deprecated in the favour of tidy_shadowutils_files.
322    """
323    import rootfspostcommands
324    bb.warn('[sort_passwd] You are using a deprecated function for '
325        'SORT_PASSWD_POSTPROCESS_COMMAND. The default one is now called '
326        '"tidy_shadowutils_files".')
327    rootfspostcommands.tidy_shadowutils_files(d.expand('${IMAGE_ROOTFS}${sysconfdir}'))
328}
329
330#
331# Enable postinst logging
332#
333postinst_enable_logging () {
334	mkdir -p ${IMAGE_ROOTFS}${sysconfdir}/default
335	echo "POSTINST_LOGGING=1" >> ${IMAGE_ROOTFS}${sysconfdir}/default/postinst
336	echo "LOGFILE=${POSTINST_LOGFILE}" >> ${IMAGE_ROOTFS}${sysconfdir}/default/postinst
337}
338
339#
340# Modify systemd default target
341#
342set_systemd_default_target () {
343	if [ -d ${IMAGE_ROOTFS}${sysconfdir}/systemd/system -a -e ${IMAGE_ROOTFS}${systemd_system_unitdir}/${SYSTEMD_DEFAULT_TARGET} ]; then
344		ln -sf ${systemd_system_unitdir}/${SYSTEMD_DEFAULT_TARGET} ${IMAGE_ROOTFS}${sysconfdir}/systemd/system/default.target
345	fi
346}
347
348# If /var/volatile is not empty, we have seen problems where programs such as the
349# journal make assumptions based on the contents of /var/volatile. The journal
350# would then write to /var/volatile before it was mounted, thus hiding the
351# items previously written.
352#
353# This change is to attempt to fix those types of issues in a way that doesn't
354# affect users that may not be using /var/volatile.
355empty_var_volatile () {
356	if [ -e ${IMAGE_ROOTFS}/etc/fstab ]; then
357		match=`awk '$1 !~ "#" && $2 ~ /\/var\/volatile/{print $2}' ${IMAGE_ROOTFS}/etc/fstab 2> /dev/null`
358		if [ -n "$match" ]; then
359			find ${IMAGE_ROOTFS}/var/volatile -mindepth 1 -delete
360		fi
361	fi
362}
363
364# Turn any symbolic /sbin/init link into a file
365remove_init_link () {
366	if [ -h ${IMAGE_ROOTFS}/sbin/init ]; then
367		LINKFILE=${IMAGE_ROOTFS}`readlink ${IMAGE_ROOTFS}/sbin/init`
368		rm ${IMAGE_ROOTFS}/sbin/init
369		cp $LINKFILE ${IMAGE_ROOTFS}/sbin/init
370	fi
371}
372
373make_zimage_symlink_relative () {
374	if [ -L ${IMAGE_ROOTFS}/boot/zImage ]; then
375		(cd ${IMAGE_ROOTFS}/boot/ && for i in `ls zImage-* | sort`; do ln -sf $i zImage; done)
376	fi
377}
378
379python write_image_manifest () {
380    from oe.rootfs import image_list_installed_packages
381    from oe.utils import format_pkg_list
382
383    deploy_dir = d.getVar('IMGDEPLOYDIR')
384    link_name = d.getVar('IMAGE_LINK_NAME')
385    manifest_name = d.getVar('IMAGE_MANIFEST')
386
387    if not manifest_name:
388        return
389
390    pkgs = image_list_installed_packages(d)
391    with open(manifest_name, 'w+') as image_manifest:
392        image_manifest.write(format_pkg_list(pkgs, "ver"))
393
394    if os.path.exists(manifest_name) and link_name:
395        manifest_link = deploy_dir + "/" + link_name + ".manifest"
396        if manifest_link != manifest_name:
397            if os.path.lexists(manifest_link):
398                os.remove(manifest_link)
399            os.symlink(os.path.basename(manifest_name), manifest_link)
400}
401
402# Can be used to create /etc/timestamp during image construction to give a reasonably
403# sane default time setting
404rootfs_update_timestamp () {
405	if [ "${REPRODUCIBLE_TIMESTAMP_ROOTFS}" != "" ]; then
406		# Convert UTC into %4Y%2m%2d%2H%2M%2S
407		sformatted=`date -u -d @${REPRODUCIBLE_TIMESTAMP_ROOTFS} +%4Y%2m%2d%2H%2M%2S`
408	else
409		sformatted=`date -u +%4Y%2m%2d%2H%2M%2S`
410	fi
411	echo $sformatted > ${IMAGE_ROOTFS}/etc/timestamp
412	bbnote "rootfs_update_timestamp: set /etc/timestamp to $sformatted"
413}
414
415# Prevent X from being started
416rootfs_no_x_startup () {
417	if [ -f ${IMAGE_ROOTFS}/etc/init.d/xserver-nodm ]; then
418		chmod a-x ${IMAGE_ROOTFS}/etc/init.d/xserver-nodm
419	fi
420}
421
422rootfs_trim_schemas () {
423	for schema in ${IMAGE_ROOTFS}/etc/gconf/schemas/*.schemas
424	do
425		# Need this in case no files exist
426		if [ -e $schema ]; then
427			oe-trim-schemas $schema > $schema.new
428			mv $schema.new $schema
429		fi
430	done
431}
432
433rootfs_check_host_user_contaminated () {
434	contaminated="${S}/host-user-contaminated.txt"
435	HOST_USER_UID="$(PSEUDO_UNLOAD=1 id -u)"
436	HOST_USER_GID="$(PSEUDO_UNLOAD=1 id -g)"
437
438	find "${IMAGE_ROOTFS}" -path "${IMAGE_ROOTFS}/home" -prune -o \
439	    -user "$HOST_USER_UID" -print -o -group "$HOST_USER_GID" -print >"$contaminated"
440
441	sed -e "s,${IMAGE_ROOTFS},," $contaminated | while read line; do
442		bbwarn "Path in the rootfs is owned by the same user or group as the user running bitbake:" $line `ls -lan ${IMAGE_ROOTFS}/$line`
443	done
444
445	if [ -s "$contaminated" ]; then
446		bbwarn "/etc/passwd:" `cat ${IMAGE_ROOTFS}/etc/passwd`
447		bbwarn "/etc/group:" `cat ${IMAGE_ROOTFS}/etc/group`
448	fi
449}
450
451# Make any absolute links in a sysroot relative
452rootfs_sysroot_relativelinks () {
453	sysroot-relativelinks.py ${SDK_OUTPUT}/${SDKTARGETSYSROOT}
454}
455
456# Generated test data json file
457python write_image_test_data() {
458    from oe.data import export2json
459
460    deploy_dir = d.getVar('IMGDEPLOYDIR')
461    link_name = d.getVar('IMAGE_LINK_NAME')
462    testdata_name = os.path.join(deploy_dir, "%s.testdata.json" % d.getVar('IMAGE_NAME'))
463
464    searchString = "%s/"%(d.getVar("TOPDIR")).replace("//","/")
465    export2json(d, testdata_name, searchString=searchString, replaceString="")
466
467    if os.path.exists(testdata_name) and link_name:
468        testdata_link = os.path.join(deploy_dir, "%s.testdata.json" % link_name)
469        if testdata_link != testdata_name:
470            if os.path.lexists(testdata_link):
471                os.remove(testdata_link)
472            os.symlink(os.path.basename(testdata_name), testdata_link)
473}
474write_image_test_data[vardepsexclude] += "TOPDIR"
475
476# Check for unsatisfied recommendations (RRECOMMENDS)
477python rootfs_log_check_recommends() {
478    log_path = d.expand("${T}/log.do_rootfs")
479    with open(log_path, 'r') as log:
480        for line in log:
481            if 'log_check' in line:
482                continue
483
484            if 'unsatisfied recommendation for' in line:
485                bb.warn('[log_check] %s: %s' % (d.getVar('PN'), line))
486}
487
488# Perform any additional adjustments needed to make rootf binary reproducible
489rootfs_reproducible () {
490	if [ "${REPRODUCIBLE_TIMESTAMP_ROOTFS}" != "" ]; then
491		# Convert UTC into %4Y%2m%2d%2H%2M%2S
492		sformatted=`date -u -d @${REPRODUCIBLE_TIMESTAMP_ROOTFS} +%4Y%2m%2d%2H%2M%2S`
493		echo $sformatted > ${IMAGE_ROOTFS}/etc/version
494		bbnote "rootfs_reproducible: set /etc/version to $sformatted"
495
496		if [ -d ${IMAGE_ROOTFS}${sysconfdir}/gconf ]; then
497			find ${IMAGE_ROOTFS}${sysconfdir}/gconf -name '%gconf.xml' -print0 | xargs -0r \
498			sed -i -e 's@\bmtime="[0-9][0-9]*"@mtime="'${REPRODUCIBLE_TIMESTAMP_ROOTFS}'"@g'
499		fi
500	fi
501}
502
503# Perform a dumb check for unit existence, not its validity
504python overlayfs_qa_check() {
505    from oe.overlayfs import mountUnitName
506
507    overlayMountPoints = d.getVarFlags("OVERLAYFS_MOUNT_POINT") or {}
508    imagepath = d.getVar("IMAGE_ROOTFS")
509    sysconfdir = d.getVar("sysconfdir")
510    searchpaths = [oe.path.join(imagepath, sysconfdir, "systemd", "system"),
511                   oe.path.join(imagepath, d.getVar("systemd_system_unitdir"))]
512    fstabpath = oe.path.join(imagepath, sysconfdir, "fstab")
513
514    if not any(os.path.exists(path) for path in [*searchpaths, fstabpath]):
515        return
516
517    fstabDevices = []
518    if os.path.isfile(fstabpath):
519        with open(fstabpath, 'r') as f:
520            for line in f:
521                if line[0] == '#':
522                    continue
523                path = line.split(maxsplit=2)
524                if len(path) > 2:
525                    fstabDevices.append(path[1])
526
527    allUnitExist = True;
528    for mountPoint in overlayMountPoints:
529        qaSkip = (d.getVarFlag("OVERLAYFS_QA_SKIP", mountPoint) or "").split()
530        if "mount-configured" in qaSkip:
531            continue
532
533        mountPath = d.getVarFlag('OVERLAYFS_MOUNT_POINT', mountPoint)
534        if mountPath in fstabDevices:
535            continue
536
537        mountUnit = mountUnitName(mountPath)
538        if any(os.path.isfile(oe.path.join(dirpath, mountUnit))
539               for dirpath in searchpaths):
540            continue
541
542        bb.warn(f'Mount path {mountPath} not found in fstab and unit '
543                f'{mountUnit} not found in systemd unit directories.')
544        bb.warn(f'Skip this check by setting OVERLAYFS_QA_SKIP[{mountPoint}] = '
545                '"mount-configured"')
546        allUnitExist = False;
547
548    if not allUnitExist:
549        bb.fatal('Not all mount paths and units are installed in the image')
550}
551
552python overlayfs_postprocess() {
553    import shutil
554
555    # install helper script
556    helperScriptName = "overlayfs-create-dirs.sh"
557    helperScriptSource = oe.path.join(d.getVar("COREBASE"), "meta/files", helperScriptName)
558    helperScriptDest = oe.path.join(d.getVar("IMAGE_ROOTFS"), "/usr/sbin/", helperScriptName)
559    shutil.copyfile(helperScriptSource, helperScriptDest)
560    os.chmod(helperScriptDest, 0o755)
561}
562