-
Notifications
You must be signed in to change notification settings - Fork 7.2k
/
Copy pathcheck_compliance.py
executable file
·2078 lines (1710 loc) · 79 KB
/
check_compliance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) 2018,2020 Intel Corporation
# Copyright (c) 2022 Nordic Semiconductor ASA
# SPDX-License-Identifier: Apache-2.0
import argparse
import collections
from itertools import takewhile
import json
import logging
import os
from pathlib import Path
import platform
import re
import subprocess
import sys
import tempfile
import traceback
import shlex
import shutil
import textwrap
import unidiff
from yamllint import config, linter
from junitparser import TestCase, TestSuite, JUnitXml, Skipped, Error, Failure
import magic
from west.manifest import Manifest
from west.manifest import ManifestProject
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from get_maintainer import Maintainers, MaintainersError
import list_boards
import list_hardware
logger = None
def git(*args, cwd=None, ignore_non_zero=False):
# Helper for running a Git command. Returns the rstrip()ed stdout output.
# Called like git("diff"). Exits with SystemError (raised by sys.exit()) on
# errors if 'ignore_non_zero' is set to False (default: False). 'cwd' is the
# working directory to use (default: current directory).
git_cmd = ("git",) + args
try:
cp = subprocess.run(git_cmd, capture_output=True, cwd=cwd)
except OSError as e:
err(f"failed to run '{cmd2str(git_cmd)}': {e}")
if not ignore_non_zero and (cp.returncode or cp.stderr):
err(f"'{cmd2str(git_cmd)}' exited with status {cp.returncode} and/or "
f"wrote to stderr.\n"
f"==stdout==\n"
f"{cp.stdout.decode('utf-8')}\n"
f"==stderr==\n"
f"{cp.stderr.decode('utf-8')}\n")
return cp.stdout.decode("utf-8").rstrip()
def get_shas(refspec):
"""
Returns the list of Git SHAs for 'refspec'.
:param refspec:
:return:
"""
return git('rev-list',
f'--max-count={-1 if "." in refspec else 1}', refspec).split()
def get_files(filter=None, paths=None):
filter_arg = (f'--diff-filter={filter}',) if filter else ()
paths_arg = ('--', *paths) if paths else ()
out = git('diff', '--name-only', *filter_arg, COMMIT_RANGE, *paths_arg)
files = out.splitlines()
for file in list(files):
if not os.path.isfile(os.path.join(GIT_TOP, file)):
# Drop submodule directories from the list.
files.remove(file)
return files
class FmtdFailure(Failure):
def __init__(
self, severity, title, file, line=None, col=None, desc="", end_line=None, end_col=None
):
self.severity = severity
self.title = title
self.file = file
self.line = line
self.col = col
self.end_line = end_line
self.end_col = end_col
self.desc = desc
description = f':{desc}' if desc else ''
msg_body = desc or title
txt = f'\n{title}{description}\nFile:{file}' + \
(f'\nLine:{line}' if line else '') + \
(f'\nColumn:{col}' if col else '') + \
(f'\nEndLine:{end_line}' if end_line else '') + \
(f'\nEndColumn:{end_col}' if end_col else '')
msg = f'{file}' + (f':{line}' if line else '') + f' {msg_body}'
typ = severity.lower()
super().__init__(msg, typ)
self.text = txt
class ComplianceTest:
"""
Base class for tests. Inheriting classes should have a run() method and set
these class variables:
name:
Test name
doc:
Link to documentation related to what's being tested
path_hint:
The path the test runs itself in. This is just informative and used in
the message that gets printed when running the test.
There are two magic strings that can be used instead of a path:
- The magic string "<zephyr-base>" can be used to refer to the
environment variable ZEPHYR_BASE or, when missing, the calculated base of
the zephyr tree
- The magic string "<git-top>" refers to the top-level repository
directory. This avoids running 'git' to find the top-level directory
before main() runs (class variable assignments run when the 'class ...'
statement runs). That avoids swallowing errors, because main() reports
them to GitHub
"""
def __init__(self):
self.case = TestCase(type(self).name, "Guidelines")
# This is necessary because Failure can be subclassed, but since it is
# always restored form the element tree, the subclass is lost upon
# restoring
self.fmtd_failures = []
def _result(self, res, text):
res.text = text.rstrip()
self.case.result += [res]
def error(self, text, msg=None, type_="error"):
"""
Signals a problem with running the test, with message 'msg'.
Raises an exception internally, so you do not need to put a 'return'
after error().
"""
err = Error(msg or f'{type(self).name} error', type_)
self._result(err, text)
raise EndTest
def skip(self, text, msg=None, type_="skip"):
"""
Signals that the test should be skipped, with message 'msg'.
Raises an exception internally, so you do not need to put a 'return'
after skip().
"""
skpd = Skipped(msg or f'{type(self).name} skipped', type_)
self._result(skpd, text)
raise EndTest
def failure(self, text, msg=None, type_="failure"):
"""
Signals that the test failed, with message 'msg'. Can be called many
times within the same test to report multiple failures.
"""
fail = Failure(msg or f'{type(self).name} issues', type_)
self._result(fail, text)
def fmtd_failure(
self, severity, title, file, line=None, col=None, desc="", end_line=None, end_col=None
):
"""
Signals that the test failed, and store the information in a formatted
standardized manner. Can be called many times within the same test to
report multiple failures.
"""
fail = FmtdFailure(severity, title, file, line, col, desc, end_line, end_col)
self._result(fail, fail.text)
self.fmtd_failures.append(fail)
class EndTest(Exception):
"""
Raised by ComplianceTest.error()/skip() to end the test.
Tests can raise EndTest themselves to immediately end the test, e.g. from
within a nested function call.
"""
class CheckPatch(ComplianceTest):
"""
Runs checkpatch and reports found issues
"""
name = "Checkpatch"
doc = "See https://docs.zephyrproject.org/latest/contribute/guidelines.html#coding-style for more details."
path_hint = "<git-top>"
def run(self):
checkpatch = os.path.join(ZEPHYR_BASE, 'scripts', 'checkpatch.pl')
if not os.path.exists(checkpatch):
self.skip(f'{checkpatch} not found')
# check for Perl installation on Windows
if os.name == 'nt':
if not shutil.which('perl'):
self.failure("Perl not installed - required for checkpatch.pl. Please install Perl or add to PATH.")
return
else:
cmd = ['perl', checkpatch]
# Linux and MacOS
else:
cmd = [checkpatch]
cmd.extend(['--mailback', '--no-tree', '-'])
diff = subprocess.Popen(('git', 'diff', '--no-ext-diff', COMMIT_RANGE),
stdout=subprocess.PIPE,
cwd=GIT_TOP)
try:
subprocess.run(cmd,
check=True,
stdin=diff.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=False, cwd=GIT_TOP)
except subprocess.CalledProcessError as ex:
output = ex.output.decode("utf-8")
regex = r'^\s*\S+:(\d+):\s*(ERROR|WARNING):(.+?):(.+)(?:\n|\r\n?)+' \
r'^\s*#(\d+):\s*FILE:\s*(.+):(\d+):'
matches = re.findall(regex, output, re.MULTILINE)
# add a guard here for excessive number of errors, do not try and
# process each one of them and instead push this as one failure.
if len(matches) > 500:
self.failure(output)
return
for m in matches:
self.fmtd_failure(m[1].lower(), m[2], m[5], m[6], col=None,
desc=m[3])
# If the regex has not matched add the whole output as a failure
if len(matches) == 0:
self.failure(output)
class BoardYmlCheck(ComplianceTest):
"""
Check the board.yml files
"""
name = "BoardYml"
doc = "Check the board.yml file format"
path_hint = "<zephyr-base>"
def check_board_file(self, file, vendor_prefixes):
"""Validate a single board file."""
with open(file) as fp:
for line_num, line in enumerate(fp.readlines(), start=1):
if "vendor:" in line:
_, vnd = line.strip().split(":", 2)
vnd = vnd.strip()
if vnd not in vendor_prefixes:
desc = f"invalid vendor: {vnd}"
self.fmtd_failure("error", "BoardYml", file, line_num,
desc=desc)
def run(self):
vendor_prefixes = ["others"]
with open(os.path.join(ZEPHYR_BASE, "dts", "bindings", "vendor-prefixes.txt")) as fp:
for line in fp.readlines():
line = line.strip()
if not line or line.startswith("#"):
continue
try:
vendor, _ = line.split("\t", 2)
vendor_prefixes.append(vendor)
except ValueError:
self.error(f"Invalid line in vendor-prefixes.txt:\"{line}\".")
self.error("Did you forget the tab character?")
path = Path(ZEPHYR_BASE)
for file in path.glob("**/board.yml"):
self.check_board_file(file, vendor_prefixes)
class ClangFormatCheck(ComplianceTest):
"""
Check if clang-format reports any issues
"""
name = "ClangFormat"
doc = "See https://docs.zephyrproject.org/latest/contribute/guidelines.html#clang-format for more details."
path_hint = "<git-top>"
def run(self):
exe = f"clang-format-diff.{'exe' if platform.system() == 'Windows' else 'py'}"
for file in get_files():
if Path(file).suffix not in ['.c', '.h']:
continue
diff = subprocess.Popen(('git', 'diff', '-U0', '--no-color', COMMIT_RANGE, '--', file),
stdout=subprocess.PIPE,
cwd=GIT_TOP)
try:
subprocess.run((exe, '-p1'),
check=True,
stdin=diff.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=GIT_TOP)
except subprocess.CalledProcessError as ex:
patchset = unidiff.PatchSet.from_string(ex.output, encoding="utf-8")
for patch in patchset:
for hunk in patch:
# Strip the before and after context
before = next(i for i,v in enumerate(hunk) if str(v).startswith(('-', '+')))
after = next(i for i,v in enumerate(reversed(hunk)) if str(v).startswith(('-', '+')))
msg = "".join([str(l) for l in hunk[before:-after or None]])
# show the hunk at the last line
self.fmtd_failure("notice",
"You may want to run clang-format on this change",
file, line=hunk.source_start + hunk.source_length - after,
desc=f'\r\n{msg}')
class DevicetreeBindingsCheck(ComplianceTest):
"""
Checks if we are introducing any unwanted properties in Devicetree Bindings.
"""
name = "DevicetreeBindings"
doc = "See https://docs.zephyrproject.org/latest/build/dts/bindings.html for more details."
path_hint = "<zephyr-base>"
def run(self, full=True):
dts_bindings = self.parse_dt_bindings()
for dts_binding in dts_bindings:
self.required_false_check(dts_binding)
def parse_dt_bindings(self):
"""
Returns a list of dts/bindings/**/*.yaml files
"""
dt_bindings = []
for file_name in get_files(filter="d"):
if 'dts/bindings/' in file_name and file_name.endswith('.yaml'):
dt_bindings.append(file_name)
return dt_bindings
def required_false_check(self, dts_binding):
with open(dts_binding) as file:
for line_number, line in enumerate(file, 1):
if 'required: false' in line:
self.fmtd_failure(
'warning', 'Devicetree Bindings', dts_binding,
line_number, col=None,
desc="'required: false' is redundant, please remove")
class KconfigCheck(ComplianceTest):
"""
Checks is we are introducing any new warnings/errors with Kconfig,
for example using undefined Kconfig variables.
"""
name = "Kconfig"
doc = "See https://docs.zephyrproject.org/latest/build/kconfig/tips.html for more details."
path_hint = "<zephyr-base>"
# Top-level Kconfig file. The path can be relative to srctree (ZEPHYR_BASE).
FILENAME = "Kconfig"
# Kconfig symbol prefix/namespace.
CONFIG_ = "CONFIG_"
def run(self):
kconf = self.parse_kconfig()
self.check_top_menu_not_too_long(kconf)
self.check_no_pointless_menuconfigs(kconf)
self.check_no_undef_within_kconfig(kconf)
self.check_no_redefined_in_defconfig(kconf)
self.check_no_enable_in_boolean_prompt(kconf)
self.check_soc_name_sync(kconf)
self.check_no_undef_outside_kconfig(kconf)
self.check_disallowed_defconfigs(kconf)
def get_modules(self, modules_file, sysbuild_modules_file, settings_file):
"""
Get a list of modules and put them in a file that is parsed by
Kconfig
This is needed to complete Kconfig sanity tests.
"""
# Invoke the script directly using the Python executable since this is
# not a module nor a pip-installed Python utility
zephyr_module_path = os.path.join(ZEPHYR_BASE, "scripts",
"zephyr_module.py")
cmd = [sys.executable, zephyr_module_path,
'--kconfig-out', modules_file,
'--sysbuild-kconfig-out', sysbuild_modules_file,
'--settings-out', settings_file]
try:
subprocess.run(cmd, check=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
self.error(ex.output.decode("utf-8"))
modules_dir = ZEPHYR_BASE + '/modules'
modules = [name for name in os.listdir(modules_dir) if
os.path.exists(os.path.join(modules_dir, name, 'Kconfig'))]
with open(modules_file, 'r') as fp_module_file:
content = fp_module_file.read()
with open(modules_file, 'w') as fp_module_file:
for module in modules:
fp_module_file.write("ZEPHYR_{}_KCONFIG = {}\n".format(
re.sub('[^a-zA-Z0-9]', '_', module).upper(),
modules_dir + '/' + module + '/Kconfig'
))
fp_module_file.write(content)
def get_module_setting_root(self, root, settings_file):
"""
Parse the Zephyr module generated settings file given by 'settings_file'
and return all root settings defined by 'root'.
"""
# Invoke the script directly using the Python executable since this is
# not a module nor a pip-installed Python utility
root_paths = []
if os.path.exists(settings_file):
with open(settings_file, 'r') as fp_setting_file:
content = fp_setting_file.read()
lines = content.strip().split('\n')
for line in lines:
root = root.upper()
if line.startswith(f'"{root}_ROOT":'):
_, root_path = line.split(":", 1)
root_paths.append(Path(root_path.strip('"')))
return root_paths
def get_kconfig_dts(self, kconfig_dts_file, settings_file):
"""
Generate the Kconfig.dts using dts/bindings as the source.
This is needed to complete Kconfig compliance tests.
"""
# Invoke the script directly using the Python executable since this is
# not a module nor a pip-installed Python utility
zephyr_drv_kconfig_path = os.path.join(ZEPHYR_BASE, "scripts", "dts",
"gen_driver_kconfig_dts.py")
binding_paths = []
binding_paths.append(os.path.join(ZEPHYR_BASE, "dts", "bindings"))
dts_root_paths = self.get_module_setting_root('dts', settings_file)
for p in dts_root_paths:
binding_paths.append(p / "dts" / "bindings")
cmd = [sys.executable, zephyr_drv_kconfig_path,
'--kconfig-out', kconfig_dts_file, '--bindings-dirs']
for binding_path in binding_paths:
cmd.append(binding_path)
try:
subprocess.run(cmd, check=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
self.error(ex.output.decode("utf-8"))
def get_v2_model(self, kconfig_dir, settings_file):
"""
Get lists of v2 boards and SoCs and put them in a file that is parsed by
Kconfig
This is needed to complete Kconfig sanity tests.
"""
os.environ['HWM_SCHEME'] = 'v2'
os.environ["KCONFIG_BOARD_DIR"] = os.path.join(kconfig_dir, 'boards')
os.makedirs(os.path.join(kconfig_dir, 'boards'), exist_ok=True)
os.makedirs(os.path.join(kconfig_dir, 'soc'), exist_ok=True)
os.makedirs(os.path.join(kconfig_dir, 'arch'), exist_ok=True)
kconfig_file = os.path.join(kconfig_dir, 'boards', 'Kconfig')
kconfig_boards_file = os.path.join(kconfig_dir, 'boards', 'Kconfig.boards')
kconfig_sysbuild_file = os.path.join(kconfig_dir, 'boards', 'Kconfig.sysbuild')
kconfig_defconfig_file = os.path.join(kconfig_dir, 'boards', 'Kconfig.defconfig')
board_roots = self.get_module_setting_root('board', settings_file)
board_roots.insert(0, Path(ZEPHYR_BASE))
soc_roots = self.get_module_setting_root('soc', settings_file)
soc_roots.insert(0, Path(ZEPHYR_BASE))
root_args = argparse.Namespace(**{'board_roots': board_roots,
'soc_roots': soc_roots, 'board': None,
'board_dir': []})
v2_boards = list_boards.find_v2_boards(root_args).values()
with open(kconfig_defconfig_file, 'w') as fp:
for board in v2_boards:
for board_dir in board.directories:
fp.write('osource "' + (board_dir / 'Kconfig.defconfig').as_posix() + '"\n')
with open(kconfig_sysbuild_file, 'w') as fp:
for board in v2_boards:
for board_dir in board.directories:
fp.write('osource "' + (board_dir / 'Kconfig.sysbuild').as_posix() + '"\n')
with open(kconfig_boards_file, 'w') as fp:
for board in v2_boards:
board_str = 'BOARD_' + re.sub(r"[^a-zA-Z0-9_]", "_", board.name).upper()
fp.write('config ' + board_str + '\n')
fp.write('\t bool\n')
for qualifier in list_boards.board_v2_qualifiers(board):
board_str = ('BOARD_' + board.name + '_' +
re.sub(r"[^a-zA-Z0-9_]", "_", qualifier)).upper()
fp.write('config ' + board_str + '\n')
fp.write('\t bool\n')
for board_dir in board.directories:
fp.write(
'source "' + (board_dir / ('Kconfig.' + board.name)).as_posix() + '"\n'
)
with open(kconfig_file, 'w') as fp:
for board in v2_boards:
for board_dir in board.directories:
fp.write('osource "' + (board_dir / 'Kconfig').as_posix() + '"\n')
kconfig_defconfig_file = os.path.join(kconfig_dir, 'soc', 'Kconfig.defconfig')
kconfig_sysbuild_file = os.path.join(kconfig_dir, 'soc', 'Kconfig.sysbuild')
kconfig_soc_file = os.path.join(kconfig_dir, 'soc', 'Kconfig.soc')
kconfig_file = os.path.join(kconfig_dir, 'soc', 'Kconfig')
root_args = argparse.Namespace(**{'soc_roots': soc_roots})
v2_systems = list_hardware.find_v2_systems(root_args)
soc_folders = {folder for soc in v2_systems.get_socs() for folder in soc.folder}
with open(kconfig_defconfig_file, 'w') as fp:
for folder in soc_folders:
fp.write('osource "' + (Path(folder) / 'Kconfig.defconfig').as_posix() + '"\n')
with open(kconfig_sysbuild_file, 'w') as fp:
for folder in soc_folders:
fp.write('osource "' + (Path(folder) / 'Kconfig.sysbuild').as_posix() + '"\n')
with open(kconfig_soc_file, 'w') as fp:
for folder in soc_folders:
fp.write('source "' + (Path(folder) / 'Kconfig.soc').as_posix() + '"\n')
with open(kconfig_file, 'w') as fp:
for folder in soc_folders:
fp.write('source "' + (Path(folder) / 'Kconfig').as_posix() + '"\n')
kconfig_file = os.path.join(kconfig_dir, 'arch', 'Kconfig')
root_args = argparse.Namespace(**{'arch_roots': [Path(ZEPHYR_BASE)], 'arch': None})
v2_archs = list_hardware.find_v2_archs(root_args)
with open(kconfig_file, 'w') as fp:
for arch in v2_archs['archs']:
fp.write('source "' + (Path(arch['path']) / 'Kconfig').as_posix() + '"\n')
def parse_kconfig(self):
"""
Returns a kconfiglib.Kconfig object for the Kconfig files. We reuse
this object for all tests to avoid having to reparse for each test.
"""
# Put the Kconfiglib path first to make sure no local Kconfiglib version is
# used
kconfig_path = os.path.join(ZEPHYR_BASE, "scripts", "kconfig")
if not os.path.exists(kconfig_path):
self.error(kconfig_path + " not found")
kconfiglib_dir = tempfile.mkdtemp(prefix="kconfiglib_")
sys.path.insert(0, kconfig_path)
# Import globally so that e.g. kconfiglib.Symbol can be referenced in
# tests
global kconfiglib
import kconfiglib
# Look up Kconfig files relative to ZEPHYR_BASE
os.environ["srctree"] = ZEPHYR_BASE
# Parse the entire Kconfig tree, to make sure we see all symbols
os.environ["SOC_DIR"] = "soc/"
os.environ["ARCH_DIR"] = "arch/"
os.environ["BOARD"] = "boards"
os.environ["ARCH"] = "*"
os.environ["KCONFIG_BINARY_DIR"] = kconfiglib_dir
os.environ['DEVICETREE_CONF'] = "dummy"
os.environ['TOOLCHAIN_HAS_NEWLIB'] = "y"
# Older name for DEVICETREE_CONF, for compatibility with older Zephyr
# versions that don't have the renaming
os.environ["GENERATED_DTS_BOARD_CONF"] = "dummy"
# For multi repo support
self.get_modules(os.path.join(kconfiglib_dir, "Kconfig.modules"),
os.path.join(kconfiglib_dir, "Kconfig.sysbuild.modules"),
os.path.join(kconfiglib_dir, "settings_file.txt"))
# For Kconfig.dts support
self.get_kconfig_dts(os.path.join(kconfiglib_dir, "Kconfig.dts"),
os.path.join(kconfiglib_dir, "settings_file.txt"))
# For hardware model support (board, soc, arch)
self.get_v2_model(kconfiglib_dir, os.path.join(kconfiglib_dir, "settings_file.txt"))
# Tells Kconfiglib to generate warnings for all references to undefined
# symbols within Kconfig files
os.environ["KCONFIG_WARN_UNDEF"] = "y"
try:
# Note this will both print warnings to stderr _and_ return
# them: so some warnings might get printed
# twice. "warn_to_stderr=False" could unfortunately cause
# some (other) warnings to never be printed.
return kconfiglib.Kconfig(filename=self.FILENAME)
except kconfiglib.KconfigError as e:
self.failure(str(e))
raise EndTest
finally:
# Clean up the temporary directory
shutil.rmtree(kconfiglib_dir)
def get_logging_syms(self, kconf):
# Returns a set() with the names of the Kconfig symbols generated with
# logging template in samples/tests folders. The Kconfig symbols doesn't
# include `CONFIG_` and for each module declared there is one symbol
# per suffix created.
suffixes = [
"_LOG_LEVEL",
"_LOG_LEVEL_DBG",
"_LOG_LEVEL_ERR",
"_LOG_LEVEL_INF",
"_LOG_LEVEL_WRN",
"_LOG_LEVEL_OFF",
"_LOG_LEVEL_INHERIT",
"_LOG_LEVEL_DEFAULT",
]
# Warning: Needs to work with both --perl-regexp and the 're' module.
regex = r"^\s*(?:module\s*=\s*)([A-Z0-9_]+)\s*(?:#|$)"
# Grep samples/ and tests/ for symbol definitions
grep_stdout = git("grep", "-I", "-h", "--perl-regexp", regex, "--",
":samples", ":tests", cwd=ZEPHYR_BASE)
names = re.findall(regex, grep_stdout, re.MULTILINE)
kconf_syms = []
for name in names:
for suffix in suffixes:
kconf_syms.append(f"{name}{suffix}")
return set(kconf_syms)
def check_disallowed_defconfigs(self, kconf):
"""
Checks that there are no disallowed Kconfigs used in board/SoC defconfig files
"""
# Grep for symbol references.
#
# Example output line for a reference to CONFIG_FOO at line 17 of
# foo/bar.c:
#
# foo/bar.c<null>17<null>#ifdef CONFIG_FOO
#
# 'git grep --only-matching' would get rid of the surrounding context
# ('#ifdef '), but it was added fairly recently (second half of 2018),
# so we extract the references from each line ourselves instead.
#
# The regex uses word boundaries (\b) to isolate the reference, and
# negative lookahead to automatically allowlist the following:
#
# - ##, for token pasting (CONFIG_FOO_##X)
#
# - $, e.g. for CMake variable expansion (CONFIG_FOO_${VAR})
#
# - @, e.g. for CMakes's configure_file() (CONFIG_FOO_@VAR@)
#
# - {, e.g. for Python scripts ("CONFIG_FOO_{}_BAR".format(...)")
#
# - *, meant for comments like '#endif /* CONFIG_FOO_* */
disallowed_symbols = {
"PINCTRL": "Drivers requiring PINCTRL must SELECT it instead.",
}
disallowed_regex = "(" + "|".join(disallowed_symbols.keys()) + ")$"
# Warning: Needs to work with both --perl-regexp and the 're' module
regex_boards = r"\bCONFIG_[A-Z0-9_]+\b(?!\s*##|[$@{(.*])"
regex_socs = r"\bconfig\s+[A-Z0-9_]+$"
grep_stdout_boards = git("grep", "--line-number", "-I", "--null",
"--perl-regexp", regex_boards, "--", ":boards",
cwd=ZEPHYR_BASE)
grep_stdout_socs = git("grep", "--line-number", "-I", "--null",
"--perl-regexp", regex_socs, "--", ":soc",
cwd=ZEPHYR_BASE)
# Board processing
# splitlines() supports various line terminators
for grep_line in grep_stdout_boards.splitlines():
path, lineno, line = grep_line.split("\0")
# Extract symbol references (might be more than one) within the line
for sym_name in re.findall(regex_boards, line):
sym_name = sym_name[len("CONFIG_"):]
# Only check in Kconfig fragment files, references might exist in documentation
if re.match(disallowed_regex, sym_name) and (path[-len("conf"):] == "conf" or
path[-len("defconfig"):] == "defconfig"):
reason = disallowed_symbols.get(sym_name)
self.fmtd_failure("error", "BoardDisallowedKconfigs", path, lineno, desc=f"""
Found disallowed Kconfig symbol in board Kconfig files: CONFIG_{sym_name:35}
{reason}
""")
# SoCs processing
# splitlines() supports various line terminators
for grep_line in grep_stdout_socs.splitlines():
path, lineno, line = grep_line.split("\0")
# Extract symbol references (might be more than one) within the line
for sym_name in re.findall(regex_socs, line):
sym_name = sym_name[len("config"):].strip()
# Only check in Kconfig defconfig files
if re.match(disallowed_regex, sym_name) and "defconfig" in path:
reason = disallowed_symbols.get(sym_name, "Unknown reason")
self.fmtd_failure("error", "SoCDisallowedKconfigs", path, lineno, desc=f"""
Found disallowed Kconfig symbol in SoC Kconfig files: {sym_name:35}
{reason}
""")
def get_defined_syms(self, kconf):
# Returns a set() with the names of all defined Kconfig symbols (with no
# 'CONFIG_' prefix). This is complicated by samples and tests defining
# their own Kconfig trees. For those, just grep for 'config FOO' to find
# definitions. Doing it "properly" with Kconfiglib is still useful for
# the main tree, because some symbols are defined using preprocessor
# macros.
# Warning: Needs to work with both --perl-regexp and the 're' module.
# (?:...) is a non-capturing group.
regex = r"^\s*(?:menu)?config\s*([A-Z0-9_]+)\s*(?:#|$)"
# Grep samples/ and tests/ for symbol definitions
grep_stdout = git("grep", "-I", "-h", "--perl-regexp", regex, "--",
":samples", ":tests", cwd=ZEPHYR_BASE)
# Generate combined list of configs and choices from the main Kconfig tree.
kconf_syms = kconf.unique_defined_syms + kconf.unique_choices
# Symbols from the main Kconfig tree + grepped definitions from samples
# and tests
return set(
[sym.name for sym in kconf_syms]
+ re.findall(regex, grep_stdout, re.MULTILINE)
).union(self.get_logging_syms(kconf))
def check_top_menu_not_too_long(self, kconf):
"""
Checks that there aren't too many items in the top-level menu (which
might be a sign that stuff accidentally got added there)
"""
max_top_items = 50
n_top_items = 0
node = kconf.top_node.list
while node:
# Only count items with prompts. Other items will never be
# shown in the menuconfig (outside show-all mode).
if node.prompt:
n_top_items += 1
node = node.next
if n_top_items > max_top_items:
self.failure(f"""
Expected no more than {max_top_items} potentially visible items (items with
prompts) in the top-level Kconfig menu, found {n_top_items} items. If you're
deliberately adding new entries, then bump the 'max_top_items' variable in
{__file__}.""")
def check_no_redefined_in_defconfig(self, kconf):
# Checks that no symbols are (re)defined in defconfigs.
for node in kconf.node_iter():
# 'kconfiglib' is global
# pylint: disable=undefined-variable
if "defconfig" in node.filename and (node.prompt or node.help):
name = (node.item.name if node.item not in
(kconfiglib.MENU, kconfiglib.COMMENT) else str(node))
self.failure(f"""
Kconfig node '{name}' found with prompt or help in {node.filename}.
Options must not be defined in defconfig files.
""")
continue
def check_no_enable_in_boolean_prompt(self, kconf):
# Checks that boolean's prompt does not start with "Enable...".
for node in kconf.node_iter():
# skip Kconfig nodes not in-tree (will present an absolute path)
if os.path.isabs(node.filename):
continue
# 'kconfiglib' is global
# pylint: disable=undefined-variable
# only process boolean symbols with a prompt
if (not isinstance(node.item, kconfiglib.Symbol) or
node.item.type != kconfiglib.BOOL or
not node.prompt or
not node.prompt[0]):
continue
if re.match(r"^[Ee]nable.*", node.prompt[0]):
self.failure(f"""
Boolean option '{node.item.name}' prompt must not start with 'Enable...'. Please
check Kconfig guidelines.
""")
continue
def check_no_pointless_menuconfigs(self, kconf):
# Checks that there are no pointless 'menuconfig' symbols without
# children in the Kconfig files
bad_mconfs = []
for node in kconf.node_iter():
# 'kconfiglib' is global
# pylint: disable=undefined-variable
# Avoid flagging empty regular menus and choices, in case people do
# something with 'osource' (could happen for 'menuconfig' symbols
# too, though it's less likely)
if node.is_menuconfig and not node.list and \
isinstance(node.item, kconfiglib.Symbol):
bad_mconfs.append(node)
if bad_mconfs:
self.failure("""\
Found pointless 'menuconfig' symbols without children. Use regular 'config'
symbols instead. See
https://docs.zephyrproject.org/latest/build/kconfig/tips.html#menuconfig-symbols.
""" + "\n".join(f"{node.item.name:35} {node.filename}:{node.linenr}"
for node in bad_mconfs))
def check_no_undef_within_kconfig(self, kconf):
"""
Checks that there are no references to undefined Kconfig symbols within
the Kconfig files
"""
undef_ref_warnings = "\n\n\n".join(warning for warning in kconf.warnings
if "undefined symbol" in warning)
if undef_ref_warnings:
self.failure(f"Undefined Kconfig symbols:\n\n {undef_ref_warnings}")
def check_soc_name_sync(self, kconf):
root_args = argparse.Namespace(**{'soc_roots': [Path(ZEPHYR_BASE)]})
v2_systems = list_hardware.find_v2_systems(root_args)
soc_names = {soc.name for soc in v2_systems.get_socs()}
soc_kconfig_names = set()
for node in kconf.node_iter():
# 'kconfiglib' is global
# pylint: disable=undefined-variable
if isinstance(node.item, kconfiglib.Symbol) and node.item.name == "SOC":
n = node.item
for d in n.defaults:
soc_kconfig_names.add(d[0].name)
soc_name_warnings = []
for name in soc_names:
if name not in soc_kconfig_names:
soc_name_warnings.append(f"soc name: {name} not found in CONFIG_SOC defaults.")
if soc_name_warnings:
soc_name_warning_str = '\n'.join(soc_name_warnings)
self.failure(f'''
Missing SoC names or CONFIG_SOC vs soc.yml out of sync:
{soc_name_warning_str}
''')
def check_no_undef_outside_kconfig(self, kconf):
"""
Checks that there are no references to undefined Kconfig symbols
outside Kconfig files (any CONFIG_FOO where no FOO symbol exists)
"""
# Grep for symbol references.
#
# Example output line for a reference to CONFIG_FOO at line 17 of
# foo/bar.c:
#
# foo/bar.c<null>17<null>#ifdef CONFIG_FOO
#
# 'git grep --only-matching' would get rid of the surrounding context
# ('#ifdef '), but it was added fairly recently (second half of 2018),
# so we extract the references from each line ourselves instead.
#
# The regex uses word boundaries (\b) to isolate the reference, and
# negative lookahead to automatically allowlist the following:
#
# - ##, for token pasting (CONFIG_FOO_##X)
#
# - $, e.g. for CMake variable expansion (CONFIG_FOO_${VAR})
#
# - @, e.g. for CMakes's configure_file() (CONFIG_FOO_@VAR@)
#
# - {, e.g. for Python scripts ("CONFIG_FOO_{}_BAR".format(...)")
#
# - *, meant for comments like '#endif /* CONFIG_FOO_* */
defined_syms = self.get_defined_syms(kconf)
# Maps each undefined symbol to a list <filename>:<linenr> strings
undef_to_locs = collections.defaultdict(list)
# Warning: Needs to work with both --perl-regexp and the 're' module
regex = r"\b" + self.CONFIG_ + r"[A-Z0-9_]+\b(?!\s*##|[$@{(.*])"
# Skip doc/releases and doc/security/vulnerabilities.rst, which often
# reference removed symbols
grep_stdout = git("grep", "--line-number", "-I", "--null",
"--perl-regexp", regex, "--", ":!/doc/releases",
":!/doc/security/vulnerabilities.rst",
cwd=Path(GIT_TOP))
# splitlines() supports various line terminators
for grep_line in grep_stdout.splitlines():
path, lineno, line = grep_line.split("\0")
# Extract symbol references (might be more than one) within the
# line
for sym_name in re.findall(regex, line):
sym_name = sym_name[len(self.CONFIG_):] # Strip CONFIG_
if sym_name not in defined_syms and \
sym_name not in self.UNDEF_KCONFIG_ALLOWLIST and \
not (sym_name.endswith("_MODULE") and sym_name[:-7] in defined_syms):
undef_to_locs[sym_name].append(f"{path}:{lineno}")
if not undef_to_locs:
return
# String that describes all referenced but undefined Kconfig symbols,
# in alphabetical order, along with the locations where they're
# referenced. Example:
#
# CONFIG_ALSO_MISSING arch/xtensa/core/fatal.c:273
# CONFIG_MISSING arch/xtensa/core/fatal.c:264, subsys/fb/cfb.c:20
undef_desc = "\n".join(f"{self.CONFIG_}{sym_name:35} {', '.join(locs)}"
for sym_name, locs in sorted(undef_to_locs.items()))
self.failure(f"""
Found references to undefined Kconfig symbols. If any of these are false
positives, then add them to UNDEF_KCONFIG_ALLOWLIST in {__file__}.
If the reference is for a comment like /* CONFIG_FOO_* */ (or
/* CONFIG_FOO_*_... */), then please use exactly that form (with the '*'). The
CI check knows not to flag it.
More generally, a reference followed by $, @, {{, (, ., *, or ## will never be
flagged.
{undef_desc}""")
# Many of these are symbols used as examples. Note that the list is sorted
# alphabetically, and skips the CONFIG_ prefix.
UNDEF_KCONFIG_ALLOWLIST = {
# zephyr-keep-sorted-start re(^\s+")
"ALSO_MISSING",
"APP_LINK_WITH_",
"APP_LOG_LEVEL", # Application log level is not detected correctly as
# the option is defined using a template, so it can't
# be grepped