blob: d4190c26eed502963eeb70579868269b041dc573 [file] [log] [blame]
Andrew Geisslerc9f78652020-09-18 14:11:35 -05001.. SPDX-License-Identifier: CC-BY-2.5
2
3====================
4Syntax and Operators
5====================
6
7|
8
9BitBake files have their own syntax. The syntax has similarities to
10several other languages but also has some unique features. This section
11describes the available syntax and operators as well as provides
12examples.
13
14Basic Syntax
15============
16
17This section provides some basic syntax examples.
18
19Basic Variable Setting
20----------------------
21
22The following example sets ``VARIABLE`` to "value". This assignment
23occurs immediately as the statement is parsed. It is a "hard"
24assignment. ::
25
26 VARIABLE = "value"
27
28As expected, if you include leading or
29trailing spaces as part of an assignment, the spaces are retained: ::
30
31 VARIABLE = " value"
32 VARIABLE = "value "
33
34Setting ``VARIABLE`` to "" sets
35it to an empty string, while setting the variable to " " sets it to a
36blank space (i.e. these are not the same values). ::
37
38 VARIABLE = ""
39 VARIABLE = " "
40
41You can use single quotes instead of double quotes when setting a
42variable's value. Doing so allows you to use values that contain the
43double quote character: ::
44
45 VARIABLE = 'I have a " in my value'
46
47.. note::
48
49 Unlike in Bourne shells, single quotes work identically to double
50 quotes in all other ways. They do not suppress variable expansions.
51
52Modifying Existing Variables
53----------------------------
54
55Sometimes you need to modify existing variables. Following are some
56cases where you might find you want to modify an existing variable:
57
58- Customize a recipe that uses the variable.
59
60- Change a variable's default value used in a ``*.bbclass`` file.
61
62- Change the variable in a ``*.bbappend`` file to override the variable
63 in the original recipe.
64
65- Change the variable in a configuration file so that the value
66 overrides an existing configuration.
67
68Changing a variable value can sometimes depend on how the value was
69originally assigned and also on the desired intent of the change. In
70particular, when you append a value to a variable that has a default
71value, the resulting value might not be what you expect. In this case,
72the value you provide might replace the value rather than append to the
73default value.
74
75If after you have changed a variable's value and something unexplained
76occurs, you can use BitBake to check the actual value of the suspect
77variable. You can make these checks for both configuration and recipe
78level changes:
79
80- For configuration changes, use the following: ::
81
82 $ bitbake -e
83
84 This
85 command displays variable values after the configuration files (i.e.
86 ``local.conf``, ``bblayers.conf``, ``bitbake.conf`` and so forth)
87 have been parsed.
88
89 .. note::
90
91 Variables that are exported to the environment are preceded by the
92 string "export" in the command's output.
93
94- For recipe changes, use the following: ::
95
96 $ bitbake recipe -e \| grep VARIABLE="
97
98 This command checks to see if the variable actually makes
99 it into a specific recipe.
100
101Line Joining
102------------
103
104Outside of :ref:`functions <bitbake-user-manual/bitbake-user-manual-metadata:functions>`,
105BitBake joins any line ending in
106a backslash character ("\") with the following line before parsing
107statements. The most common use for the "\" character is to split
108variable assignments over multiple lines, as in the following example: ::
109
110 FOO = "bar \
111 baz \
112 qaz"
113
114Both the "\" character and the newline
115character that follow it are removed when joining lines. Thus, no
116newline characters end up in the value of ``FOO``.
117
118Consider this additional example where the two assignments both assign
119"barbaz" to ``FOO``: ::
120
121 FOO = "barbaz"
122 FOO = "bar\
123 baz"
124
125.. note::
126
127 BitBake does not interpret escape sequences like "\n" in variable
128 values. For these to have an effect, the value must be passed to some
129 utility that interprets escape sequences, such as
130 ``printf`` or ``echo -n``.
131
132Variable Expansion
133------------------
134
135Variables can reference the contents of other variables using a syntax
136that is similar to variable expansion in Bourne shells. The following
137assignments result in A containing "aval" and B evaluating to
138"preavalpost". ::
139
140 A = "aval"
141 B = "pre${A}post"
142
143.. note::
144
145 Unlike in Bourne shells, the curly braces are mandatory: Only ``${FOO}`` and not
146 ``$FOO`` is recognized as an expansion of ``FOO``.
147
148The "=" operator does not immediately expand variable references in the
149right-hand side. Instead, expansion is deferred until the variable
150assigned to is actually used. The result depends on the current values
151of the referenced variables. The following example should clarify this
152behavior: ::
153
154 A = "${B} baz"
155 B = "${C} bar"
156 C = "foo"
157 *At this point, ${A} equals "foo bar baz"*
158 C = "qux"
159 *At this point, ${A} equals "qux bar baz"*
160 B = "norf"
161 *At this point, ${A} equals "norf baz"\*
162
163Contrast this behavior with the
164:ref:`bitbake-user-manual/bitbake-user-manual-metadata:immediate variable
165expansion (:=)` operator.
166
167If the variable expansion syntax is used on a variable that does not
168exist, the string is kept as is. For example, given the following
169assignment, ``BAR`` expands to the literal string "${FOO}" as long as
170``FOO`` does not exist. ::
171
172 BAR = "${FOO}"
173
174Setting a default value (?=)
175----------------------------
176
177You can use the "?=" operator to achieve a "softer" assignment for a
178variable. This type of assignment allows you to define a variable if it
179is undefined when the statement is parsed, but to leave the value alone
180if the variable has a value. Here is an example: ::
181
182 A ?= "aval"
183
184If ``A`` is
185set at the time this statement is parsed, the variable retains its
186value. However, if ``A`` is not set, the variable is set to "aval".
187
188.. note::
189
190 This assignment is immediate. Consequently, if multiple "?="
191 assignments to a single variable exist, the first of those ends up
192 getting used.
193
194Setting a weak default value (??=)
195----------------------------------
196
197It is possible to use a "weaker" assignment than in the previous section
198by using the "??=" operator. This assignment behaves identical to "?="
199except that the assignment is made at the end of the parsing process
200rather than immediately. Consequently, when multiple "??=" assignments
201exist, the last one is used. Also, any "=" or "?=" assignment will
202override the value set with "??=". Here is an example: ::
203
204 A ??= "somevalue"
205 A ??= "someothervalue"
206
207If ``A`` is set before the above statements are
208parsed, the variable retains its value. If ``A`` is not set, the
209variable is set to "someothervalue".
210
211Again, this assignment is a "lazy" or "weak" assignment because it does
212not occur until the end of the parsing process.
213
214Immediate variable expansion (:=)
215---------------------------------
216
217The ":=" operator results in a variable's contents being expanded
218immediately, rather than when the variable is actually used: ::
219
220 T = "123"
221 A := "test ${T}"
222 T = "456"
223 B := "${T} ${C}"
224 C = "cval"
225 C := "${C}append"
226
227In this example, ``A`` contains "test 123", even though the final value
228of ``T`` is "456". The variable ``B`` will end up containing "456
229cvalappend". This is because references to undefined variables are
230preserved as is during (immediate)expansion. This is in contrast to GNU
231Make, where undefined variables expand to nothing. The variable ``C``
232contains "cvalappend" since ``${C}`` immediately expands to "cval".
233
234.. _appending-and-prepending:
235
236Appending (+=) and prepending (=+) With Spaces
237----------------------------------------------
238
239Appending and prepending values is common and can be accomplished using
240the "+=" and "=+" operators. These operators insert a space between the
241current value and prepended or appended value.
242
243These operators take immediate effect during parsing. Here are some
244examples: ::
245
246 B = "bval"
247 B += "additionaldata"
248 C = "cval"
249 C =+ "test"
250
251The variable ``B`` contains "bval additionaldata" and ``C`` contains "test
252cval".
253
254.. _appending-and-prepending-without-spaces:
255
256Appending (.=) and Prepending (=.) Without Spaces
257-------------------------------------------------
258
259If you want to append or prepend values without an inserted space, use
260the ".=" and "=." operators.
261
262These operators take immediate effect during parsing. Here are some
263examples: ::
264
265 B = "bval"
266 B .= "additionaldata"
267 C = "cval"
268 C =. "test"
269
270The variable ``B`` contains "bvaladditionaldata" and ``C`` contains
271"testcval".
272
273Appending and Prepending (Override Style Syntax)
274------------------------------------------------
275
276You can also append and prepend a variable's value using an override
277style syntax. When you use this syntax, no spaces are inserted.
278
279These operators differ from the ":=", ".=", "=.", "+=", and "=+"
280operators in that their effects are applied at variable expansion time
281rather than being immediately applied. Here are some examples: ::
282
283 B = "bval"
284 B_append = " additional data"
285 C = "cval"
286 C_prepend = "additional data "
287 D = "dval"
288 D_append = "additional data"
289
290The variable ``B``
291becomes "bval additional data" and ``C`` becomes "additional data cval".
292The variable ``D`` becomes "dvaladditional data".
293
294.. note::
295
296 You must control all spacing when you use the override syntax.
297
298It is also possible to append and prepend to shell functions and
299BitBake-style Python functions. See the ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:shell functions`" and ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:bitbake-style python functions`"
300sections for examples.
301
302.. _removing-override-style-syntax:
303
304Removal (Override Style Syntax)
305-------------------------------
306
307You can remove values from lists using the removal override style
308syntax. Specifying a value for removal causes all occurrences of that
309value to be removed from the variable.
310
311When you use this syntax, BitBake expects one or more strings.
312Surrounding spaces and spacing are preserved. Here is an example: ::
313
314 FOO = "123 456 789 123456 123 456 123 456"
315 FOO_remove = "123"
316 FOO_remove = "456"
317 FOO2 = " abc def ghi abcdef abc def abc def def"
318 FOO2_remove = "\
319 def \
320 abc \
321 ghi \
322 "
323
324The variable ``FOO`` becomes
325" 789 123456 " and ``FOO2`` becomes " abcdef ".
326
327Like "_append" and "_prepend", "_remove" is applied at variable
328expansion time.
329
330Override Style Operation Advantages
331-----------------------------------
332
333An advantage of the override style operations "_append", "_prepend", and
334"_remove" as compared to the "+=" and "=+" operators is that the
335override style operators provide guaranteed operations. For example,
336consider a class ``foo.bbclass`` that needs to add the value "val" to
337the variable ``FOO``, and a recipe that uses ``foo.bbclass`` as follows: ::
338
339 inherit foo
340 FOO = "initial"
341
342If ``foo.bbclass`` uses the "+=" operator,
343as follows, then the final value of ``FOO`` will be "initial", which is
344not what is desired: ::
345
346 FOO += "val"
347
348If, on the other hand, ``foo.bbclass``
349uses the "_append" operator, then the final value of ``FOO`` will be
350"initial val", as intended: ::
351
352 FOO_append = " val"
353
354.. note::
355
356 It is never necessary to use "+=" together with "_append". The following
357 sequence of assignments appends "barbaz" to FOO: ::
358
359 FOO_append = "bar"
360 FOO_append = "baz"
361
362
363 The only effect of changing the second assignment in the previous
364 example to use "+=" would be to add a space before "baz" in the
365 appended value (due to how the "+=" operator works).
366
367Another advantage of the override style operations is that you can
368combine them with other overrides as described in the
369":ref:`bitbake-user-manual/bitbake-user-manual-metadata:conditional syntax (overrides)`" section.
370
371Variable Flag Syntax
372--------------------
373
374Variable flags are BitBake's implementation of variable properties or
375attributes. It is a way of tagging extra information onto a variable.
376You can find more out about variable flags in general in the
377":ref:`bitbake-user-manual/bitbake-user-manual-metadata:variable flags`" section.
378
379You can define, append, and prepend values to variable flags. All the
380standard syntax operations previously mentioned work for variable flags
381except for override style syntax (i.e. "_prepend", "_append", and
382"_remove").
383
384Here are some examples showing how to set variable flags: ::
385
386 FOO[a] = "abc"
387 FOO[b] = "123"
388 FOO[a] += "456"
389
390The variable ``FOO`` has two flags:
391``[a]`` and ``[b]``. The flags are immediately set to "abc" and "123",
392respectively. The ``[a]`` flag becomes "abc 456".
393
394No need exists to pre-define variable flags. You can simply start using
395them. One extremely common application is to attach some brief
396documentation to a BitBake variable as follows: ::
397
398 CACHE[doc] = "The directory holding the cache of the metadata."
399
400Inline Python Variable Expansion
401--------------------------------
402
403You can use inline Python variable expansion to set variables. Here is
404an example: ::
405
406 DATE = "${@time.strftime('%Y%m%d',time.gmtime())}"
407
408This example results in the ``DATE`` variable being set to the current date.
409
410Probably the most common use of this feature is to extract the value of
411variables from BitBake's internal data dictionary, ``d``. The following
412lines select the values of a package name and its version number,
413respectively: ::
414
415 PN = "${@bb.parse.BBHandler.vars_from_file(d.getVar('FILE', False),d)[0] or 'defaultpkgname'}"
416 PV = "${@bb.parse.BBHandler.vars_from_file(d.getVar('FILE', False),d)[1] or '1.0'}"
417
418.. note::
419
420 Inline Python expressions work just like variable expansions insofar as the
421 "=" and ":=" operators are concerned. Given the following assignment, foo()
422 is called each time FOO is expanded: ::
423
424 FOO = "${@foo()}"
425
426 Contrast this with the following immediate assignment, where foo() is only
427 called once, while the assignment is parsed: ::
428
429 FOO := "${@foo()}"
430
431For a different way to set variables with Python code during parsing,
432see the
433":ref:`bitbake-user-manual/bitbake-user-manual-metadata:anonymous python functions`" section.
434
435Unsetting variables
436-------------------
437
438It is possible to completely remove a variable or a variable flag from
439BitBake's internal data dictionary by using the "unset" keyword. Here is
440an example: ::
441
442 unset DATE
443 unset do_fetch[noexec]
444
445These two statements remove the ``DATE`` and the ``do_fetch[noexec]`` flag.
446
447Providing Pathnames
448-------------------
449
450When specifying pathnames for use with BitBake, do not use the tilde
451("~") character as a shortcut for your home directory. Doing so might
452cause BitBake to not recognize the path since BitBake does not expand
453this character in the same way a shell would.
454
455Instead, provide a fuller path as the following example illustrates: ::
456
457 BBLAYERS ?= " \
458 /home/scott-lenovo/LayerA \
459 "
460
461Exporting Variables to the Environment
462======================================
463
464You can export variables to the environment of running tasks by using
465the ``export`` keyword. For example, in the following example, the
466``do_foo`` task prints "value from the environment" when run: ::
467
468 export ENV_VARIABLE
469 ENV_VARIABLE = "value from the environment"
470
471 do_foo() {
472 bbplain "$ENV_VARIABLE"
473 }
474
475.. note::
476
477 BitBake does not expand ``$ENV_VARIABLE`` in this case because it lacks the
478 obligatory ``{}`` . Rather, ``$ENV_VARIABLE`` is expanded by the shell.
479
480It does not matter whether ``export ENV_VARIABLE`` appears before or
481after assignments to ``ENV_VARIABLE``.
482
483It is also possible to combine ``export`` with setting a value for the
484variable. Here is an example: ::
485
486 export ENV_VARIABLE = "variable-value"
487
488In the output of ``bitbake -e``, variables that are exported to the
489environment are preceded by "export".
490
491Among the variables commonly exported to the environment are ``CC`` and
492``CFLAGS``, which are picked up by many build systems.
493
494Conditional Syntax (Overrides)
495==============================
496
497BitBake uses :term:`OVERRIDES` to control what
498variables are overridden after BitBake parses recipes and configuration
499files. This section describes how you can use ``OVERRIDES`` as
500conditional metadata, talks about key expansion in relationship to
501``OVERRIDES``, and provides some examples to help with understanding.
502
503Conditional Metadata
504--------------------
505
506You can use ``OVERRIDES`` to conditionally select a specific version of
507a variable and to conditionally append or prepend the value of a
508variable.
509
510.. note::
511
512 Overrides can only use lower-case characters. Additionally,
513 underscores are not permitted in override names as they are used to
514 separate overrides from each other and from the variable name.
515
516- *Selecting a Variable:* The ``OVERRIDES`` variable is a
517 colon-character-separated list that contains items for which you want
518 to satisfy conditions. Thus, if you have a variable that is
Andrew Geisslerf0343792020-11-18 10:42:21 -0600519 conditional on "arm", and "arm" is in ``OVERRIDES``, then the
520 "arm"-specific version of the variable is used rather than the
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500521 non-conditional version. Here is an example: ::
522
523 OVERRIDES = "architecture:os:machine"
524 TEST = "default"
525 TEST_os = "osspecific"
526 TEST_nooverride = "othercondvalue"
527
528 In this example, the ``OVERRIDES``
529 variable lists three overrides: "architecture", "os", and "machine".
530 The variable ``TEST`` by itself has a default value of "default". You
531 select the os-specific version of the ``TEST`` variable by appending
532 the "os" override to the variable (i.e. ``TEST_os``).
533
534 To better understand this, consider a practical example that assumes
535 an OpenEmbedded metadata-based Linux kernel recipe file. The
536 following lines from the recipe file first set the kernel branch
537 variable ``KBRANCH`` to a default value, then conditionally override
538 that value based on the architecture of the build: ::
539
540 KBRANCH = "standard/base"
541 KBRANCH_qemuarm = "standard/arm-versatile-926ejs"
542 KBRANCH_qemumips = "standard/mti-malta32"
543 KBRANCH_qemuppc = "standard/qemuppc"
544 KBRANCH_qemux86 = "standard/common-pc/base"
545 KBRANCH_qemux86-64 = "standard/common-pc-64/base"
546 KBRANCH_qemumips64 = "standard/mti-malta64"
547
548- *Appending and Prepending:* BitBake also supports append and prepend
549 operations to variable values based on whether a specific item is
550 listed in ``OVERRIDES``. Here is an example: ::
551
552 DEPENDS = "glibc ncurses"
553 OVERRIDES = "machine:local"
554 DEPENDS_append_machine = "libmad"
555
556 In this example, ``DEPENDS`` becomes "glibc ncurses libmad".
557
558 Again, using an OpenEmbedded metadata-based kernel recipe file as an
559 example, the following lines will conditionally append to the
560 ``KERNEL_FEATURES`` variable based on the architecture: ::
561
562 KERNEL_FEATURES_append = " ${KERNEL_EXTRA_FEATURES}"
563 KERNEL_FEATURES_append_qemux86=" cfg/sound.scc cfg/paravirt_kvm.scc"
564 KERNEL_FEATURES_append_qemux86-64=" cfg/sound.scc cfg/paravirt_kvm.scc"
565
566- *Setting a Variable for a Single Task:* BitBake supports setting a
567 variable just for the duration of a single task. Here is an example: ::
568
569 FOO_task-configure = "val 1"
570 FOO_task-compile = "val 2"
571
572 In the
573 previous example, ``FOO`` has the value "val 1" while the
574 ``do_configure`` task is executed, and the value "val 2" while the
575 ``do_compile`` task is executed.
576
577 Internally, this is implemented by prepending the task (e.g.
578 "task-compile:") to the value of
579 :term:`OVERRIDES` for the local datastore of the
580 ``do_compile`` task.
581
582 You can also use this syntax with other combinations (e.g.
583 "``_prepend``") as shown in the following example: ::
584
585 EXTRA_OEMAKE_prepend_task-compile = "${PARALLEL_MAKE} "
586
587Key Expansion
588-------------
589
590Key expansion happens when the BitBake datastore is finalized. To better
591understand this, consider the following example: ::
592
593 A${B} = "X"
594 B = "2"
595 A2 = "Y"
596
597In this case, after all the parsing is complete, BitBake expands
598``${B}`` into "2". This expansion causes ``A2``, which was set to "Y"
599before the expansion, to become "X".
600
601.. _variable-interaction-worked-examples:
602
603Examples
604--------
605
606Despite the previous explanations that show the different forms of
607variable definitions, it can be hard to work out exactly what happens
608when variable operators, conditional overrides, and unconditional
609overrides are combined. This section presents some common scenarios
610along with explanations for variable interactions that typically confuse
611users.
612
613There is often confusion concerning the order in which overrides and
614various "append" operators take effect. Recall that an append or prepend
615operation using "_append" and "_prepend" does not result in an immediate
616assignment as would "+=", ".=", "=+", or "=.". Consider the following
617example: ::
618
619 OVERRIDES = "foo"
620 A = "Z"
621 A_foo_append = "X"
622
623For this case,
624``A`` is unconditionally set to "Z" and "X" is unconditionally and
625immediately appended to the variable ``A_foo``. Because overrides have
626not been applied yet, ``A_foo`` is set to "X" due to the append and
627``A`` simply equals "Z".
628
629Applying overrides, however, changes things. Since "foo" is listed in
630``OVERRIDES``, the conditional variable ``A`` is replaced with the "foo"
631version, which is equal to "X". So effectively, ``A_foo`` replaces
632``A``.
633
634This next example changes the order of the override and the append: ::
635
636 OVERRIDES = "foo"
637 A = "Z"
638 A_append_foo = "X"
639
640For this case, before
641overrides are handled, ``A`` is set to "Z" and ``A_append_foo`` is set
642to "X". Once the override for "foo" is applied, however, ``A`` gets
643appended with "X". Consequently, ``A`` becomes "ZX". Notice that spaces
644are not appended.
645
646This next example has the order of the appends and overrides reversed
647back as in the first example: ::
648
649 OVERRIDES = "foo"
650 A = "Y"
651 A_foo_append = "Z"
652 A_foo_append = "X"
653
654For this case, before any overrides are resolved,
655``A`` is set to "Y" using an immediate assignment. After this immediate
656assignment, ``A_foo`` is set to "Z", and then further appended with "X"
657leaving the variable set to "ZX". Finally, applying the override for
658"foo" results in the conditional variable ``A`` becoming "ZX" (i.e.
659``A`` is replaced with ``A_foo``).
660
661This final example mixes in some varying operators: ::
662
663 A = "1"
664 A_append = "2"
665 A_append = "3"
666 A += "4"
667 A .= "5"
668
669For this case, the type of append
670operators are affecting the order of assignments as BitBake passes
671through the code multiple times. Initially, ``A`` is set to "1 45"
672because of the three statements that use immediate operators. After
673these assignments are made, BitBake applies the "_append" operations.
674Those operations result in ``A`` becoming "1 4523".
675
676Sharing Functionality
677=====================
678
679BitBake allows for metadata sharing through include files (``.inc``) and
680class files (``.bbclass``). For example, suppose you have a piece of
681common functionality such as a task definition that you want to share
682between more than one recipe. In this case, creating a ``.bbclass`` file
683that contains the common functionality and then using the ``inherit``
684directive in your recipes to inherit the class would be a common way to
685share the task.
686
687This section presents the mechanisms BitBake provides to allow you to
688share functionality between recipes. Specifically, the mechanisms
689include ``include``, ``inherit``, ``INHERIT``, and ``require``
690directives.
691
692Locating Include and Class Files
693--------------------------------
694
695BitBake uses the :term:`BBPATH` variable to locate
696needed include and class files. Additionally, BitBake searches the
697current directory for ``include`` and ``require`` directives.
698
699.. note::
700
701 The BBPATH variable is analogous to the environment variable PATH .
702
703In order for include and class files to be found by BitBake, they need
704to be located in a "classes" subdirectory that can be found in
705``BBPATH``.
706
707``inherit`` Directive
708---------------------
709
710When writing a recipe or class file, you can use the ``inherit``
711directive to inherit the functionality of a class (``.bbclass``).
712BitBake only supports this directive when used within recipe and class
713files (i.e. ``.bb`` and ``.bbclass``).
714
715The ``inherit`` directive is a rudimentary means of specifying
716functionality contained in class files that your recipes require. For
717example, you can easily abstract out the tasks involved in building a
718package that uses Autoconf and Automake and put those tasks into a class
719file and then have your recipe inherit that class file.
720
721As an example, your recipes could use the following directive to inherit
722an ``autotools.bbclass`` file. The class file would contain common
723functionality for using Autotools that could be shared across recipes: ::
724
725 inherit autotools
726
727In this case, BitBake would search for the directory
728``classes/autotools.bbclass`` in ``BBPATH``.
729
730.. note::
731
732 You can override any values and functions of the inherited class
733 within your recipe by doing so after the "inherit" statement.
734
735If you want to use the directive to inherit multiple classes, separate
736them with spaces. The following example shows how to inherit both the
737``buildhistory`` and ``rm_work`` classes: ::
738
739 inherit buildhistory rm_work
740
741An advantage with the inherit directive as compared to both the
742:ref:`include <bitbake-user-manual/bitbake-user-manual-metadata:\`\`include\`\` directive>` and :ref:`require <bitbake-user-manual/bitbake-user-manual-metadata:\`\`require\`\` directive>`
743directives is that you can inherit class files conditionally. You can
744accomplish this by using a variable expression after the ``inherit``
745statement. Here is an example: ::
746
747 inherit ${VARNAME}
748
749If ``VARNAME`` is
750going to be set, it needs to be set before the ``inherit`` statement is
751parsed. One way to achieve a conditional inherit in this case is to use
752overrides: ::
753
754 VARIABLE = ""
755 VARIABLE_someoverride = "myclass"
756
757Another method is by using anonymous Python. Here is an example: ::
758
759 python () {
760 if condition == value:
761 d.setVar('VARIABLE', 'myclass')
762 else:
763 d.setVar('VARIABLE', '')
764 }
765
766Alternatively, you could use an in-line Python expression in the
767following form: ::
768
769 inherit ${@'classname' if condition else ''}
770 inherit ${@functionname(params)}
771
772In all cases, if the expression evaluates to an
773empty string, the statement does not trigger a syntax error because it
774becomes a no-op.
775
776``include`` Directive
777---------------------
778
779BitBake understands the ``include`` directive. This directive causes
780BitBake to parse whatever file you specify, and to insert that file at
781that location. The directive is much like its equivalent in Make except
782that if the path specified on the include line is a relative path,
783BitBake locates the first file it can find within ``BBPATH``.
784
785The include directive is a more generic method of including
786functionality as compared to the :ref:`inherit <bitbake-user-manual/bitbake-user-manual-metadata:\`\`inherit\`\` directive>`
787directive, which is restricted to class (i.e. ``.bbclass``) files. The
788include directive is applicable for any other kind of shared or
789encapsulated functionality or configuration that does not suit a
790``.bbclass`` file.
791
792As an example, suppose you needed a recipe to include some self-test
793definitions: ::
794
795 include test_defs.inc
796
797.. note::
798
799 The include directive does not produce an error when the file cannot be
800 found. Consequently, it is recommended that if the file you are including is
801 expected to exist, you should use :ref:`require <require-inclusion>` instead
802 of include . Doing so makes sure that an error is produced if the file cannot
803 be found.
804
805.. _require-inclusion:
806
807``require`` Directive
808---------------------
809
810BitBake understands the ``require`` directive. This directive behaves
811just like the ``include`` directive with the exception that BitBake
812raises a parsing error if the file to be included cannot be found. Thus,
813any file you require is inserted into the file that is being parsed at
814the location of the directive.
815
816The require directive, like the include directive previously described,
817is a more generic method of including functionality as compared to the
818:ref:`inherit <bitbake-user-manual/bitbake-user-manual-metadata:\`\`inherit\`\` directive>` directive, which is restricted to class
819(i.e. ``.bbclass``) files. The require directive is applicable for any
820other kind of shared or encapsulated functionality or configuration that
821does not suit a ``.bbclass`` file.
822
823Similar to how BitBake handles :ref:`include <bitbake-user-manual/bitbake-user-manual-metadata:\`\`include\`\` directive>`, if
824the path specified on the require line is a relative path, BitBake
825locates the first file it can find within ``BBPATH``.
826
827As an example, suppose you have two versions of a recipe (e.g.
828``foo_1.2.2.bb`` and ``foo_2.0.0.bb``) where each version contains some
829identical functionality that could be shared. You could create an
830include file named ``foo.inc`` that contains the common definitions
831needed to build "foo". You need to be sure ``foo.inc`` is located in the
832same directory as your two recipe files as well. Once these conditions
833are set up, you can share the functionality using a ``require``
834directive from within each recipe: ::
835
836 require foo.inc
837
838``INHERIT`` Configuration Directive
839-----------------------------------
840
841When creating a configuration file (``.conf``), you can use the
842:term:`INHERIT` configuration directive to inherit a
843class. BitBake only supports this directive when used within a
844configuration file.
845
846As an example, suppose you needed to inherit a class file called
847``abc.bbclass`` from a configuration file as follows: ::
848
849 INHERIT += "abc"
850
851This configuration directive causes the named class to be inherited at
852the point of the directive during parsing. As with the ``inherit``
853directive, the ``.bbclass`` file must be located in a "classes"
854subdirectory in one of the directories specified in ``BBPATH``.
855
856.. note::
857
858 Because .conf files are parsed first during BitBake's execution, using
859 INHERIT to inherit a class effectively inherits the class globally (i.e. for
860 all recipes).
861
862If you want to use the directive to inherit multiple classes, you can
863provide them on the same line in the ``local.conf`` file. Use spaces to
864separate the classes. The following example shows how to inherit both
865the ``autotools`` and ``pkgconfig`` classes: ::
866
867 INHERIT += "autotools pkgconfig"
868
869Functions
870=========
871
872As with most languages, functions are the building blocks that are used
873to build up operations into tasks. BitBake supports these types of
874functions:
875
876- *Shell Functions:* Functions written in shell script and executed
877 either directly as functions, tasks, or both. They can also be called
878 by other shell functions.
879
880- *BitBake-Style Python Functions:* Functions written in Python and
881 executed by BitBake or other Python functions using
882 ``bb.build.exec_func()``.
883
884- *Python Functions:* Functions written in Python and executed by
885 Python.
886
887- *Anonymous Python Functions:* Python functions executed automatically
888 during parsing.
889
890Regardless of the type of function, you can only define them in class
891(``.bbclass``) and recipe (``.bb`` or ``.inc``) files.
892
893Shell Functions
894---------------
895
896Functions written in shell script and executed either directly as
897functions, tasks, or both. They can also be called by other shell
898functions. Here is an example shell function definition: ::
899
900 some_function () {
901 echo "Hello World"
902 }
903
904When you create these types of functions in
905your recipe or class files, you need to follow the shell programming
906rules. The scripts are executed by ``/bin/sh``, which may not be a bash
907shell but might be something such as ``dash``. You should not use
908Bash-specific script (bashisms).
909
910Overrides and override-style operators like ``_append`` and ``_prepend``
911can also be applied to shell functions. Most commonly, this application
912would be used in a ``.bbappend`` file to modify functions in the main
913recipe. It can also be used to modify functions inherited from classes.
914
915As an example, consider the following: ::
916
917 do_foo() {
918 bbplain first
919 fn
920 }
921
922 fn_prepend() {
923 bbplain second
924 }
925
926 fn() {
927 bbplain third
928 }
929
930 do_foo_append() {
931 bbplain fourth
932 }
933
934Running ``do_foo`` prints the following: ::
935
936 recipename do_foo: first
937 recipename do_foo: second
938 recipename do_foo: third
939 recipename do_foo: fourth
940
941.. note::
942
943 Overrides and override-style operators can be applied to any shell
944 function, not just :ref:`tasks <bitbake-user-manual/bitbake-user-manual-metadata:tasks>`.
945
946You can use the ``bitbake -e`` recipename command to view the final
947assembled function after all overrides have been applied.
948
949BitBake-Style Python Functions
950------------------------------
951
952These functions are written in Python and executed by BitBake or other
953Python functions using ``bb.build.exec_func()``.
954
955An example BitBake function is: ::
956
957 python some_python_function () {
958 d.setVar("TEXT", "Hello World")
959 print d.getVar("TEXT")
960 }
961
962Because the
963Python "bb" and "os" modules are already imported, you do not need to
964import these modules. Also in these types of functions, the datastore
965("d") is a global variable and is always automatically available.
966
967.. note::
968
969 Variable expressions (e.g. ``${X}`` ) are no longer expanded within Python
970 functions. This behavior is intentional in order to allow you to freely set
971 variable values to expandable expressions without having them expanded
972 prematurely. If you do wish to expand a variable within a Python function,
973 use ``d.getVar("X")`` . Or, for more complicated expressions, use ``d.expand()``.
974
975Similar to shell functions, you can also apply overrides and
976override-style operators to BitBake-style Python functions.
977
978As an example, consider the following: ::
979
980 python do_foo_prepend() {
981 bb.plain("first")
982 }
983
984 python do_foo() {
985 bb.plain("second")
986 }
987
988 python do_foo_append() {
989 bb.plain("third")
990 }
991
992Running ``do_foo`` prints the following: ::
993
994 recipename do_foo: first
995 recipename do_foo: second
996 recipename do_foo: third
997
998You can use the ``bitbake -e`` recipename command to view
999the final assembled function after all overrides have been applied.
1000
1001Python Functions
1002----------------
1003
1004These functions are written in Python and are executed by other Python
1005code. Examples of Python functions are utility functions that you intend
1006to call from in-line Python or from within other Python functions. Here
1007is an example: ::
1008
1009 def get_depends(d):
1010 if d.getVar('SOMECONDITION'):
1011 return "dependencywithcond"
1012 else:
1013 return "dependency"
1014
1015 SOMECONDITION = "1"
1016 DEPENDS = "${@get_depends(d)}"
1017
1018This would result in ``DEPENDS`` containing ``dependencywithcond``.
1019
1020Here are some things to know about Python functions:
1021
1022- Python functions can take parameters.
1023
1024- The BitBake datastore is not automatically available. Consequently,
1025 you must pass it in as a parameter to the function.
1026
1027- The "bb" and "os" Python modules are automatically available. You do
1028 not need to import them.
1029
1030BitBake-Style Python Functions Versus Python Functions
1031------------------------------------------------------
1032
1033Following are some important differences between BitBake-style Python
1034functions and regular Python functions defined with "def":
1035
1036- Only BitBake-style Python functions can be :ref:`tasks <bitbake-user-manual/bitbake-user-manual-metadata:tasks>`.
1037
1038- Overrides and override-style operators can only be applied to
1039 BitBake-style Python functions.
1040
1041- Only regular Python functions can take arguments and return values.
1042
1043- :ref:`Variable flags <bitbake-user-manual/bitbake-user-manual-metadata:variable flags>` such as
1044 ``[dirs]``, ``[cleandirs]``, and ``[lockfiles]`` can be used on BitBake-style
1045 Python functions, but not on regular Python functions.
1046
1047- BitBake-style Python functions generate a separate
1048 ``${``\ :term:`T`\ ``}/run.``\ function-name\ ``.``\ pid
1049 script that is executed to run the function, and also generate a log
1050 file in ``${T}/log.``\ function-name\ ``.``\ pid if they are executed
1051 as tasks.
1052
1053 Regular Python functions execute "inline" and do not generate any
1054 files in ``${T}``.
1055
1056- Regular Python functions are called with the usual Python syntax.
1057 BitBake-style Python functions are usually tasks and are called
1058 directly by BitBake, but can also be called manually from Python code
1059 by using the ``bb.build.exec_func()`` function. Here is an example: ::
1060
1061 bb.build.exec_func("my_bitbake_style_function", d)
1062
1063 .. note::
1064
1065 ``bb.build.exec_func()`` can also be used to run shell functions from Python
1066 code. If you want to run a shell function before a Python function within
1067 the same task, then you can use a parent helper Python function that
1068 starts by running the shell function with ``bb.build.exec_func()`` and then
1069 runs the Python code.
1070
1071 To detect errors from functions executed with
1072 ``bb.build.exec_func()``, you can catch the ``bb.build.FuncFailed``
1073 exception.
1074
1075 .. note::
1076
1077 Functions in metadata (recipes and classes) should not themselves raise
1078 ``bb.build.FuncFailed``. Rather, ``bb.build.FuncFailed`` should be viewed as a
1079 general indicator that the called function failed by raising an
1080 exception. For example, an exception raised by ``bb.fatal()`` will be caught
1081 inside ``bb.build.exec_func()``, and a ``bb.build.FuncFailed`` will be raised in
1082 response.
1083
1084Due to their simplicity, you should prefer regular Python functions over
1085BitBake-style Python functions unless you need a feature specific to
1086BitBake-style Python functions. Regular Python functions in metadata are
1087a more recent invention than BitBake-style Python functions, and older
1088code tends to use ``bb.build.exec_func()`` more often.
1089
1090Anonymous Python Functions
1091--------------------------
1092
1093Sometimes it is useful to set variables or perform other operations
1094programmatically during parsing. To do this, you can define special
1095Python functions, called anonymous Python functions, that run at the end
1096of parsing. For example, the following conditionally sets a variable
1097based on the value of another variable: ::
1098
1099 python () {
1100 if d.getVar('SOMEVAR') == 'value':
1101 d.setVar('ANOTHERVAR', 'value2')
1102 }
1103
1104An equivalent way to mark a function as an anonymous function is to give it
1105the name "__anonymous", rather than no name.
1106
1107Anonymous Python functions always run at the end of parsing, regardless
1108of where they are defined. If a recipe contains many anonymous
1109functions, they run in the same order as they are defined within the
1110recipe. As an example, consider the following snippet: ::
1111
1112 python () {
1113 d.setVar('FOO', 'foo 2')
1114 }
1115
1116 FOO = "foo 1"
1117
1118 python () {
1119 d.appendVar('BAR',' bar 2')
1120 }
1121
1122 BAR = "bar 1"
1123
1124The previous example is conceptually
1125equivalent to the following snippet: ::
1126
1127 FOO = "foo 1"
1128 BAR = "bar 1"
1129 FOO = "foo 2"
1130 BAR += "bar 2"
1131
1132``FOO`` ends up with the value "foo 2", and
1133``BAR`` with the value "bar 1 bar 2". Just as in the second snippet, the
1134values set for the variables within the anonymous functions become
1135available to tasks, which always run after parsing.
1136
1137Overrides and override-style operators such as "``_append``" are applied
1138before anonymous functions run. In the following example, ``FOO`` ends
1139up with the value "foo from anonymous": ::
1140
1141 FOO = "foo"
1142 FOO_append = " from outside"
1143
1144 python () {
1145 d.setVar("FOO", "foo from anonymous")
1146 }
1147
1148For methods
1149you can use with anonymous Python functions, see the
1150":ref:`bitbake-user-manual/bitbake-user-manual-metadata:functions you can call from within python`"
1151section. For a different method to run Python code during parsing, see
1152the ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:inline python variable expansion`" section.
1153
1154Flexible Inheritance for Class Functions
1155----------------------------------------
1156
1157Through coding techniques and the use of ``EXPORT_FUNCTIONS``, BitBake
1158supports exporting a function from a class such that the class function
1159appears as the default implementation of the function, but can still be
1160called if a recipe inheriting the class needs to define its own version
1161of the function.
1162
1163To understand the benefits of this feature, consider the basic scenario
1164where a class defines a task function and your recipe inherits the
1165class. In this basic scenario, your recipe inherits the task function as
1166defined in the class. If desired, your recipe can add to the start and
1167end of the function by using the "_prepend" or "_append" operations
1168respectively, or it can redefine the function completely. However, if it
1169redefines the function, there is no means for it to call the class
1170version of the function. ``EXPORT_FUNCTIONS`` provides a mechanism that
1171enables the recipe's version of the function to call the original
1172version of the function.
1173
1174To make use of this technique, you need the following things in place:
1175
1176- The class needs to define the function as follows: ::
1177
1178 classname_functionname
1179
1180 For example, if you have a class file
1181 ``bar.bbclass`` and a function named ``do_foo``, the class must
1182 define the function as follows: ::
1183
1184 bar_do_foo
1185
1186- The class needs to contain the ``EXPORT_FUNCTIONS`` statement as
1187 follows: ::
1188
1189 EXPORT_FUNCTIONS functionname
1190
1191 For example, continuing with
1192 the same example, the statement in the ``bar.bbclass`` would be as
1193 follows: ::
1194
1195 EXPORT_FUNCTIONS do_foo
1196
1197- You need to call the function appropriately from within your recipe.
1198 Continuing with the same example, if your recipe needs to call the
1199 class version of the function, it should call ``bar_do_foo``.
1200 Assuming ``do_foo`` was a shell function and ``EXPORT_FUNCTIONS`` was
1201 used as above, the recipe's function could conditionally call the
1202 class version of the function as follows: ::
1203
1204 do_foo() {
1205 if [ somecondition ] ; then
1206 bar_do_foo
1207 else
1208 # Do something else
1209 fi
1210 }
1211
1212 To call your modified version of the function as defined in your recipe,
1213 call it as ``do_foo``.
1214
1215With these conditions met, your single recipe can freely choose between
1216the original function as defined in the class file and the modified
1217function in your recipe. If you do not set up these conditions, you are
1218limited to using one function or the other.
1219
1220Tasks
1221=====
1222
1223Tasks are BitBake execution units that make up the steps that BitBake
1224can run for a given recipe. Tasks are only supported in recipes and
1225classes (i.e. in ``.bb`` files and files included or inherited from
1226``.bb`` files). By convention, tasks have names that start with "do\_".
1227
1228Promoting a Function to a Task
1229------------------------------
1230
1231Tasks are either :ref:`shell functions <bitbake-user-manual/bitbake-user-manual-metadata:shell functions>` or
1232:ref:`BitBake-style Python functions <bitbake-user-manual/bitbake-user-manual-metadata:bitbake-style python functions>`
1233that have been promoted to tasks by using the ``addtask`` command. The
1234``addtask`` command can also optionally describe dependencies between
1235the task and other tasks. Here is an example that shows how to define a
1236task and declare some dependencies: ::
1237
1238 python do_printdate () {
1239 import time
1240 print time.strftime('%Y%m%d', time.gmtime())
1241 }
1242 addtask printdate after do_fetch before do_build
1243
1244The first argument to ``addtask`` is the name
1245of the function to promote to a task. If the name does not start with
1246"do\_", "do\_" is implicitly added, which enforces the convention that all
1247task names start with "do\_".
1248
1249In the previous example, the ``do_printdate`` task becomes a dependency
1250of the ``do_build`` task, which is the default task (i.e. the task run
1251by the ``bitbake`` command unless another task is specified explicitly).
1252Additionally, the ``do_printdate`` task becomes dependent upon the
1253``do_fetch`` task. Running the ``do_build`` task results in the
1254``do_printdate`` task running first.
1255
1256.. note::
1257
1258 If you try out the previous example, you might see that the
1259 ``do_printdate``
1260 task is only run the first time you build the recipe with the
1261 ``bitbake``
1262 command. This is because BitBake considers the task "up-to-date"
1263 after that initial run. If you want to force the task to always be
1264 rerun for experimentation purposes, you can make BitBake always
1265 consider the task "out-of-date" by using the
1266 :ref:`[nostamp] <bitbake-user-manual/bitbake-user-manual-metadata:Variable Flags>`
1267 variable flag, as follows: ::
1268
1269 do_printdate[nostamp] = "1"
1270
1271 You can also explicitly run the task and provide the
1272 -f option as follows: ::
1273
1274 $ bitbake recipe -c printdate -f
1275
1276 When manually selecting a task to run with the bitbake ``recipe
1277 -c task`` command, you can omit the "do\_" prefix as part of the task
1278 name.
1279
1280You might wonder about the practical effects of using ``addtask``
1281without specifying any dependencies as is done in the following example: ::
1282
1283 addtask printdate
1284
1285In this example, assuming dependencies have not been
1286added through some other means, the only way to run the task is by
1287explicitly selecting it with ``bitbake`` recipe ``-c printdate``. You
1288can use the ``do_listtasks`` task to list all tasks defined in a recipe
1289as shown in the following example: ::
1290
1291 $ bitbake recipe -c listtasks
1292
1293For more information on task dependencies, see the
1294":ref:`bitbake-user-manual/bitbake-user-manual-execution:dependencies`" section.
1295
1296See the ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:variable flags`" section for information
1297on variable flags you can use with tasks.
1298
Andrew Geissler95ac1b82021-03-31 14:34:31 -05001299.. note::
1300
1301 While it's infrequent, it's possible to define multiple tasks as
1302 dependencies when calling ``addtask``. For example, here's a snippet
1303 from the OpenEmbedded class file ``package_tar.bbclass``::
1304
1305 addtask package_write_tar before do_build after do_packagedata do_package
1306
1307 Note how the ``package_write_tar`` task has to wait until both of
1308 ``do_packagedata`` and ``do_package`` complete.
1309
Andrew Geisslerc9f78652020-09-18 14:11:35 -05001310Deleting a Task
1311---------------
1312
1313As well as being able to add tasks, you can delete them. Simply use the
1314``deltask`` command to delete a task. For example, to delete the example
1315task used in the previous sections, you would use: ::
1316
1317 deltask printdate
1318
1319If you delete a task using the ``deltask`` command and the task has
1320dependencies, the dependencies are not reconnected. For example, suppose
1321you have three tasks named ``do_a``, ``do_b``, and ``do_c``.
1322Furthermore, ``do_c`` is dependent on ``do_b``, which in turn is
1323dependent on ``do_a``. Given this scenario, if you use ``deltask`` to
1324delete ``do_b``, the implicit dependency relationship between ``do_c``
1325and ``do_a`` through ``do_b`` no longer exists, and ``do_c``
1326dependencies are not updated to include ``do_a``. Thus, ``do_c`` is free
1327to run before ``do_a``.
1328
1329If you want dependencies such as these to remain intact, use the
1330``[noexec]`` varflag to disable the task instead of using the
1331``deltask`` command to delete it: ::
1332
1333 do_b[noexec] = "1"
1334
1335Passing Information Into the Build Task Environment
1336---------------------------------------------------
1337
1338When running a task, BitBake tightly controls the shell execution
1339environment of the build tasks to make sure unwanted contamination from
1340the build machine cannot influence the build.
1341
1342.. note::
1343
1344 By default, BitBake cleans the environment to include only those
1345 things exported or listed in its whitelist to ensure that the build
1346 environment is reproducible and consistent. You can prevent this
1347 "cleaning" by setting the :term:`BB_PRESERVE_ENV` variable.
1348
1349Consequently, if you do want something to get passed into the build task
1350environment, you must take these two steps:
1351
1352#. Tell BitBake to load what you want from the environment into the
1353 datastore. You can do so through the
1354 :term:`BB_ENV_WHITELIST` and
1355 :term:`BB_ENV_EXTRAWHITE` variables. For
1356 example, assume you want to prevent the build system from accessing
1357 your ``$HOME/.ccache`` directory. The following command "whitelists"
1358 the environment variable ``CCACHE_DIR`` causing BitBake to allow that
1359 variable into the datastore: ::
1360
1361 export BB_ENV_EXTRAWHITE="$BB_ENV_EXTRAWHITE CCACHE_DIR"
1362
1363#. Tell BitBake to export what you have loaded into the datastore to the
1364 task environment of every running task. Loading something from the
1365 environment into the datastore (previous step) only makes it
1366 available in the datastore. To export it to the task environment of
1367 every running task, use a command similar to the following in your
1368 local configuration file ``local.conf`` or your distribution
1369 configuration file: ::
1370
1371 export CCACHE_DIR
1372
1373 .. note::
1374
1375 A side effect of the previous steps is that BitBake records the
1376 variable as a dependency of the build process in things like the
1377 setscene checksums. If doing so results in unnecessary rebuilds of
1378 tasks, you can whitelist the variable so that the setscene code
1379 ignores the dependency when it creates checksums.
1380
1381Sometimes, it is useful to be able to obtain information from the
1382original execution environment. BitBake saves a copy of the original
1383environment into a special variable named :term:`BB_ORIGENV`.
1384
1385The ``BB_ORIGENV`` variable returns a datastore object that can be
1386queried using the standard datastore operators such as
1387``getVar(, False)``. The datastore object is useful, for example, to
1388find the original ``DISPLAY`` variable. Here is an example: ::
1389
1390 origenv = d.getVar("BB_ORIGENV", False)
1391 bar = origenv.getVar("BAR", False)
1392
1393The previous example returns ``BAR`` from the original execution
1394environment.
1395
1396Variable Flags
1397==============
1398
1399Variable flags (varflags) help control a task's functionality and
1400dependencies. BitBake reads and writes varflags to the datastore using
1401the following command forms: ::
1402
1403 variable = d.getVarFlags("variable")
1404 self.d.setVarFlags("FOO", {"func": True})
1405
1406When working with varflags, the same syntax, with the exception of
1407overrides, applies. In other words, you can set, append, and prepend
1408varflags just like variables. See the
1409":ref:`bitbake-user-manual/bitbake-user-manual-metadata:variable flag syntax`" section for details.
1410
1411BitBake has a defined set of varflags available for recipes and classes.
1412Tasks support a number of these flags which control various
1413functionality of the task:
1414
1415- ``[cleandirs]``: Empty directories that should be created before
1416 the task runs. Directories that already exist are removed and
1417 recreated to empty them.
1418
1419- ``[depends]``: Controls inter-task dependencies. See the
1420 :term:`DEPENDS` variable and the
1421 ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:inter-task
1422 dependencies`" section for more information.
1423
1424- ``[deptask]``: Controls task build-time dependencies. See the
1425 :term:`DEPENDS` variable and the ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:build dependencies`" section for more information.
1426
1427- ``[dirs]``: Directories that should be created before the task
1428 runs. Directories that already exist are left as is. The last
1429 directory listed is used as the current working directory for the
1430 task.
1431
1432- ``[lockfiles]``: Specifies one or more lockfiles to lock while the
1433 task executes. Only one task may hold a lockfile, and any task that
1434 attempts to lock an already locked file will block until the lock is
1435 released. You can use this variable flag to accomplish mutual
1436 exclusion.
1437
1438- ``[noexec]``: When set to "1", marks the task as being empty, with
1439 no execution required. You can use the ``[noexec]`` flag to set up
1440 tasks as dependency placeholders, or to disable tasks defined
1441 elsewhere that are not needed in a particular recipe.
1442
1443- ``[nostamp]``: When set to "1", tells BitBake to not generate a
1444 stamp file for a task, which implies the task should always be
1445 executed.
1446
1447 .. caution::
1448
1449 Any task that depends (possibly indirectly) on a ``[nostamp]`` task will
1450 always be executed as well. This can cause unnecessary rebuilding if you
1451 are not careful.
1452
1453- ``[number_threads]``: Limits tasks to a specific number of
1454 simultaneous threads during execution. This varflag is useful when
1455 your build host has a large number of cores but certain tasks need to
1456 be rate-limited due to various kinds of resource constraints (e.g. to
1457 avoid network throttling). ``number_threads`` works similarly to the
1458 :term:`BB_NUMBER_THREADS` variable but is task-specific.
1459
1460 Set the value globally. For example, the following makes sure the
1461 ``do_fetch`` task uses no more than two simultaneous execution
1462 threads: do_fetch[number_threads] = "2"
1463
1464 .. warning::
1465
1466 - Setting the varflag in individual recipes rather than globally
1467 can result in unpredictable behavior.
1468
1469 - Setting the varflag to a value greater than the value used in
1470 the ``BB_NUMBER_THREADS`` variable causes ``number_threads`` to
1471 have no effect.
1472
1473- ``[postfuncs]``: List of functions to call after the completion of
1474 the task.
1475
1476- ``[prefuncs]``: List of functions to call before the task executes.
1477
1478- ``[rdepends]``: Controls inter-task runtime dependencies. See the
1479 :term:`RDEPENDS` variable, the
1480 :term:`RRECOMMENDS` variable, and the
1481 ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:inter-task dependencies`" section for
1482 more information.
1483
1484- ``[rdeptask]``: Controls task runtime dependencies. See the
1485 :term:`RDEPENDS` variable, the
1486 :term:`RRECOMMENDS` variable, and the
1487 ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:runtime dependencies`" section for more
1488 information.
1489
1490- ``[recideptask]``: When set in conjunction with ``recrdeptask``,
1491 specifies a task that should be inspected for additional
1492 dependencies.
1493
1494- ``[recrdeptask]``: Controls task recursive runtime dependencies.
1495 See the :term:`RDEPENDS` variable, the
1496 :term:`RRECOMMENDS` variable, and the
1497 ":ref:`bitbake-user-manual/bitbake-user-manual-metadata:recursive dependencies`" section for
1498 more information.
1499
1500- ``[stamp-extra-info]``: Extra stamp information to append to the
1501 task's stamp. As an example, OpenEmbedded uses this flag to allow
1502 machine-specific tasks.
1503
1504- ``[umask]``: The umask to run the task under.
1505
1506Several varflags are useful for controlling how signatures are
1507calculated for variables. For more information on this process, see the
1508":ref:`bitbake-user-manual/bitbake-user-manual-execution:checksums (signatures)`" section.
1509
1510- ``[vardeps]``: Specifies a space-separated list of additional
1511 variables to add to a variable's dependencies for the purposes of
1512 calculating its signature. Adding variables to this list is useful,
1513 for example, when a function refers to a variable in a manner that
1514 does not allow BitBake to automatically determine that the variable
1515 is referred to.
1516
1517- ``[vardepsexclude]``: Specifies a space-separated list of variables
1518 that should be excluded from a variable's dependencies for the
1519 purposes of calculating its signature.
1520
1521- ``[vardepvalue]``: If set, instructs BitBake to ignore the actual
1522 value of the variable and instead use the specified value when
1523 calculating the variable's signature.
1524
1525- ``[vardepvalueexclude]``: Specifies a pipe-separated list of
1526 strings to exclude from the variable's value when calculating the
1527 variable's signature.
1528
1529Events
1530======
1531
1532BitBake allows installation of event handlers within recipe and class
1533files. Events are triggered at certain points during operation, such as
1534the beginning of operation against a given recipe (i.e. ``*.bb``), the
1535start of a given task, a task failure, a task success, and so forth. The
1536intent is to make it easy to do things like email notification on build
1537failures.
1538
1539Following is an example event handler that prints the name of the event
1540and the content of the ``FILE`` variable: ::
1541
1542 addhandler myclass_eventhandler
1543 python myclass_eventhandler() {
1544 from bb.event import getName
1545 print("The name of the Event is %s" % getName(e))
1546 print("The file we run for is %s" % d.getVar('FILE'))
1547 }
1548 myclass_eventhandler[eventmask] = "bb.event.BuildStarted
1549 bb.event.BuildCompleted"
1550
1551In the previous example, an eventmask has been
1552set so that the handler only sees the "BuildStarted" and
1553"BuildCompleted" events. This event handler gets called every time an
1554event matching the eventmask is triggered. A global variable "e" is
1555defined, which represents the current event. With the ``getName(e)``
1556method, you can get the name of the triggered event. The global
1557datastore is available as "d". In legacy code, you might see "e.data"
1558used to get the datastore. However, realize that "e.data" is deprecated
1559and you should use "d" going forward.
1560
1561The context of the datastore is appropriate to the event in question.
1562For example, "BuildStarted" and "BuildCompleted" events run before any
1563tasks are executed so would be in the global configuration datastore
1564namespace. No recipe-specific metadata exists in that namespace. The
1565"BuildStarted" and "BuildCompleted" events also run in the main
1566cooker/server process rather than any worker context. Thus, any changes
1567made to the datastore would be seen by other cooker/server events within
1568the current build but not seen outside of that build or in any worker
1569context. Task events run in the actual tasks in question consequently
1570have recipe-specific and task-specific contents. These events run in the
1571worker context and are discarded at the end of task execution.
1572
1573During a standard build, the following common events might occur. The
1574following events are the most common kinds of events that most metadata
1575might have an interest in viewing:
1576
1577- ``bb.event.ConfigParsed()``: Fired when the base configuration; which
1578 consists of ``bitbake.conf``, ``base.bbclass`` and any global
1579 ``INHERIT`` statements; has been parsed. You can see multiple such
1580 events when each of the workers parse the base configuration or if
1581 the server changes configuration and reparses. Any given datastore
1582 only has one such event executed against it, however. If
Andrew Geissler95ac1b82021-03-31 14:34:31 -05001583 :term:`BB_INVALIDCONF` is set in the datastore by the event
Andrew Geisslerc9f78652020-09-18 14:11:35 -05001584 handler, the configuration is reparsed and a new event triggered,
1585 allowing the metadata to update configuration.
1586
1587- ``bb.event.HeartbeatEvent()``: Fires at regular time intervals of one
1588 second. You can configure the interval time using the
1589 ``BB_HEARTBEAT_EVENT`` variable. The event's "time" attribute is the
1590 ``time.time()`` value when the event is triggered. This event is
1591 useful for activities such as system state monitoring.
1592
1593- ``bb.event.ParseStarted()``: Fired when BitBake is about to start
1594 parsing recipes. This event's "total" attribute represents the number
1595 of recipes BitBake plans to parse.
1596
1597- ``bb.event.ParseProgress()``: Fired as parsing progresses. This
1598 event's "current" attribute is the number of recipes parsed as well
1599 as the "total" attribute.
1600
1601- ``bb.event.ParseCompleted()``: Fired when parsing is complete. This
1602 event's "cached", "parsed", "skipped", "virtuals", "masked", and
1603 "errors" attributes provide statistics for the parsing results.
1604
1605- ``bb.event.BuildStarted()``: Fired when a new build starts. BitBake
1606 fires multiple "BuildStarted" events (one per configuration) when
1607 multiple configuration (multiconfig) is enabled.
1608
1609- ``bb.build.TaskStarted()``: Fired when a task starts. This event's
1610 "taskfile" attribute points to the recipe from which the task
1611 originates. The "taskname" attribute, which is the task's name,
1612 includes the ``do_`` prefix, and the "logfile" attribute point to
1613 where the task's output is stored. Finally, the "time" attribute is
1614 the task's execution start time.
1615
1616- ``bb.build.TaskInvalid()``: Fired if BitBake tries to execute a task
1617 that does not exist.
1618
1619- ``bb.build.TaskFailedSilent()``: Fired for setscene tasks that fail
1620 and should not be presented to the user verbosely.
1621
1622- ``bb.build.TaskFailed()``: Fired for normal tasks that fail.
1623
1624- ``bb.build.TaskSucceeded()``: Fired when a task successfully
1625 completes.
1626
1627- ``bb.event.BuildCompleted()``: Fired when a build finishes.
1628
1629- ``bb.cooker.CookerExit()``: Fired when the BitBake server/cooker
1630 shuts down. This event is usually only seen by the UIs as a sign they
1631 should also shutdown.
1632
1633This next list of example events occur based on specific requests to the
1634server. These events are often used to communicate larger pieces of
1635information from the BitBake server to other parts of BitBake such as
1636user interfaces:
1637
1638- ``bb.event.TreeDataPreparationStarted()``
1639- ``bb.event.TreeDataPreparationProgress()``
1640- ``bb.event.TreeDataPreparationCompleted()``
1641- ``bb.event.DepTreeGenerated()``
1642- ``bb.event.CoreBaseFilesFound()``
1643- ``bb.event.ConfigFilePathFound()``
1644- ``bb.event.FilesMatchingFound()``
1645- ``bb.event.ConfigFilesFound()``
1646- ``bb.event.TargetsTreeGenerated()``
1647
1648.. _variants-class-extension-mechanism:
1649
1650Variants - Class Extension Mechanism
1651====================================
1652
1653BitBake supports two features that facilitate creating from a single
1654recipe file multiple incarnations of that recipe file where all
1655incarnations are buildable. These features are enabled through the
1656:term:`BBCLASSEXTEND` and :term:`BBVERSIONS` variables.
1657
1658.. note::
1659
1660 The mechanism for this class extension is extremely specific to the
1661 implementation. Usually, the recipe's :term:`PROVIDES` , :term:`PN` , and
1662 :term:`DEPENDS` variables would need to be modified by the extension
1663 class. For specific examples, see the OE-Core native , nativesdk , and
1664 multilib classes.
1665
1666- ``BBCLASSEXTEND``: This variable is a space separated list of
1667 classes used to "extend" the recipe for each variant. Here is an
1668 example that results in a second incarnation of the current recipe
1669 being available. This second incarnation will have the "native" class
1670 inherited. ::
1671
1672 BBCLASSEXTEND = "native"
1673
1674- ``BBVERSIONS``: This variable allows a single recipe to build
1675 multiple versions of a project from a single recipe file. You can
1676 also specify conditional metadata (using the
1677 :term:`OVERRIDES` mechanism) for a single
1678 version, or an optionally named range of versions. Here is an
1679 example: ::
1680
1681 BBVERSIONS = "1.0 2.0 git"
1682 SRC_URI_git = "git://someurl/somepath.git"
1683
1684 BBVERSIONS = "1.0.[0-6]:1.0.0+ 1.0.[7-9]:1.0.7+"
1685 SRC_URI_append_1.0.7+ = "file://some_patch_which_the_new_versions_need.patch;patch=1"
1686
1687 The name of the range defaults to the original version of the recipe. For
1688 example, in OpenEmbedded, the recipe file ``foo_1.0.0+.bb`` creates a default
1689 name range of ``1.0.0+``. This is useful because the range name is not only
1690 placed into overrides, but it is also made available for the metadata to use
1691 in the variable that defines the base recipe versions for use in ``file://``
1692 search paths (:term:`FILESPATH`).
1693
1694Dependencies
1695============
1696
1697To allow for efficient parallel processing, BitBake handles dependencies
1698at the task level. Dependencies can exist both between tasks within a
1699single recipe and between tasks in different recipes. Following are
1700examples of each:
1701
1702- For tasks within a single recipe, a recipe's ``do_configure`` task
1703 might need to complete before its ``do_compile`` task can run.
1704
1705- For tasks in different recipes, one recipe's ``do_configure`` task
1706 might require another recipe's ``do_populate_sysroot`` task to finish
1707 first such that the libraries and headers provided by the other
1708 recipe are available.
1709
1710This section describes several ways to declare dependencies. Remember,
1711even though dependencies are declared in different ways, they are all
1712simply dependencies between tasks.
1713
1714.. _dependencies-internal-to-the-bb-file:
1715
1716Dependencies Internal to the ``.bb`` File
1717-----------------------------------------
1718
1719BitBake uses the ``addtask`` directive to manage dependencies that are
1720internal to a given recipe file. You can use the ``addtask`` directive
1721to indicate when a task is dependent on other tasks or when other tasks
1722depend on that recipe. Here is an example: ::
1723
1724 addtask printdate after do_fetch before do_build
1725
1726In this example, the ``do_printdate`` task
1727depends on the completion of the ``do_fetch`` task, and the ``do_build``
1728task depends on the completion of the ``do_printdate`` task.
1729
1730.. note::
1731
1732 For a task to run, it must be a direct or indirect dependency of some
1733 other task that is scheduled to run.
1734
1735 For illustration, here are some examples:
1736
1737 - The directive ``addtask mytask before do_configure`` causes
1738 ``do_mytask`` to run before ``do_configure`` runs. Be aware that
1739 ``do_mytask`` still only runs if its :ref:`input
1740 checksum <bitbake-user-manual/bitbake-user-manual-execution:checksums (signatures)>` has changed since the last time it was
1741 run. Changes to the input checksum of ``do_mytask`` also
1742 indirectly cause ``do_configure`` to run.
1743
1744 - The directive ``addtask mytask after do_configure`` by itself
1745 never causes ``do_mytask`` to run. ``do_mytask`` can still be run
1746 manually as follows: ::
1747
1748 $ bitbake recipe -c mytask
1749
1750 Declaring ``do_mytask`` as a dependency of some other task that is
1751 scheduled to run also causes it to run. Regardless, the task runs after
1752 ``do_configure``.
1753
1754Build Dependencies
1755------------------
1756
1757BitBake uses the :term:`DEPENDS` variable to manage
1758build time dependencies. The ``[deptask]`` varflag for tasks signifies
1759the task of each item listed in ``DEPENDS`` that must complete before
1760that task can be executed. Here is an example: ::
1761
1762 do_configure[deptask] = "do_populate_sysroot"
1763
1764In this example, the ``do_populate_sysroot`` task
1765of each item in ``DEPENDS`` must complete before ``do_configure`` can
1766execute.
1767
1768Runtime Dependencies
1769--------------------
1770
1771BitBake uses the :term:`PACKAGES`, :term:`RDEPENDS`, and :term:`RRECOMMENDS`
1772variables to manage runtime dependencies.
1773
1774The ``PACKAGES`` variable lists runtime packages. Each of those packages
1775can have ``RDEPENDS`` and ``RRECOMMENDS`` runtime dependencies. The
1776``[rdeptask]`` flag for tasks is used to signify the task of each item
1777runtime dependency which must have completed before that task can be
1778executed. ::
1779
1780 do_package_qa[rdeptask] = "do_packagedata"
1781
1782In the previous
1783example, the ``do_packagedata`` task of each item in ``RDEPENDS`` must
1784have completed before ``do_package_qa`` can execute.
1785Although ``RDEPENDS`` contains entries from the
1786runtime dependency namespace, BitBake knows how to map them back
1787to the build-time dependency namespace, in which the tasks are defined.
1788
1789Recursive Dependencies
1790----------------------
1791
1792BitBake uses the ``[recrdeptask]`` flag to manage recursive task
1793dependencies. BitBake looks through the build-time and runtime
1794dependencies of the current recipe, looks through the task's inter-task
1795dependencies, and then adds dependencies for the listed task. Once
1796BitBake has accomplished this, it recursively works through the
1797dependencies of those tasks. Iterative passes continue until all
1798dependencies are discovered and added.
1799
1800The ``[recrdeptask]`` flag is most commonly used in high-level recipes
1801that need to wait for some task to finish "globally". For example,
1802``image.bbclass`` has the following: ::
1803
1804 do_rootfs[recrdeptask] += "do_packagedata"
1805
1806This statement says that the ``do_packagedata`` task of
1807the current recipe and all recipes reachable (by way of dependencies)
1808from the image recipe must run before the ``do_rootfs`` task can run.
1809
1810BitBake allows a task to recursively depend on itself by
1811referencing itself in the task list: ::
1812
1813 do_a[recrdeptask] = "do_a do_b"
1814
1815In the same way as before, this means that the ``do_a``
1816and ``do_b`` tasks of the current recipe and all
1817recipes reachable (by way of dependencies) from the recipe
1818must run before the ``do_a`` task can run. In this
1819case BitBake will ignore the current recipe's ``do_a``
1820task circular dependency on itself.
1821
1822Inter-Task Dependencies
1823-----------------------
1824
1825BitBake uses the ``[depends]`` flag in a more generic form to manage
1826inter-task dependencies. This more generic form allows for
1827inter-dependency checks for specific tasks rather than checks for the
1828data in ``DEPENDS``. Here is an example: ::
1829
1830 do_patch[depends] = "quilt-native:do_populate_sysroot"
1831
1832In this example, the ``do_populate_sysroot`` task of the target ``quilt-native``
1833must have completed before the ``do_patch`` task can execute.
1834
1835The ``[rdepends]`` flag works in a similar way but takes targets in the
1836runtime namespace instead of the build-time dependency namespace.
1837
1838Functions You Can Call From Within Python
1839=========================================
1840
1841BitBake provides many functions you can call from within Python
1842functions. This section lists the most commonly used functions, and
1843mentions where to find others.
1844
1845Functions for Accessing Datastore Variables
1846-------------------------------------------
1847
1848It is often necessary to access variables in the BitBake datastore using
1849Python functions. The BitBake datastore has an API that allows you this
1850access. Here is a list of available operations:
1851
1852.. list-table::
1853 :widths: auto
1854 :header-rows: 1
1855
1856 * - *Operation*
1857 - *Description*
1858 * - ``d.getVar("X", expand)``
1859 - Returns the value of variable "X". Using "expand=True" expands the
1860 value. Returns "None" if the variable "X" does not exist.
1861 * - ``d.setVar("X", "value")``
1862 - Sets the variable "X" to "value"
1863 * - ``d.appendVar("X", "value")``
1864 - Adds "value" to the end of the variable "X". Acts like ``d.setVar("X",
1865 "value")`` if the variable "X" does not exist.
1866 * - ``d.prependVar("X", "value")``
1867 - Adds "value" to the start of the variable "X". Acts like
1868 ``d.setVar("X","value")`` if the variable "X" does not exist.
1869 * - ``d.delVar("X")``
1870 - Deletes the variable "X" from the datastore. Does nothing if the variable
1871 "X" does not exist.
1872 * - ``d.renameVar("X", "Y")``
1873 - Renames the variable "X" to "Y". Does nothing if the variable "X" does
1874 not exist.
1875 * - ``d.getVarFlag("X", flag, expand)``
1876 - Returns the value of variable "X". Using "expand=True" expands the
1877 value. Returns "None" if either the variable "X" or the named flag does
1878 not exist.
1879 * - ``d.setVarFlag("X", flag, "value")``
1880 - Sets the named flag for variable "X" to "value".
1881 * - ``d.appendVarFlag("X", flag, "value")``
1882 - Appends "value" to the named flag on the variable "X". Acts like
1883 ``d.setVarFlag("X", flag, "value")`` if the named flag does not exist.
1884 * - ``d.prependVarFlag("X", flag, "value")``
1885 - Prepends "value" to the named flag on the variable "X". Acts like
1886 ``d.setVarFlag("X", flag, "value")`` if the named flag does not exist.
1887 * - ``d.delVarFlag("X", flag)``
1888 - Deletes the named flag on the variable "X" from the datastore.
1889 * - ``d.setVarFlags("X", flagsdict)``
1890 - Sets the flags specified in the ``flagsdict()``
1891 parameter. ``setVarFlags`` does not clear previous flags. Think of this
1892 operation as ``addVarFlags``.
1893 * - ``d.getVarFlags("X")``
1894 - Returns a ``flagsdict`` of the flags for the variable "X". Returns "None"
1895 if the variable "X" does not exist.
1896 * - ``d.delVarFlags("X")``
1897 - Deletes all the flags for the variable "X". Does nothing if the variable
1898 "X" does not exist.
1899 * - ``d.expand(expression)``
1900 - Expands variable references in the specified string
1901 expression. References to variables that do not exist are left as is. For
1902 example, ``d.expand("foo ${X}")`` expands to the literal string "foo
1903 ${X}" if the variable "X" does not exist.
1904
1905Other Functions
1906---------------
1907
1908You can find many other functions that can be called from Python by
1909looking at the source code of the ``bb`` module, which is in
1910``bitbake/lib/bb``. For example, ``bitbake/lib/bb/utils.py`` includes
1911the commonly used functions ``bb.utils.contains()`` and
1912``bb.utils.mkdirhier()``, which come with docstrings.
1913
1914Task Checksums and Setscene
1915===========================
1916
1917BitBake uses checksums (or signatures) along with the setscene to
1918determine if a task needs to be run. This section describes the process.
1919To help understand how BitBake does this, the section assumes an
1920OpenEmbedded metadata-based example.
1921
1922These checksums are stored in :term:`STAMP`. You can
1923examine the checksums using the following BitBake command: ::
1924
1925 $ bitbake-dumpsigs
1926
1927This command returns the signature data in a readable
1928format that allows you to examine the inputs used when the OpenEmbedded
1929build system generates signatures. For example, using
1930``bitbake-dumpsigs`` allows you to examine the ``do_compile`` task's
Andrew Geisslerf0343792020-11-18 10:42:21 -06001931"sigdata" for a C application (e.g. ``bash``). Running the command also
1932reveals that the "CC" variable is part of the inputs that are hashed.
Andrew Geisslerc9f78652020-09-18 14:11:35 -05001933Any changes to this variable would invalidate the stamp and cause the
1934``do_compile`` task to run.
1935
1936The following list describes related variables:
1937
1938- :term:`BB_HASHCHECK_FUNCTION`:
1939 Specifies the name of the function to call during the "setscene" part
1940 of the task's execution in order to validate the list of task hashes.
1941
1942- :term:`BB_SETSCENE_DEPVALID`:
1943 Specifies a function BitBake calls that determines whether BitBake
1944 requires a setscene dependency to be met.
1945
1946- :term:`BB_SETSCENE_VERIFY_FUNCTION2`:
1947 Specifies a function to call that verifies the list of planned task
1948 execution before the main task execution happens.
1949
1950- :term:`BB_STAMP_POLICY`: Defines the mode
1951 for comparing timestamps of stamp files.
1952
1953- :term:`BB_STAMP_WHITELIST`: Lists stamp
1954 files that are looked at when the stamp policy is "whitelist".
1955
1956- :term:`BB_TASKHASH`: Within an executing task,
1957 this variable holds the hash of the task as returned by the currently
1958 enabled signature generator.
1959
1960- :term:`STAMP`: The base path to create stamp files.
1961
1962- :term:`STAMPCLEAN`: Again, the base path to
1963 create stamp files but can use wildcards for matching a range of
1964 files for clean operations.
1965
1966Wildcard Support in Variables
1967=============================
1968
1969Support for wildcard use in variables varies depending on the context in
1970which it is used. For example, some variables and file names allow
1971limited use of wildcards through the "``%``" and "``*``" characters.
1972Other variables or names support Python's
1973`glob <https://docs.python.org/3/library/glob.html>`_ syntax,
1974`fnmatch <https://docs.python.org/3/library/fnmatch.html#module-fnmatch>`_
1975syntax, or
1976`Regular Expression (re) <https://docs.python.org/3/library/re.html>`_
1977syntax.
1978
1979For variables that have wildcard suport, the documentation describes
1980which form of wildcard, its use, and its limitations.