blob: 4ac977b12207801e469372022431dacaf04dda28 [file] [log] [blame]
Patrick Williams92b42cb2022-09-03 06:53:57 -05001#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7# remove tasks that modify the source tree in case externalsrc is inherited
8SRCTREECOVEREDTASKS += "do_validate_branches do_kernel_configcheck do_kernel_checkout do_fetch do_unpack do_patch"
9PATCH_GIT_USER_EMAIL ?= "kernel-yocto@oe"
10PATCH_GIT_USER_NAME ?= "OpenEmbedded"
11
12# The distro or local.conf should set this, but if nobody cares...
13LINUX_KERNEL_TYPE ??= "standard"
14
15# KMETA ?= ""
16KBRANCH ?= "master"
17KMACHINE ?= "${MACHINE}"
18SRCREV_FORMAT ?= "meta_machine"
19
20# LEVELS:
21# 0: no reporting
22# 1: report options that are specified, but not in the final config
23# 2: report options that are not hardware related, but set by a BSP
24KCONF_AUDIT_LEVEL ?= "1"
25KCONF_BSP_AUDIT_LEVEL ?= "0"
26KMETA_AUDIT ?= "yes"
27KMETA_AUDIT_WERROR ?= ""
28
29# returns local (absolute) path names for all valid patches in the
30# src_uri
31def find_patches(d,subdir):
32 patches = src_patches(d)
33 patch_list=[]
34 for p in patches:
35 _, _, local, _, _, parm = bb.fetch.decodeurl(p)
36 # if patchdir has been passed, we won't be able to apply it so skip
37 # the patch for now, and special processing happens later
38 patchdir = ''
39 if "patchdir" in parm:
40 patchdir = parm["patchdir"]
41 if subdir:
42 if subdir == patchdir:
43 patch_list.append(local)
44 else:
45 # skip the patch if a patchdir was supplied, it won't be handled
46 # properly
47 if not patchdir:
48 patch_list.append(local)
49
50 return patch_list
51
52# returns all the elements from the src uri that are .scc files
53def find_sccs(d):
54 sources=src_patches(d, True)
55 sources_list=[]
56 for s in sources:
57 base, ext = os.path.splitext(os.path.basename(s))
58 if ext and ext in [".scc", ".cfg"]:
59 sources_list.append(s)
60 elif base and 'defconfig' in base:
61 sources_list.append(s)
62
63 return sources_list
64
65# check the SRC_URI for "kmeta" type'd git repositories. Return the name of
66# the repository as it will be found in WORKDIR
67def find_kernel_feature_dirs(d):
68 feature_dirs=[]
69 fetch = bb.fetch2.Fetch([], d)
70 for url in fetch.urls:
71 urldata = fetch.ud[url]
72 parm = urldata.parm
73 type=""
74 if "type" in parm:
75 type = parm["type"]
76 if "destsuffix" in parm:
77 destdir = parm["destsuffix"]
78 if type == "kmeta":
79 feature_dirs.append(destdir)
80
81 return feature_dirs
82
83# find the master/machine source branch. In the same way that the fetcher proceses
84# git repositories in the SRC_URI we take the first repo found, first branch.
85def get_machine_branch(d, default):
86 fetch = bb.fetch2.Fetch([], d)
87 for url in fetch.urls:
88 urldata = fetch.ud[url]
89 parm = urldata.parm
90 if "branch" in parm:
91 branches = urldata.parm.get("branch").split(',')
92 btype = urldata.parm.get("type")
93 if btype != "kmeta":
94 return branches[0]
95
96 return default
97
98# returns a list of all directories that are on FILESEXTRAPATHS (and
99# hence available to the build) that contain .scc or .cfg files
100def get_dirs_with_fragments(d):
101 extrapaths = []
102 extrafiles = []
103 extrapathsvalue = (d.getVar("FILESEXTRAPATHS") or "")
104 # Remove default flag which was used for checking
105 extrapathsvalue = extrapathsvalue.replace("__default:", "")
106 extrapaths = extrapathsvalue.split(":")
107 for path in extrapaths:
108 if path + ":True" not in extrafiles:
109 extrafiles.append(path + ":" + str(os.path.exists(path)))
110
111 return " ".join(extrafiles)
112
113do_kernel_metadata() {
114 set +e
115
116 if [ -n "$1" ]; then
117 mode="$1"
118 else
119 mode="patch"
120 fi
121
122 cd ${S}
123 export KMETA=${KMETA}
124
125 bbnote "do_kernel_metadata: for summary/debug, set KCONF_AUDIT_LEVEL > 0"
126
127 # if kernel tools are available in-tree, they are preferred
128 # and are placed on the path before any external tools. Unless
129 # the external tools flag is set, in that case we do nothing.
130 if [ -f "${S}/scripts/util/configme" ]; then
131 if [ -z "${EXTERNAL_KERNEL_TOOLS}" ]; then
132 PATH=${S}/scripts/util:${PATH}
133 fi
134 fi
135
136 # In a similar manner to the kernel itself:
137 #
138 # defconfig: $(obj)/conf
139 # ifeq ($(KBUILD_DEFCONFIG),)
140 # $< --defconfig $(Kconfig)
141 # else
142 # @echo "*** Default configuration is based on '$(KBUILD_DEFCONFIG)'"
143 # $(Q)$< --defconfig=arch/$(SRCARCH)/configs/$(KBUILD_DEFCONFIG) $(Kconfig)
144 # endif
145 #
146 # If a defconfig is specified via the KBUILD_DEFCONFIG variable, we copy it
147 # from the source tree, into a common location and normalized "defconfig" name,
148 # where the rest of the process will include and incoroporate it into the build
149 #
150 # If the fetcher has already placed a defconfig in WORKDIR (from the SRC_URI),
151 # we don't overwrite it, but instead warn the user that SRC_URI defconfigs take
152 # precendence.
153 #
154 if [ -n "${KBUILD_DEFCONFIG}" ]; then
155 if [ -f "${S}/arch/${ARCH}/configs/${KBUILD_DEFCONFIG}" ]; then
156 if [ -f "${WORKDIR}/defconfig" ]; then
157 # If the two defconfig's are different, warn that we overwrote the
158 # one already placed in WORKDIR
159 cmp "${WORKDIR}/defconfig" "${S}/arch/${ARCH}/configs/${KBUILD_DEFCONFIG}"
160 if [ $? -ne 0 ]; then
161 bbdebug 1 "detected SRC_URI or unpatched defconfig in WORKDIR. ${KBUILD_DEFCONFIG} copied over it"
162 fi
163 cp -f ${S}/arch/${ARCH}/configs/${KBUILD_DEFCONFIG} ${WORKDIR}/defconfig
164 else
165 cp -f ${S}/arch/${ARCH}/configs/${KBUILD_DEFCONFIG} ${WORKDIR}/defconfig
166 fi
167 in_tree_defconfig="${WORKDIR}/defconfig"
168 else
169 bbfatal "A KBUILD_DEFCONFIG '${KBUILD_DEFCONFIG}' was specified, but not present in the source tree (${S}/arch/${ARCH}/configs/)"
170 fi
171 fi
172
173 if [ "$mode" = "patch" ]; then
174 # was anyone trying to patch the kernel meta data ?, we need to do
175 # this here, since the scc commands migrate the .cfg fragments to the
176 # kernel source tree, where they'll be used later.
177 check_git_config
178 patches="${@" ".join(find_patches(d,'kernel-meta'))}"
179 for p in $patches; do
180 (
181 cd ${WORKDIR}/kernel-meta
182 git am -s $p
183 )
184 done
185 fi
186
187 sccs_from_src_uri="${@" ".join(find_sccs(d))}"
188 patches="${@" ".join(find_patches(d,''))}"
189 feat_dirs="${@" ".join(find_kernel_feature_dirs(d))}"
190
191 # a quick check to make sure we don't have duplicate defconfigs If
192 # there's a defconfig in the SRC_URI, did we also have one from the
193 # KBUILD_DEFCONFIG processing above ?
194 src_uri_defconfig=$(echo $sccs_from_src_uri | awk '(match($0, "defconfig") != 0) { print $0 }' RS=' ')
195 # drop and defconfig's from the src_uri variable, we captured it just above here if it existed
196 sccs_from_src_uri=$(echo $sccs_from_src_uri | awk '(match($0, "defconfig") == 0) { print $0 }' RS=' ')
197
198 if [ -n "$in_tree_defconfig" ]; then
199 sccs_defconfig=$in_tree_defconfig
200 if [ -n "$src_uri_defconfig" ]; then
201 bbwarn "[NOTE]: defconfig was supplied both via KBUILD_DEFCONFIG and SRC_URI. Dropping SRC_URI entry $src_uri_defconfig"
202 fi
203 else
204 # if we didn't have an in-tree one, make our defconfig the one
205 # from the src_uri. Note: there may not have been one from the
206 # src_uri, so this can be an empty variable.
207 sccs_defconfig=$src_uri_defconfig
208 fi
209 sccs="$sccs_from_src_uri"
210
211 # check for feature directories/repos/branches that were part of the
212 # SRC_URI. If they were supplied, we convert them into include directives
213 # for the update part of the process
214 for f in ${feat_dirs}; do
Andrew Geissler6aa7eec2023-03-03 12:41:14 -0600215 if [ -d "${WORKDIR}/$f/kernel-meta" ]; then
Patrick Williams92b42cb2022-09-03 06:53:57 -0500216 includes="$includes -I${WORKDIR}/$f/kernel-meta"
217 elif [ -d "${WORKDIR}/../oe-local-files/$f" ]; then
218 includes="$includes -I${WORKDIR}/../oe-local-files/$f"
219 elif [ -d "${WORKDIR}/$f" ]; then
220 includes="$includes -I${WORKDIR}/$f"
221 fi
222 done
223 for s in ${sccs} ${patches}; do
224 sdir=$(dirname $s)
225 includes="$includes -I${sdir}"
226 # if a SRC_URI passed patch or .scc has a subdir of "kernel-meta",
227 # then we add it to the search path
228 if [ -d "${sdir}/kernel-meta" ]; then
229 includes="$includes -I${sdir}/kernel-meta"
230 fi
231 done
232
233 # expand kernel features into their full path equivalents
234 bsp_definition=$(spp ${includes} --find -DKMACHINE=${KMACHINE} -DKTYPE=${LINUX_KERNEL_TYPE})
235 if [ -z "$bsp_definition" ]; then
236 if [ -z "$sccs_defconfig" ]; then
237 bbfatal_log "Could not locate BSP definition for ${KMACHINE}/${LINUX_KERNEL_TYPE} and no defconfig was provided"
238 fi
239 else
240 # if the bsp definition has "define KMETA_EXTERNAL_BSP t",
241 # then we need to set a flag that will instruct the next
242 # steps to use the BSP as both configuration and patches.
243 grep -q KMETA_EXTERNAL_BSP $bsp_definition
244 if [ $? -eq 0 ]; then
245 KMETA_EXTERNAL_BSPS="t"
246 fi
247 fi
248 meta_dir=$(kgit --meta)
249
250 KERNEL_FEATURES_FINAL=""
251 if [ -n "${KERNEL_FEATURES}" ]; then
252 for feature in ${KERNEL_FEATURES}; do
253 feature_found=f
254 for d in $includes; do
255 path_to_check=$(echo $d | sed 's/^-I//')
256 if [ "$feature_found" = "f" ] && [ -e "$path_to_check/$feature" ]; then
257 feature_found=t
258 fi
259 done
260 if [ "$feature_found" = "f" ]; then
261 if [ -n "${KERNEL_DANGLING_FEATURES_WARN_ONLY}" ]; then
262 bbwarn "Feature '$feature' not found, but KERNEL_DANGLING_FEATURES_WARN_ONLY is set"
263 bbwarn "This may cause runtime issues, dropping feature and allowing configuration to continue"
264 else
265 bberror "Feature '$feature' not found, this will cause configuration failures."
266 bberror "Check the SRC_URI for meta-data repositories or directories that may be missing"
267 bbfatal_log "Set KERNEL_DANGLING_FEATURES_WARN_ONLY to ignore this issue"
268 fi
269 else
270 KERNEL_FEATURES_FINAL="$KERNEL_FEATURES_FINAL $feature"
271 fi
272 done
273 fi
274
275 if [ "$mode" = "config" ]; then
276 # run1: pull all the configuration fragments, no matter where they come from
277 elements="`echo -n ${bsp_definition} $sccs_defconfig ${sccs} ${patches} $KERNEL_FEATURES_FINAL`"
278 if [ -n "${elements}" ]; then
279 echo "${bsp_definition}" > ${S}/${meta_dir}/bsp_definition
280 scc --force -o ${S}/${meta_dir}:cfg,merge,meta ${includes} $sccs_defconfig $bsp_definition $sccs $patches $KERNEL_FEATURES_FINAL
281 if [ $? -ne 0 ]; then
282 bbfatal_log "Could not generate configuration queue for ${KMACHINE}."
283 fi
284 fi
285 fi
286
287 # if KMETA_EXTERNAL_BSPS has been set, or it has been detected from
288 # the bsp definition, then we inject the bsp_definition into the
289 # patch phase below. we'll piggy back on the sccs variable.
290 if [ -n "${KMETA_EXTERNAL_BSPS}" ]; then
291 sccs="${bsp_definition} ${sccs}"
292 fi
293
294 if [ "$mode" = "patch" ]; then
295 # run2: only generate patches for elements that have been passed on the SRC_URI
296 elements="`echo -n ${sccs} ${patches} $KERNEL_FEATURES_FINAL`"
297 if [ -n "${elements}" ]; then
298 scc --force -o ${S}/${meta_dir}:patch --cmds patch ${includes} ${sccs} ${patches} $KERNEL_FEATURES_FINAL
299 if [ $? -ne 0 ]; then
300 bbfatal_log "Could not generate configuration queue for ${KMACHINE}."
301 fi
302 fi
303 fi
304
305 if [ ${KCONF_AUDIT_LEVEL} -gt 0 ]; then
306 bbnote "kernel meta data summary for ${KMACHINE} (${LINUX_KERNEL_TYPE}):"
307 bbnote "======================================================================"
308 if [ -n "${KMETA_EXTERNAL_BSPS}" ]; then
309 bbnote "Non kernel-cache (external) bsp"
310 fi
311 bbnote "BSP entry point / definition: $bsp_definition"
312 if [ -n "$in_tree_defconfig" ]; then
313 bbnote "KBUILD_DEFCONFIG: ${KBUILD_DEFCONFIG}"
314 fi
315 bbnote "Fragments from SRC_URI: $sccs_from_src_uri"
316 bbnote "KERNEL_FEATURES: $KERNEL_FEATURES_FINAL"
317 bbnote "Final scc/cfg list: $sccs_defconfig $bsp_definition $sccs $KERNEL_FEATURES_FINAL"
318 fi
319
320 set -e
321}
322
323do_patch() {
324 set +e
325 cd ${S}
326
327 check_git_config
328 meta_dir=$(kgit --meta)
329 (cd ${meta_dir}; ln -sf patch.queue series)
330 if [ -f "${meta_dir}/series" ]; then
331 kgit_extra_args=""
332 if [ "${KERNEL_DEBUG_TIMESTAMPS}" != "1" ]; then
333 kgit_extra_args="--commit-sha author"
334 fi
335 kgit-s2q --gen -v $kgit_extra_args --patches .kernel-meta/
336 if [ $? -ne 0 ]; then
337 bberror "Could not apply patches for ${KMACHINE}."
338 bbfatal_log "Patch failures can be resolved in the linux source directory ${S})"
339 fi
340 fi
341
342 if [ -f "${meta_dir}/merge.queue" ]; then
343 # we need to merge all these branches
344 for b in $(cat ${meta_dir}/merge.queue); do
345 git show-ref --verify --quiet refs/heads/${b}
346 if [ $? -eq 0 ]; then
347 bbnote "Merging branch ${b}"
348 git merge -q --no-ff -m "Merge branch ${b}" ${b}
349 else
350 bbfatal "branch ${b} does not exist, cannot merge"
351 fi
352 done
353 fi
354
355 set -e
356}
357
358do_kernel_checkout() {
359 set +e
360
361 source_dir=`echo ${S} | sed 's%/$%%'`
362 source_workdir="${WORKDIR}/git"
363 if [ -d "${WORKDIR}/git/" ]; then
364 # case: git repository
365 # if S is WORKDIR/git, then we shouldn't be moving or deleting the tree.
366 if [ "${source_dir}" != "${source_workdir}" ]; then
367 if [ -d "${source_workdir}/.git" ]; then
368 # regular git repository with .git
369 rm -rf ${S}
370 mv ${WORKDIR}/git ${S}
371 else
372 # create source for bare cloned git repository
373 git clone ${WORKDIR}/git ${S}
374 rm -rf ${WORKDIR}/git
375 fi
376 fi
377 cd ${S}
378
379 # convert any remote branches to local tracking ones
380 for i in `git branch -a --no-color | grep remotes | grep -v HEAD`; do
381 b=`echo $i | cut -d' ' -f2 | sed 's%remotes/origin/%%'`;
382 git show-ref --quiet --verify -- "refs/heads/$b"
383 if [ $? -ne 0 ]; then
384 git branch $b $i > /dev/null
385 fi
386 done
387
388 # Create a working tree copy of the kernel by checking out a branch
389 machine_branch="${@ get_machine_branch(d, "${KBRANCH}" )}"
390
391 # checkout and clobber any unimportant files
392 git checkout -f ${machine_branch}
393 else
394 # case: we have no git repository at all.
395 # To support low bandwidth options for building the kernel, we'll just
396 # convert the tree to a git repo and let the rest of the process work unchanged
397
398 # if ${S} hasn't been set to the proper subdirectory a default of "linux" is
399 # used, but we can't initialize that empty directory. So check it and throw a
400 # clear error
401
402 cd ${S}
403 if [ ! -f "Makefile" ]; then
404 bberror "S is not set to the linux source directory. Check "
405 bbfatal "the recipe and set S to the proper extracted subdirectory"
406 fi
407 rm -f .gitignore
408 git init
409 check_git_config
410 git add .
411 git commit -q -m "baseline commit: creating repo for ${PN}-${PV}"
412 git clean -d -f
413 fi
414
415 set -e
416}
417do_kernel_checkout[dirs] = "${S} ${WORKDIR}"
418
419addtask kernel_checkout before do_kernel_metadata after do_symlink_kernsrc
420addtask kernel_metadata after do_validate_branches do_unpack before do_patch
421do_kernel_metadata[depends] = "kern-tools-native:do_populate_sysroot"
422do_kernel_metadata[file-checksums] = " ${@get_dirs_with_fragments(d)}"
423do_validate_branches[depends] = "kern-tools-native:do_populate_sysroot"
424
425do_kernel_configme[depends] += "virtual/${TARGET_PREFIX}binutils:do_populate_sysroot"
426do_kernel_configme[depends] += "virtual/${TARGET_PREFIX}gcc:do_populate_sysroot"
427do_kernel_configme[depends] += "bc-native:do_populate_sysroot bison-native:do_populate_sysroot"
428do_kernel_configme[depends] += "kern-tools-native:do_populate_sysroot"
429do_kernel_configme[dirs] += "${S} ${B}"
430do_kernel_configme() {
431 do_kernel_metadata config
432
433 # translate the kconfig_mode into something that merge_config.sh
434 # understands
435 case ${KCONFIG_MODE} in
436 *allnoconfig)
437 config_flags="-n"
438 ;;
439 *alldefconfig)
440 config_flags=""
441 ;;
442 *)
443 if [ -f ${WORKDIR}/defconfig ]; then
444 config_flags="-n"
445 fi
446 ;;
447 esac
448
449 cd ${S}
450
451 meta_dir=$(kgit --meta)
452 configs="$(scc --configs -o ${meta_dir})"
453 if [ $? -ne 0 ]; then
454 bberror "${configs}"
455 bbfatal_log "Could not find configuration queue (${meta_dir}/config.queue)"
456 fi
457
Patrick Williams520786c2023-06-25 16:20:36 -0500458 CFLAGS="${CFLAGS} ${TOOLCHAIN_OPTIONS}" HOSTCC="${BUILD_CC} ${BUILD_CFLAGS} ${BUILD_LDFLAGS}" HOSTCPP="${BUILD_CPP}" CC="${KERNEL_CC}" LD="${KERNEL_LD}" OBJCOPY="${KERNEL_OBJCOPY}" STRIP="${KERNEL_STRIP}" ARCH=${ARCH} merge_config.sh -O ${B} ${config_flags} ${configs} > ${meta_dir}/cfg/merge_config_build.log 2>&1
Patrick Williams92b42cb2022-09-03 06:53:57 -0500459 if [ $? -ne 0 -o ! -f ${B}/.config ]; then
460 bberror "Could not generate a .config for ${KMACHINE}-${LINUX_KERNEL_TYPE}"
461 if [ ${KCONF_AUDIT_LEVEL} -gt 1 ]; then
462 bbfatal_log "`cat ${meta_dir}/cfg/merge_config_build.log`"
463 else
464 bbfatal_log "Details can be found at: ${S}/${meta_dir}/cfg/merge_config_build.log"
465 fi
466 fi
467
468 if [ ! -z "${LINUX_VERSION_EXTENSION}" ]; then
469 echo "# Global settings from linux recipe" >> ${B}/.config
470 echo "CONFIG_LOCALVERSION="\"${LINUX_VERSION_EXTENSION}\" >> ${B}/.config
471 fi
472}
473
474addtask kernel_configme before do_configure after do_patch
475addtask config_analysis
476
477do_config_analysis[depends] = "virtual/kernel:do_configure"
478do_config_analysis[depends] += "kern-tools-native:do_populate_sysroot"
479
480CONFIG_AUDIT_FILE ?= "${WORKDIR}/config-audit.txt"
481CONFIG_ANALYSIS_FILE ?= "${WORKDIR}/config-analysis.txt"
482
483python do_config_analysis() {
484 import re, string, sys, subprocess
485
486 s = d.getVar('S')
487
488 env = os.environ.copy()
489 env['PATH'] = "%s:%s%s" % (d.getVar('PATH'), s, "/scripts/util/")
490 env['LD'] = d.getVar('KERNEL_LD')
491 env['CC'] = d.getVar('KERNEL_CC')
Andrew Geissler6aa7eec2023-03-03 12:41:14 -0600492 env['OBJCOPY'] = d.getVar('KERNEL_OBJCOPY')
Patrick Williams520786c2023-06-25 16:20:36 -0500493 env['STRIP'] = d.getVar('KERNEL_STRIP')
Patrick Williams92b42cb2022-09-03 06:53:57 -0500494 env['ARCH'] = d.getVar('ARCH')
495 env['srctree'] = s
496
497 # read specific symbols from the kernel recipe or from local.conf
498 # i.e.: CONFIG_ANALYSIS:pn-linux-yocto-dev = 'NF_CONNTRACK LOCALVERSION'
499 config = d.getVar( 'CONFIG_ANALYSIS' )
500 if not config:
501 config = [ "" ]
502 else:
503 config = config.split()
504
505 for c in config:
506 for action in ["analysis","audit"]:
507 if action == "analysis":
508 try:
509 analysis = subprocess.check_output(['symbol_why.py', '--dotconfig', '{}'.format( d.getVar('B') + '/.config' ), '--blame', c], cwd=s, env=env ).decode('utf-8')
510 except subprocess.CalledProcessError as e:
Patrick Williams2390b1b2022-11-03 13:47:49 -0500511 bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
Patrick Williams92b42cb2022-09-03 06:53:57 -0500512
513 outfile = d.getVar( 'CONFIG_ANALYSIS_FILE' )
514
515 if action == "audit":
516 try:
517 analysis = subprocess.check_output(['symbol_why.py', '--dotconfig', '{}'.format( d.getVar('B') + '/.config' ), '--summary', '--extended', '--sanity', c], cwd=s, env=env ).decode('utf-8')
518 except subprocess.CalledProcessError as e:
Patrick Williams2390b1b2022-11-03 13:47:49 -0500519 bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
Patrick Williams92b42cb2022-09-03 06:53:57 -0500520
521 outfile = d.getVar( 'CONFIG_AUDIT_FILE' )
522
523 if c:
524 outdir = os.path.dirname( outfile )
525 outname = os.path.basename( outfile )
526 outfile = outdir + '/'+ c + '-' + outname
527
528 if config and os.path.isfile(outfile):
529 os.remove(outfile)
530
531 with open(outfile, 'w+') as f:
532 f.write( analysis )
533
534 bb.warn( "Configuration {} executed, see: {} for details".format(action,outfile ))
535 if c:
536 bb.warn( analysis )
537}
538
539python do_kernel_configcheck() {
540 import re, string, sys, subprocess
541
542 s = d.getVar('S')
543
544 # if KMETA isn't set globally by a recipe using this routine, use kgit to
545 # locate or create the meta directory. Otherwise, kconf_check is not
546 # passed a valid meta-series for processing
547 kmeta = d.getVar("KMETA")
548 if not kmeta or not os.path.exists('{}/{}'.format(s,kmeta)):
549 kmeta = subprocess.check_output(['kgit', '--meta'], cwd=d.getVar('S')).decode('utf-8').rstrip()
550
551 env = os.environ.copy()
552 env['PATH'] = "%s:%s%s" % (d.getVar('PATH'), s, "/scripts/util/")
553 env['LD'] = d.getVar('KERNEL_LD')
554 env['CC'] = d.getVar('KERNEL_CC')
Andrew Geissler6aa7eec2023-03-03 12:41:14 -0600555 env['OBJCOPY'] = d.getVar('KERNEL_OBJCOPY')
Patrick Williams520786c2023-06-25 16:20:36 -0500556 env['STRIP'] = d.getVar('KERNEL_STRIP')
Patrick Williams92b42cb2022-09-03 06:53:57 -0500557 env['ARCH'] = d.getVar('ARCH')
558 env['srctree'] = s
559
560 try:
561 configs = subprocess.check_output(['scc', '--configs', '-o', s + '/.kernel-meta'], env=env).decode('utf-8')
562 except subprocess.CalledProcessError as e:
563 bb.fatal( "Cannot gather config fragments for audit: %s" % e.output.decode("utf-8") )
564
565 config_check_visibility = int(d.getVar("KCONF_AUDIT_LEVEL") or 0)
566 bsp_check_visibility = int(d.getVar("KCONF_BSP_AUDIT_LEVEL") or 0)
567 kmeta_audit_werror = d.getVar("KMETA_AUDIT_WERROR") or ""
568 warnings_detected = False
569
570 # if config check visibility is "1", that's the lowest level of audit. So
571 # we add the --classify option to the run, since classification will
572 # streamline the output to only report options that could be boot issues,
573 # or are otherwise required for proper operation.
574 extra_params = ""
575 if config_check_visibility == 1:
576 extra_params = "--classify"
577
578 # category #1: mismatches
579 try:
580 analysis = subprocess.check_output(['symbol_why.py', '--dotconfig', '{}'.format( d.getVar('B') + '/.config' ), '--mismatches', extra_params], cwd=s, env=env ).decode('utf-8')
581 except subprocess.CalledProcessError as e:
Patrick Williams2390b1b2022-11-03 13:47:49 -0500582 bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
Patrick Williams92b42cb2022-09-03 06:53:57 -0500583
584 if analysis:
585 outfile = "{}/{}/cfg/mismatch.txt".format( s, kmeta )
586 if os.path.isfile(outfile):
587 os.remove(outfile)
588 with open(outfile, 'w+') as f:
589 f.write( analysis )
590
591 if config_check_visibility and os.stat(outfile).st_size > 0:
592 with open (outfile, "r") as myfile:
593 results = myfile.read()
594 bb.warn( "[kernel config]: specified values did not make it into the kernel's final configuration:\n\n%s" % results)
595 warnings_detected = True
596
597 # category #2: invalid fragment elements
598 extra_params = ""
599 if bsp_check_visibility > 1:
600 extra_params = "--strict"
601 try:
602 analysis = subprocess.check_output(['symbol_why.py', '--dotconfig', '{}'.format( d.getVar('B') + '/.config' ), '--invalid', extra_params], cwd=s, env=env ).decode('utf-8')
603 except subprocess.CalledProcessError as e:
Patrick Williams2390b1b2022-11-03 13:47:49 -0500604 bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
Patrick Williams92b42cb2022-09-03 06:53:57 -0500605
606 if analysis:
607 outfile = "{}/{}/cfg/invalid.txt".format(s,kmeta)
608 if os.path.isfile(outfile):
609 os.remove(outfile)
610 with open(outfile, 'w+') as f:
611 f.write( analysis )
612
613 if bsp_check_visibility and os.stat(outfile).st_size > 0:
614 with open (outfile, "r") as myfile:
615 results = myfile.read()
616 bb.warn( "[kernel config]: This BSP contains fragments with warnings:\n\n%s" % results)
617 warnings_detected = True
618
619 # category #3: redefined options (this is pretty verbose and is debug only)
620 try:
621 analysis = subprocess.check_output(['symbol_why.py', '--dotconfig', '{}'.format( d.getVar('B') + '/.config' ), '--sanity'], cwd=s, env=env ).decode('utf-8')
622 except subprocess.CalledProcessError as e:
Patrick Williams2390b1b2022-11-03 13:47:49 -0500623 bb.fatal( "config analysis failed when running '%s': %s" % (" ".join(e.cmd), e.output.decode('utf-8')))
Patrick Williams92b42cb2022-09-03 06:53:57 -0500624
625 if analysis:
626 outfile = "{}/{}/cfg/redefinition.txt".format(s,kmeta)
627 if os.path.isfile(outfile):
628 os.remove(outfile)
629 with open(outfile, 'w+') as f:
630 f.write( analysis )
631
632 # if the audit level is greater than two, we report if a fragment has overriden
633 # a value from a base fragment. This is really only used for new kernel introduction
634 if bsp_check_visibility > 2 and os.stat(outfile).st_size > 0:
635 with open (outfile, "r") as myfile:
636 results = myfile.read()
637 bb.warn( "[kernel config]: This BSP has configuration options defined in more than one config, with differing values:\n\n%s" % results)
638 warnings_detected = True
639
640 if warnings_detected and kmeta_audit_werror:
641 bb.fatal( "configuration warnings detected, werror is set, promoting to fatal" )
642}
643
644# Ensure that the branches (BSP and meta) are on the locations specified by
645# their SRCREV values. If they are NOT on the right commits, the branches
646# are corrected to the proper commit.
647do_validate_branches() {
648 set +e
649 cd ${S}
650
651 machine_branch="${@ get_machine_branch(d, "${KBRANCH}" )}"
652 machine_srcrev="${SRCREV_machine}"
653
654 # if SRCREV is AUTOREV it shows up as AUTOINC there's nothing to
655 # check and we can exit early
656 if [ "${machine_srcrev}" = "AUTOINC" ]; then
657 linux_yocto_dev='${@oe.utils.conditional("PREFERRED_PROVIDER_virtual/kernel", "linux-yocto-dev", "1", "", d)}'
658 if [ -n "$linux_yocto_dev" ]; then
659 git checkout -q -f ${machine_branch}
660 ver=$(grep "^VERSION =" ${S}/Makefile | sed s/.*=\ *//)
661 patchlevel=$(grep "^PATCHLEVEL =" ${S}/Makefile | sed s/.*=\ *//)
662 sublevel=$(grep "^SUBLEVEL =" ${S}/Makefile | sed s/.*=\ *//)
663 kver="$ver.$patchlevel"
664 bbnote "dev kernel: performing version -> branch -> SRCREV validation"
665 bbnote "dev kernel: recipe version ${LINUX_VERSION}, src version: $kver"
666 echo "${LINUX_VERSION}" | grep -q $kver
667 if [ $? -ne 0 ]; then
668 version="$(echo ${LINUX_VERSION} | sed 's/\+.*$//g')"
669 versioned_branch="v$version/$machine_branch"
670
671 machine_branch=$versioned_branch
672 force_srcrev="$(git rev-parse $machine_branch 2> /dev/null)"
673 if [ $? -ne 0 ]; then
674 bbfatal "kernel version mismatch detected, and no valid branch $machine_branch detected"
675 fi
676
677 bbnote "dev kernel: adjusting branch to $machine_branch, srcrev to: $force_srcrev"
678 fi
679 else
680 bbnote "SRCREV validation is not required for AUTOREV"
681 fi
682 elif [ "${machine_srcrev}" = "" ]; then
683 if [ "${SRCREV}" != "AUTOINC" ] && [ "${SRCREV}" != "INVALID" ]; then
684 # SRCREV_machine_<MACHINE> was not set. This means that a custom recipe
685 # that doesn't use the SRCREV_FORMAT "machine_meta" is being built. In
686 # this case, we need to reset to the give SRCREV before heading to patching
687 bbnote "custom recipe is being built, forcing SRCREV to ${SRCREV}"
688 force_srcrev="${SRCREV}"
689 fi
690 else
691 git cat-file -t ${machine_srcrev} > /dev/null
692 if [ $? -ne 0 ]; then
693 bberror "${machine_srcrev} is not a valid commit ID."
694 bbfatal_log "The kernel source tree may be out of sync"
695 fi
696 force_srcrev=${machine_srcrev}
697 fi
698
699 git checkout -q -f ${machine_branch}
700 if [ -n "${force_srcrev}" ]; then
701 # see if the branch we are about to patch has been properly reset to the defined
702 # SRCREV .. if not, we reset it.
703 branch_head=`git rev-parse HEAD`
704 if [ "${force_srcrev}" != "${branch_head}" ]; then
705 current_branch=`git rev-parse --abbrev-ref HEAD`
706 git branch "$current_branch-orig"
707 git reset --hard ${force_srcrev}
708 # We've checked out HEAD, make sure we cleanup kgit-s2q fence post check
709 # so the patches are applied as expected otherwise no patching
710 # would be done in some corner cases.
711 kgit-s2q --clean
712 fi
713 fi
714
715 set -e
716}
717
718OE_TERMINAL_EXPORTS += "KBUILD_OUTPUT"
719KBUILD_OUTPUT = "${B}"
720
721python () {
722 # If diffconfig is available, ensure it runs after kernel_configme
723 if 'do_diffconfig' in d:
724 bb.build.addtask('do_diffconfig', None, 'do_kernel_configme', d)
725
726 externalsrc = d.getVar('EXTERNALSRC')
727 if externalsrc:
728 # If we deltask do_patch, do_kernel_configme is left without
729 # dependencies and runs too early
730 d.setVarFlag('do_kernel_configme', 'deps', (d.getVarFlag('do_kernel_configme', 'deps', False) or []) + ['do_unpack'])
731}
732
733# extra tasks
734addtask kernel_version_sanity_check after do_kernel_metadata do_kernel_checkout before do_compile
735addtask validate_branches before do_patch after do_kernel_checkout
736addtask kernel_configcheck after do_configure before do_compile