-
Notifications
You must be signed in to change notification settings - Fork 5
/
kconfiglib.py
7160 lines (5645 loc) · 254 KB
/
kconfiglib.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
# Copyright (c) 2011-2019, Ulf Magnusson
# SPDX-License-Identifier: ISC
"""
Overview
========
Kconfiglib is a Python 2/3 library for scripting and extracting information
from Kconfig (https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt)
configuration systems.
See the homepage at https://github.com/zephyrproject-rtos/Kconfiglib for a longer
overview.
Since Kconfiglib 12.0.0, the library version is available in
kconfiglib.VERSION, which is a (<major>, <minor>, <patch>) tuple, e.g.
(12, 0, 0).
Using Kconfiglib on the Linux kernel with the Makefile targets
==============================================================
For the Linux kernel, a handy interface is provided by the
scripts/kconfig/Makefile patch, which can be applied with either 'git am' or
the 'patch' utility:
$ wget -qO- https://raw.githubusercontent.com/zephyrproject-rtos/Kconfiglib/master/makefile.patch | git am
$ wget -qO- https://raw.githubusercontent.com/zephyrproject-rtos/Kconfiglib/master/makefile.patch | patch -p1
Warning: Not passing -p1 to patch will cause the wrong file to be patched.
Please tell me if the patch does not apply. It should be trivial to apply
manually, as it's just a block of text that needs to be inserted near the other
*conf: targets in scripts/kconfig/Makefile.
Look further down for a motivation for the Makefile patch and for instructions
on how you can use Kconfiglib without it.
If you do not wish to install Kconfiglib via pip, the Makefile patch is set up
so that you can also just clone Kconfiglib into the kernel root:
$ git clone git://github.com/zephyrproject-rtos/Kconfiglib.git
$ git am Kconfiglib/makefile.patch (or 'patch -p1 < Kconfiglib/makefile.patch')
Warning: The directory name Kconfiglib/ is significant in this case, because
it's added to PYTHONPATH by the new targets in makefile.patch.
The targets added by the Makefile patch are described in the following
sections.
make kmenuconfig
----------------
This target runs the curses menuconfig interface with Python 3. As of
Kconfiglib 12.2.0, both Python 2 and Python 3 are supported (previously, only
Python 3 was supported, so this was a backport).
make guiconfig
--------------
This target runs the Tkinter menuconfig interface. Both Python 2 and Python 3
are supported. To change the Python interpreter used, pass
PYTHONCMD=<executable> to 'make'. The default is 'python'.
make [ARCH=<arch>] iscriptconfig
--------------------------------
This target gives an interactive Python prompt where a Kconfig instance has
been preloaded and is available in 'kconf'. To change the Python interpreter
used, pass PYTHONCMD=<executable> to 'make'. The default is 'python'.
To get a feel for the API, try evaluating and printing the symbols in
kconf.defined_syms, and explore the MenuNode menu tree starting at
kconf.top_node by following 'next' and 'list' pointers.
The item contained in a menu node is found in MenuNode.item (note that this can
be one of the constants kconfiglib.MENU and kconfiglib.COMMENT), and all
symbols and choices have a 'nodes' attribute containing their menu nodes
(usually only one). Printing a menu node will print its item, in Kconfig
format.
If you want to look up a symbol by name, use the kconf.syms dictionary.
make scriptconfig SCRIPT=<script> [SCRIPT_ARG=<arg>]
----------------------------------------------------
This target runs the Python script given by the SCRIPT parameter on the
configuration. sys.argv[1] holds the name of the top-level Kconfig file
(currently always "Kconfig" in practice), and sys.argv[2] holds the SCRIPT_ARG
argument, if given.
See the examples/ subdirectory for example scripts.
make dumpvarsconfig
-------------------
This target prints a list of all environment variables referenced from the
Kconfig files, together with their values. See the
Kconfiglib/examples/dumpvars.py script.
Only environment variables that are referenced via the Kconfig preprocessor
$(FOO) syntax are included. The preprocessor was added in Linux 4.18.
Using Kconfiglib without the Makefile targets
=============================================
The make targets are only needed to pick up environment variables exported from
the Kbuild makefiles and referenced inside Kconfig files, via e.g.
'source "arch/$(SRCARCH)/Kconfig" and commands run via '$(shell,...)'.
These variables are referenced as of writing (Linux 4.18), together with sample
values:
srctree (.)
ARCH (x86)
SRCARCH (x86)
KERNELVERSION (4.18.0)
CC (gcc)
HOSTCC (gcc)
HOSTCXX (g++)
CC_VERSION_TEXT (gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0)
Older kernels only reference ARCH, SRCARCH, and KERNELVERSION.
If your kernel is recent enough (4.18+), you can get a list of referenced
environment variables via 'make dumpvarsconfig' (see above). Note that this
command is added by the Makefile patch.
To run Kconfiglib without the Makefile patch, set the environment variables
manually:
$ srctree=. ARCH=x86 SRCARCH=x86 KERNELVERSION=`make kernelversion` ... python(3)
>>> import kconfiglib
>>> kconf = kconfiglib.Kconfig() # filename defaults to "Kconfig"
Search the top-level Makefile for "Additional ARCH settings" to see other
possibilities for ARCH and SRCARCH.
Intro to symbol values
======================
Kconfiglib has the same assignment semantics as the C implementation.
Any symbol can be assigned a value by the user (via Kconfig.load_config() or
Symbol.set_value()), but this user value is only respected if the symbol is
visible, which corresponds to it (currently) being visible in the menuconfig
interface.
For symbols with prompts, the visibility of the symbol is determined by the
condition on the prompt. Symbols without prompts are never visible, so setting
a user value on them is pointless. A warning will be printed by default if
Symbol.set_value() is called on a promptless symbol. Assignments to promptless
symbols are normal within a .config file, so no similar warning will be printed
by load_config().
Dependencies from parents and 'if'/'depends on' are propagated to properties,
including prompts, so these two configurations are logically equivalent:
(1)
menu "menu"
depends on A
if B
config FOO
tristate "foo" if D
default y
depends on C
endif
endmenu
(2)
menu "menu"
depends on A
config FOO
tristate "foo" if A && B && C && D
default y if A && B && C
endmenu
In this example, A && B && C && D (the prompt condition) needs to be non-n for
FOO to be visible (assignable). If its value is m, the symbol can only be
assigned the value m: The visibility sets an upper bound on the value that can
be assigned by the user, and any higher user value will be truncated down.
'default' properties are independent of the visibility, though a 'default' will
often get the same condition as the prompt due to dependency propagation.
'default' properties are used if the symbol is not visible or has no user
value.
Symbols with no user value (or that have a user value but are not visible) and
no (active) 'default' default to n for bool/tristate symbols, and to the empty
string for other symbol types.
'select' works similarly to symbol visibility, but sets a lower bound on the
value of the symbol. The lower bound is determined by the value of the
select*ing* symbol. 'select' does not respect visibility, so non-visible
symbols can be forced to a particular (minimum) value by a select as well.
For non-bool/tristate symbols, it only matters whether the visibility is n or
non-n: m visibility acts the same as y visibility.
Conditions on 'default' and 'select' work in mostly intuitive ways. If the
condition is n, the 'default' or 'select' is disabled. If it is m, the
'default' or 'select' value (the value of the selecting symbol) is truncated
down to m.
When writing a configuration with Kconfig.write_config(), only symbols that are
visible, have an (active) default, or are selected will get written out (note
that this includes all symbols that would accept user values). Kconfiglib
matches the .config format produced by the C implementations down to the
character. This eases testing.
For a visible bool/tristate symbol FOO with value n, this line is written to
.config:
# CONFIG_FOO is not set
The point is to remember the user n selection (which might differ from the
default value the symbol would get), while at the same sticking to the rule
that undefined corresponds to n (.config uses Makefile format, making the line
above a comment). When the .config file is read back in, this line will be
treated the same as the following assignment:
CONFIG_FOO=n
In Kconfiglib, the set of (currently) assignable values for a bool/tristate
symbol appear in Symbol.assignable. For other symbol types, just check if
sym.visibility is non-0 (non-n) to see whether the user value will have an
effect.
Intro to the menu tree
======================
The menu structure, as seen in e.g. menuconfig, is represented by a tree of
MenuNode objects. The top node of the configuration corresponds to an implicit
top-level menu, the title of which is shown at the top in the standard
menuconfig interface. (The title is also available in Kconfig.mainmenu_text in
Kconfiglib.)
The top node is found in Kconfig.top_node. From there, you can visit child menu
nodes by following the 'list' pointer, and any following menu nodes by
following the 'next' pointer. Usually, a non-None 'list' pointer indicates a
menu or Choice, but menu nodes for symbols can sometimes have a non-None 'list'
pointer too due to submenus created implicitly from dependencies.
MenuNode.item is either a Symbol or a Choice object, or one of the constants
MENU and COMMENT. The prompt of the menu node can be found in MenuNode.prompt,
which also holds the title for menus and comments. For Symbol and Choice,
MenuNode.help holds the help text (if any, otherwise None).
Most symbols will only have a single menu node. A symbol defined in multiple
locations will have one menu node for each location. The list of menu nodes for
a Symbol or Choice can be found in the Symbol/Choice.nodes attribute.
Note that prompts and help texts for symbols and choices are stored in their
menu node(s) rather than in the Symbol or Choice objects themselves. This makes
it possible to define a symbol in multiple locations with a different prompt or
help text in each location. To get the help text or prompt for a symbol with a
single menu node, do sym.nodes[0].help and sym.nodes[0].prompt, respectively.
The prompt is a (text, condition) tuple, where condition determines the
visibility (see 'Intro to expressions' below).
This organization mirrors the C implementation. MenuNode is called
'struct menu' there, but I thought "menu" was a confusing name.
It is possible to give a Choice a name and define it in multiple locations,
hence why Choice.nodes is also a list.
As a convenience, the properties added at a particular definition location are
available on the MenuNode itself, in e.g. MenuNode.defaults. This is helpful
when generating documentation, so that symbols/choices defined in multiple
locations can be shown with the correct properties at each location.
Intro to expressions
====================
Expressions can be evaluated with the expr_value() function and printed with
the expr_str() function (these are used internally as well). Evaluating an
expression always yields a tristate value, where n, m, and y are represented as
0, 1, and 2, respectively.
The following table should help you figure out how expressions are represented.
A, B, C, ... are symbols (Symbol instances), NOT is the kconfiglib.NOT
constant, etc.
Expression Representation
---------- --------------
A A
"A" A (constant symbol)
!A (NOT, A)
A && B (AND, A, B)
A && B && C (AND, A, (AND, B, C))
A || B (OR, A, B)
A || (B && C && D) (OR, A, (AND, B, (AND, C, D)))
A = B (EQUAL, A, B)
A != "foo" (UNEQUAL, A, foo (constant symbol))
A && B = C && D (AND, A, (AND, (EQUAL, B, C), D))
n Kconfig.n (constant symbol)
m Kconfig.m (constant symbol)
y Kconfig.y (constant symbol)
"y" Kconfig.y (constant symbol)
Strings like "foo" in 'default "foo"' or 'depends on SYM = "foo"' are
represented as constant symbols, so the only values that appear in expressions
are symbols***. This mirrors the C implementation.
***For choice symbols, the parent Choice will appear in expressions as well,
but it's usually invisible as the value interfaces of Symbol and Choice are
identical. This mirrors the C implementation and makes different choice modes
"just work".
Manual evaluation examples:
- The value of A && B is min(A.tri_value, B.tri_value)
- The value of A || B is max(A.tri_value, B.tri_value)
- The value of !A is 2 - A.tri_value
- The value of A = B is 2 (y) if A.str_value == B.str_value, and 0 (n)
otherwise. Note that str_value is used here instead of tri_value.
For constant (as well as undefined) symbols, str_value matches the name of
the symbol. This mirrors the C implementation and explains why
'depends on SYM = "foo"' above works as expected.
n/m/y are automatically converted to the corresponding constant symbols
"n"/"m"/"y" (Kconfig.n/m/y) during parsing.
Kconfig.const_syms is a dictionary like Kconfig.syms but for constant symbols.
If a condition is missing (e.g., <cond> when the 'if <cond>' is removed from
'default A if <cond>'), it is actually Kconfig.y. The standard __str__()
functions just avoid printing 'if y' conditions to give cleaner output.
Kconfig extensions
==================
Kconfiglib includes a couple of Kconfig extensions:
'source' with relative path
---------------------------
The 'rsource' statement sources Kconfig files with a path relative to directory
of the Kconfig file containing the 'rsource' statement, instead of relative to
the project root.
Consider following directory tree:
Project
+--Kconfig
|
+--src
+--Kconfig
|
+--SubSystem1
+--Kconfig
|
+--ModuleA
+--Kconfig
In this example, assume that src/SubSystem1/Kconfig wants to source
src/SubSystem1/ModuleA/Kconfig.
With 'source', this statement would be used:
source "src/SubSystem1/ModuleA/Kconfig"
With 'rsource', this turns into
rsource "ModuleA/Kconfig"
If an absolute path is given to 'rsource', it acts the same as 'source'.
'rsource' can be used to create "position-independent" Kconfig trees that can
be moved around freely.
Globbing 'source'
-----------------
'source' and 'rsource' accept glob patterns, sourcing all matching Kconfig
files. They require at least one matching file, raising a KconfigError
otherwise.
For example, the following statement might source sub1/foofoofoo and
sub2/foobarfoo:
source "sub[12]/foo*foo"
The glob patterns accepted are the same as for the standard glob.glob()
function.
Two additional statements are provided for cases where it's acceptable for a
pattern to match no files: 'osource' and 'orsource' (the o is for "optional").
For example, the following statements will be no-ops if neither "foo" nor any
files matching "bar*" exist:
osource "foo"
osource "bar*"
'orsource' does a relative optional source.
'source' and 'osource' are analogous to 'include' and '-include' in Make.
Generalized def_* keywords
--------------------------
def_int, def_hex, and def_string are available in addition to def_bool and
def_tristate, allowing int, hex, and string symbols to be given a type and a
default at the same time.
Extra optional warnings
-----------------------
Some optional warnings can be controlled via environment variables:
- KCONFIG_WARN_UNDEF: If set to 'y', warnings will be generated for all
references to undefined symbols within Kconfig files. The only gotcha is
that all hex literals must be prefixed with "0x" or "0X", to make it
possible to distinguish them from symbol references.
Some projects (e.g. the Linux kernel) use multiple Kconfig trees with many
shared Kconfig files, leading to some safe undefined symbol references.
KCONFIG_WARN_UNDEF is useful in projects that only have a single Kconfig
tree though.
KCONFIG_STRICT is an older alias for this environment variable, supported
for backwards compatibility.
- KCONFIG_WARN_UNDEF_ASSIGN: If set to 'y', warnings will be generated for
all assignments to undefined symbols within .config files. By default, no
such warnings are generated.
This warning can also be enabled/disabled via the Kconfig.warn_assign_undef
variable.
Preprocessor user functions defined in Python
---------------------------------------------
Preprocessor functions can be defined in Python, which makes it simple to
integrate information from existing Python tools into Kconfig (e.g. to have
Kconfig symbols depend on hardware information stored in some other format).
Putting a Python module named kconfigfunctions(.py) anywhere in sys.path will
cause it to be imported by Kconfiglib (in Kconfig.__init__()). Note that
sys.path can be customized via PYTHONPATH, and includes the directory of the
module being run by default, as well as installation directories.
If the KCONFIG_FUNCTIONS environment variable is set, it gives a different
module name to use instead of 'kconfigfunctions'.
The imported module is expected to define a global dictionary named 'functions'
that maps function names to Python functions, as follows:
def my_fn(kconf, name, arg_1, arg_2, ...):
# kconf:
# Kconfig instance
#
# name:
# Name of the user-defined function ("my-fn"). Think argv[0].
#
# arg_1, arg_2, ...:
# Arguments passed to the function from Kconfig (strings)
#
# Returns a string to be substituted as the result of calling the
# function
...
def my_other_fn(kconf, name, arg_1, arg_2, ...):
...
functions = {
"my-fn": (my_fn, <min.args>, <max.args>/None),
"my-other-fn": (my_other_fn, <min.args>, <max.args>/None),
...
}
...
<min.args> and <max.args> are the minimum and maximum number of arguments
expected by the function (excluding the implicit 'name' argument). If
<max.args> is None, there is no upper limit to the number of arguments. Passing
an invalid number of arguments will generate a KconfigError exception.
Functions can access the current parsing location as kconf.filename/linenr.
Accessing other fields of the Kconfig object is not safe. See the warning
below.
Keep in mind that for a variable defined like 'foo = $(fn)', 'fn' will be
called only when 'foo' is expanded. If 'fn' uses the parsing location and the
intent is to use the location of the assignment, you want 'foo := $(fn)'
instead, which calls the function immediately.
Once defined, user functions can be called from Kconfig in the same way as
other preprocessor functions:
config FOO
...
depends on $(my-fn,arg1,arg2)
If my_fn() returns "n", this will result in
config FOO
...
depends on n
Warning
*******
User-defined preprocessor functions are called as they're encountered at parse
time, before all Kconfig files have been processed, and before the menu tree
has been finalized. There are no guarantees that accessing Kconfig symbols or
the menu tree via the 'kconf' parameter will work, and it could potentially
lead to a crash.
Preferably, user-defined functions should be stateless.
Feedback
========
For bug reports, suggestions, and questions, please open a ticket on the GitHub
page.
"""
import errno
import importlib
import os
import re
import sys
# Get rid of some attribute lookups. These are obvious in context.
from glob import iglob
from os.path import dirname, exists, expandvars, islink, join, realpath
VERSION = (14, 1, 0)
# File layout:
#
# Public classes
# Public functions
# Internal functions
# Global constants
# Line length: 79 columns
#
# Public classes
#
class Kconfig(object):
"""
Represents a Kconfig configuration, e.g. for x86 or ARM. This is the set of
symbols, choices, and menu nodes appearing in the configuration. Creating
any number of Kconfig objects (including for different architectures) is
safe. Kconfiglib doesn't keep any global state.
The following attributes are available. They should be treated as
read-only, and some are implemented through @property magic.
syms:
A dictionary with all symbols in the configuration, indexed by name. Also
includes all symbols that are referenced in expressions but never
defined, except for constant (quoted) symbols.
Undefined symbols can be recognized by Symbol.nodes being empty -- see
the 'Intro to the menu tree' section in the module docstring.
const_syms:
A dictionary like 'syms' for constant (quoted) symbols
named_choices:
A dictionary like 'syms' for named choices (choice FOO)
defined_syms:
A list with all defined symbols, in the same order as they appear in the
Kconfig files. Symbols defined in multiple locations appear multiple
times.
Note: You probably want to use 'unique_defined_syms' instead. This
attribute is mostly maintained for backwards compatibility.
unique_defined_syms:
A list like 'defined_syms', but with duplicates removed. Just the first
instance is kept for symbols defined in multiple locations. Kconfig order
is preserved otherwise.
Using this attribute instead of 'defined_syms' can save work, and
automatically gives reasonable behavior when writing configuration output
(symbols defined in multiple locations only generate output once, while
still preserving Kconfig order for readability).
choices:
A list with all choices, in the same order as they appear in the Kconfig
files.
Note: You probably want to use 'unique_choices' instead. This attribute
is mostly maintained for backwards compatibility.
unique_choices:
Analogous to 'unique_defined_syms', for choices. Named choices can have
multiple definition locations.
menus:
A list with all menus, in the same order as they appear in the Kconfig
files
comments:
A list with all comments, in the same order as they appear in the Kconfig
files
kconfig_filenames:
A list with the filenames of all Kconfig files included in the
configuration, relative to $srctree (or relative to the current directory
if $srctree isn't set), except absolute paths (e.g.
'source "/foo/Kconfig"') are kept as-is.
The files are listed in the order they are source'd, starting with the
top-level Kconfig file. If a file is source'd multiple times, it will
appear multiple times. Use set() to get unique filenames.
Note that Kconfig.sync_deps() already indirectly catches any file
modifications that change configuration output.
env_vars:
A set() with the names of all environment variables referenced in the
Kconfig files.
Only environment variables referenced with the preprocessor $(FOO) syntax
will be registered. The older $FOO syntax is only supported for backwards
compatibility.
Also note that $(FOO) won't be registered unless the environment variable
$FOO is actually set. If it isn't, $(FOO) is an expansion of an unset
preprocessor variable (which gives the empty string).
Another gotcha is that environment variables referenced in the values of
recursively expanded preprocessor variables (those defined with =) will
only be registered if the variable is actually used (expanded) somewhere.
The note from the 'kconfig_filenames' documentation applies here too.
n/m/y:
The predefined constant symbols n/m/y. Also available in const_syms.
modules:
The Symbol instance for the modules symbol. Currently hardcoded to
MODULES, which is backwards compatible. Kconfiglib will warn if
'option modules' is set on some other symbol. Tell me if you need proper
'option modules' support.
'modules' is never None. If the MODULES symbol is not explicitly defined,
its tri_value will be 0 (n), as expected.
A simple way to enable modules is to do 'kconf.modules.set_value(2)'
(provided the MODULES symbol is defined and visible). Modules are
disabled by default in the kernel Kconfig files as of writing, though
nearly all defconfig files enable them (with 'CONFIG_MODULES=y').
defconfig_list:
The Symbol instance for the 'option defconfig_list' symbol, or None if no
defconfig_list symbol exists. The defconfig filename derived from this
symbol can be found in Kconfig.defconfig_filename.
defconfig_filename:
The filename given by the defconfig_list symbol. This is taken from the
first 'default' with a satisfied condition where the specified file
exists (can be opened for reading). If a defconfig file foo/defconfig is
not found and $srctree was set when the Kconfig was created,
$srctree/foo/defconfig is looked up as well.
'defconfig_filename' is None if either no defconfig_list symbol exists,
or if the defconfig_list symbol has no 'default' with a satisfied
condition that specifies a file that exists.
Gotcha: scripts/kconfig/Makefile might pass --defconfig=<defconfig> to
scripts/kconfig/conf when running e.g. 'make defconfig'. This option
overrides the defconfig_list symbol, meaning defconfig_filename might not
always match what 'make defconfig' would use.
top_node:
The menu node (see the MenuNode class) of the implicit top-level menu.
Acts as the root of the menu tree.
mainmenu_text:
The prompt (title) of the top menu (top_node). Defaults to "Main menu".
Can be changed with the 'mainmenu' statement (see kconfig-language.txt).
variables:
A dictionary with all preprocessor variables, indexed by name. See the
Variable class.
warn:
Set this variable to True/False to enable/disable warnings. See
Kconfig.__init__().
When 'warn' is False, the values of the other warning-related variables
are ignored.
This variable as well as the other warn* variables can be read to check
the current warning settings.
warn_to_stderr:
Set this variable to True/False to enable/disable warnings on stderr. See
Kconfig.__init__().
warn_assign_undef:
Set this variable to True to generate warnings for assignments to
undefined symbols in configuration files.
This variable is False by default unless the KCONFIG_WARN_UNDEF_ASSIGN
environment variable was set to 'y' when the Kconfig instance was
created.
warn_assign_override:
Set this variable to True to generate warnings for multiple assignments
to the same symbol in configuration files, where the assignments set
different values (e.g. CONFIG_FOO=m followed by CONFIG_FOO=y, where the
last value would get used).
This variable is True by default. Disabling it might be useful when
merging configurations.
warn_assign_redun:
Like warn_assign_override, but for multiple assignments setting a symbol
to the same value.
This variable is True by default. Disabling it might be useful when
merging configurations.
warnings:
A list of strings containing all warnings that have been generated, for
cases where more flexibility is needed.
See the 'warn_to_stderr' parameter to Kconfig.__init__() and the
Kconfig.warn_to_stderr variable as well. Note that warnings still get
added to Kconfig.warnings when 'warn_to_stderr' is True.
Just as for warnings printed to stderr, only warnings that are enabled
will get added to Kconfig.warnings. See the various Kconfig.warn*
variables.
missing_syms:
A list with (name, value) tuples for all assignments to undefined symbols
within the most recently loaded .config file(s). 'name' is the symbol
name without the 'CONFIG_' prefix. 'value' is a string that gives the
right-hand side of the assignment verbatim.
See Kconfig.load_config() as well.
srctree:
The value the $srctree environment variable had when the Kconfig instance
was created, or the empty string if $srctree wasn't set. This gives nice
behavior with os.path.join(), which treats "" as the current directory,
without adding "./".
Kconfig files are looked up relative to $srctree (unless absolute paths
are used), and .config files are looked up relative to $srctree if they
are not found in the current directory. This is used to support
out-of-tree builds. The C tools use this environment variable in the same
way.
Changing $srctree after creating the Kconfig instance has no effect. Only
the value when the configuration is loaded matters. This avoids surprises
if multiple configurations are loaded with different values for $srctree.
config_prefix:
The value the CONFIG_ environment variable had when the Kconfig instance
was created, or "CONFIG_" if CONFIG_ wasn't set. This is the prefix used
(and expected) on symbol names in .config files and C headers. Used in
the same way in the C tools.
config_header:
The value the KCONFIG_CONFIG_HEADER environment variable had when the
Kconfig instance was created, or the empty string if
KCONFIG_CONFIG_HEADER wasn't set. This string is inserted verbatim at the
beginning of configuration files. See write_config().
header_header:
The value the KCONFIG_AUTOHEADER_HEADER environment variable had when the
Kconfig instance was created, or the empty string if
KCONFIG_AUTOHEADER_HEADER wasn't set. This string is inserted verbatim at
the beginning of header files. See write_autoconf().
filename/linenr:
The current parsing location, for use in Python preprocessor functions.
See the module docstring.
"""
__slots__ = (
"_encoding",
"_functions",
"_set_match",
"_srctree_prefix",
"_unset_match",
"_warn_assign_no_prompt",
"choices",
"comments",
"config_header",
"config_prefix",
"const_syms",
"defconfig_list",
"defined_syms",
"env_vars",
"header_header",
"kconfig_filenames",
"m",
"menus",
"missing_syms",
"modules",
"n",
"named_choices",
"srctree",
"syms",
"top_node",
"unique_choices",
"unique_defined_syms",
"variables",
"warn",
"warn_assign_override",
"warn_assign_redun",
"warn_assign_undef",
"warn_to_stderr",
"warnings",
"y",
# Parsing-related
"_parsing_kconfigs",
"_readline",
"filename",
"linenr",
"_include_path",
"_filestack",
"_line",
"_tokens",
"_tokens_i",
"_reuse_tokens",
)
#
# Public interface
#
def __init__(self, filename="Kconfig", warn=True, warn_to_stderr=True,
encoding="utf-8", suppress_traceback=False):
"""
Creates a new Kconfig object by parsing Kconfig files.
Note that Kconfig files are not the same as .config files (which store
configuration symbol values).
See the module docstring for some environment variables that influence
default warning settings (KCONFIG_WARN_UNDEF and
KCONFIG_WARN_UNDEF_ASSIGN).
Raises KconfigError on syntax/semantic errors, and OSError or (possibly
a subclass of) IOError on IO errors ('errno', 'strerror', and
'filename' are available). Note that IOError is an alias for OSError on
Python 3, so it's enough to catch OSError there. If you need Python 2/3
compatibility, it's easiest to catch EnvironmentError, which is a
common base class of OSError/IOError on Python 2 and an alias for
OSError on Python 3.
filename (default: "Kconfig"):
The Kconfig file to load. For the Linux kernel, you'll want "Kconfig"
from the top-level directory, as environment variables will make sure
the right Kconfig is included from there (arch/$SRCARCH/Kconfig as of
writing).
If $srctree is set, 'filename' will be looked up relative to it.
$srctree is also used to look up source'd files within Kconfig files.
See the class documentation.
If you are using Kconfiglib via 'make scriptconfig', the filename of
the base base Kconfig file will be in sys.argv[1]. It's currently
always "Kconfig" in practice.
warn (default: True):
True if warnings related to this configuration should be generated.
This can be changed later by setting Kconfig.warn to True/False. It
is provided as a constructor argument since warnings might be
generated during parsing.
See the other Kconfig.warn_* variables as well, which enable or
suppress certain warnings when warnings are enabled.
All generated warnings are added to the Kconfig.warnings list. See
the class documentation.
warn_to_stderr (default: True):
True if warnings should be printed to stderr in addition to being
added to Kconfig.warnings.
This can be changed later by setting Kconfig.warn_to_stderr to
True/False.
encoding (default: "utf-8"):
The encoding to use when reading and writing files, and when decoding
output from commands run via $(shell). If None, the encoding
specified in the current locale will be used.
The "utf-8" default avoids exceptions on systems that are configured
to use the C locale, which implies an ASCII encoding.
This parameter has no effect on Python 2, due to implementation
issues (regular strings turning into Unicode strings, which are
distinct in Python 2). Python 2 doesn't decode regular strings
anyway.
Related PEP: https://www.python.org/dev/peps/pep-0538/
suppress_traceback (default: False):
Helper for tools. When True, any EnvironmentError or KconfigError
generated during parsing is caught, the exception message is printed
to stderr together with the command name, and sys.exit(1) is called
(which generates SystemExit).
This hides the Python traceback for "expected" errors like syntax
errors in Kconfig files.
Other exceptions besides EnvironmentError and KconfigError are still
propagated when suppress_traceback is True.
"""
try:
self._init(filename, warn, warn_to_stderr, encoding)
except (EnvironmentError, KconfigError) as e:
if suppress_traceback:
cmd = sys.argv[0] # Empty string if missing
if cmd:
cmd += ": "
# Some long exception messages have extra newlines for better
# formatting when reported as an unhandled exception. Strip
# them here.
sys.exit(cmd + str(e).strip())
raise
def _init(self, filename, warn, warn_to_stderr, encoding):
# See __init__()
self._encoding = encoding
self.srctree = os.getenv("srctree", "")
# A prefix we can reliably strip from glob() results to get a filename
# relative to $srctree. relpath() can cause issues for symlinks,
# because it assumes symlink/../foo is the same as foo/.
self._srctree_prefix = realpath(self.srctree) + os.sep
self.warn = warn
self.warn_to_stderr = warn_to_stderr
self.warn_assign_undef = os.getenv("KCONFIG_WARN_UNDEF_ASSIGN") == "y"
self.warn_assign_override = True
self.warn_assign_redun = True
self._warn_assign_no_prompt = True
self.warnings = []
self.config_prefix = os.getenv("CONFIG_", "CONFIG_")
# Regular expressions for parsing .config files
self._set_match = _re_match(self.config_prefix + r"([^=]+)=(.*)")
self._unset_match = _re_match(r"# {}([^ ]+) is not set".format(
self.config_prefix))
self.config_header = os.getenv("KCONFIG_CONFIG_HEADER", "")
self.header_header = os.getenv("KCONFIG_AUTOHEADER_HEADER", "")
self.syms = {}
self.const_syms = {}
self.defined_syms = []
self.missing_syms = []
self.named_choices = {}
self.choices = []
self.menus = []
self.comments = []
for nmy in "n", "m", "y":
sym = Symbol()
sym.kconfig = self
sym.name = nmy