summaryrefslogtreecommitdiffstats
path: root/bitbake/lib/bb/utils.py
diff options
context:
space:
mode:
Diffstat (limited to 'bitbake/lib/bb/utils.py')
-rw-r--r--bitbake/lib/bb/utils.py673
1 files changed, 518 insertions, 155 deletions
diff --git a/bitbake/lib/bb/utils.py b/bitbake/lib/bb/utils.py
index ebee65d3dd..1cc74ed546 100644
--- a/bitbake/lib/bb/utils.py
+++ b/bitbake/lib/bb/utils.py
@@ -11,11 +11,8 @@ import re, fcntl, os, string, stat, shutil, time
11import sys 11import sys
12import errno 12import errno
13import logging 13import logging
14import bb
15import bb.msg
16import locale 14import locale
17import multiprocessing 15import multiprocessing
18import fcntl
19import importlib 16import importlib
20import importlib.machinery 17import importlib.machinery
21import importlib.util 18import importlib.util
@@ -24,7 +21,6 @@ import subprocess
24import glob 21import glob
25import fnmatch 22import fnmatch
26import traceback 23import traceback
27import errno
28import signal 24import signal
29import collections 25import collections
30import copy 26import copy
@@ -36,6 +32,8 @@ import tempfile
36from subprocess import getstatusoutput 32from subprocess import getstatusoutput
37from contextlib import contextmanager 33from contextlib import contextmanager
38from ctypes import cdll 34from ctypes import cdll
35import bb
36import bb.msg
39 37
40logger = logging.getLogger("BitBake.Util") 38logger = logging.getLogger("BitBake.Util")
41python_extensions = importlib.machinery.all_suffixes() 39python_extensions = importlib.machinery.all_suffixes()
@@ -84,7 +82,16 @@ def explode_version(s):
84 return r 82 return r
85 83
86def split_version(s): 84def split_version(s):
87 """Split a version string into its constituent parts (PE, PV, PR)""" 85 """Split a version string into its constituent parts (PE, PV, PR).
86
87 Arguments:
88
89 - ``s``: version string. The format of the input string should be::
90
91 ${PE}:${PV}-${PR}
92
93 Returns a tuple ``(pe, pv, pr)``.
94 """
88 s = s.strip(" <>=") 95 s = s.strip(" <>=")
89 e = 0 96 e = 0
90 if s.count(':'): 97 if s.count(':'):
@@ -136,16 +143,30 @@ def vercmp(ta, tb):
136 return r 143 return r
137 144
138def vercmp_string(a, b): 145def vercmp_string(a, b):
139 """ Split version strings and compare them """ 146 """ Split version strings using ``bb.utils.split_version()`` and compare
147 them with ``bb.utils.vercmp().``
148
149 Arguments:
150
151 - ``a``: left version string operand.
152 - ``b``: right version string operand.
153
154 Returns what ``bb.utils.vercmp()`` returns."""
140 ta = split_version(a) 155 ta = split_version(a)
141 tb = split_version(b) 156 tb = split_version(b)
142 return vercmp(ta, tb) 157 return vercmp(ta, tb)
143 158
144def vercmp_string_op(a, b, op): 159def vercmp_string_op(a, b, op):
145 """ 160 """
146 Compare two versions and check if the specified comparison operator matches the result of the comparison. 161 Takes the return value ``bb.utils.vercmp()`` and returns the operation
147 This function is fairly liberal about what operators it will accept since there are a variety of styles 162 defined by ``op`` between the return value and 0.
148 depending on the context. 163
164 Arguments:
165
166 - ``a``: left version string operand.
167 - ``b``: right version string operand.
168 - ``op``: operator string. Can be one of ``=``, ``==``, ``<=``, ``>=``,
169 ``>``, ``>>``, ``<``, ``<<`` or ``!=``.
149 """ 170 """
150 res = vercmp_string(a, b) 171 res = vercmp_string(a, b)
151 if op in ('=', '=='): 172 if op in ('=', '=='):
@@ -165,9 +186,16 @@ def vercmp_string_op(a, b, op):
165 186
166def explode_deps(s): 187def explode_deps(s):
167 """ 188 """
168 Take an RDEPENDS style string of format: 189 Takes an RDEPENDS style string of format::
169 "DEPEND1 (optional version) DEPEND2 (optional version) ..." 190
170 and return a list of dependencies. 191 DEPEND1 (optional version) DEPEND2 (optional version) ...
192
193 Arguments:
194
195 - ``s``: input RDEPENDS style string
196
197 Returns a list of dependencies.
198
171 Version information is ignored. 199 Version information is ignored.
172 """ 200 """
173 r = [] 201 r = []
@@ -189,9 +217,17 @@ def explode_deps(s):
189 217
190def explode_dep_versions2(s, *, sort=True): 218def explode_dep_versions2(s, *, sort=True):
191 """ 219 """
192 Take an RDEPENDS style string of format: 220 Takes an RDEPENDS style string of format::
193 "DEPEND1 (optional version) DEPEND2 (optional version) ..." 221
194 and return a dictionary of dependencies and versions. 222 DEPEND1 (optional version) DEPEND2 (optional version) ...
223
224 Arguments:
225
226 - ``s``: input RDEPENDS style string
227 - ``*``: *Unused*.
228 - ``sort``: whether to sort the output or not.
229
230 Returns a dictionary of dependencies and versions.
195 """ 231 """
196 r = collections.OrderedDict() 232 r = collections.OrderedDict()
197 l = s.replace(",", "").split() 233 l = s.replace(",", "").split()
@@ -256,10 +292,17 @@ def explode_dep_versions2(s, *, sort=True):
256 292
257def explode_dep_versions(s): 293def explode_dep_versions(s):
258 """ 294 """
259 Take an RDEPENDS style string of format: 295 Take an RDEPENDS style string of format::
260 "DEPEND1 (optional version) DEPEND2 (optional version) ..." 296
261 skip null value and items appeared in dependency string multiple times 297 DEPEND1 (optional version) DEPEND2 (optional version) ...
262 and return a dictionary of dependencies and versions. 298
299 Skips null values and items appeared in dependency string multiple times.
300
301 Arguments:
302
303 - ``s``: input RDEPENDS style string
304
305 Returns a dictionary of dependencies and versions.
263 """ 306 """
264 r = explode_dep_versions2(s) 307 r = explode_dep_versions2(s)
265 for d in r: 308 for d in r:
@@ -273,7 +316,17 @@ def explode_dep_versions(s):
273 316
274def join_deps(deps, commasep=True): 317def join_deps(deps, commasep=True):
275 """ 318 """
276 Take the result from explode_dep_versions and generate a dependency string 319 Take a result from ``bb.utils.explode_dep_versions()`` and generate a
320 dependency string.
321
322 Arguments:
323
324 - ``deps``: dictionary of dependencies and versions.
325 - ``commasep``: makes the return value separated by commas if ``True``,
326 separated by spaces otherwise.
327
328 Returns a comma-separated (space-separated if ``comma-sep`` is ``False``)
329 string of dependencies and versions.
277 """ 330 """
278 result = [] 331 result = []
279 for dep in deps: 332 for dep in deps:
@@ -435,7 +488,11 @@ def better_eval(source, locals, extraglobals = None):
435 488
436@contextmanager 489@contextmanager
437def fileslocked(files, *args, **kwargs): 490def fileslocked(files, *args, **kwargs):
438 """Context manager for locking and unlocking file locks.""" 491 """Context manager for locking and unlocking file locks. Uses
492 ``bb.utils.lockfile()`` and ``bb.utils.unlockfile()`` to lock and unlock
493 files.
494
495 No return value."""
439 locks = [] 496 locks = []
440 if files: 497 if files:
441 for lockfile in files: 498 for lockfile in files:
@@ -446,19 +503,29 @@ def fileslocked(files, *args, **kwargs):
446 try: 503 try:
447 yield 504 yield
448 finally: 505 finally:
506 locks.reverse()
449 for lock in locks: 507 for lock in locks:
450 bb.utils.unlockfile(lock) 508 bb.utils.unlockfile(lock)
451 509
452def lockfile(name, shared=False, retry=True, block=False): 510def lockfile(name, shared=False, retry=True, block=False):
453 """ 511 """
454 Use the specified file as a lock file, return when the lock has 512 Use the specified file (with filename ``name``) as a lock file, return when
455 been acquired. Returns a variable to pass to unlockfile(). 513 the lock has been acquired. Returns a variable to pass to unlockfile().
456 Parameters: 514
457 retry: True to re-try locking if it fails, False otherwise 515 Arguments:
458 block: True to block until the lock succeeds, False otherwise 516
517 - ``shared``: sets the lock as a shared lock instead of an
518 exclusive lock.
519 - ``retry``: ``True`` to re-try locking if it fails, ``False``
520 otherwise.
521 - ``block``: ``True`` to block until the lock succeeds,
522 ``False`` otherwise.
523
459 The retry and block parameters are kind of equivalent unless you 524 The retry and block parameters are kind of equivalent unless you
460 consider the possibility of sending a signal to the process to break 525 consider the possibility of sending a signal to the process to break
461 out - at which point you want block=True rather than retry=True. 526 out - at which point you want block=True rather than retry=True.
527
528 Returns the locked file descriptor in case of success, ``None`` otherwise.
462 """ 529 """
463 basename = os.path.basename(name) 530 basename = os.path.basename(name)
464 if len(basename) > 255: 531 if len(basename) > 255:
@@ -517,7 +584,13 @@ def lockfile(name, shared=False, retry=True, block=False):
517 584
518def unlockfile(lf): 585def unlockfile(lf):
519 """ 586 """
520 Unlock a file locked using lockfile() 587 Unlock a file locked using ``bb.utils.lockfile()``.
588
589 Arguments:
590
591 - ``lf``: the locked file descriptor.
592
593 No return value.
521 """ 594 """
522 try: 595 try:
523 # If we had a shared lock, we need to promote to exclusive before 596 # If we had a shared lock, we need to promote to exclusive before
@@ -545,7 +618,11 @@ def _hasher(method, filename):
545 618
546def md5_file(filename): 619def md5_file(filename):
547 """ 620 """
548 Return the hex string representation of the MD5 checksum of filename. 621 Arguments:
622
623 - ``filename``: path to the input file.
624
625 Returns the hexadecimal string representation of the MD5 checksum of filename.
549 """ 626 """
550 import hashlib 627 import hashlib
551 try: 628 try:
@@ -557,36 +634,81 @@ def md5_file(filename):
557 634
558def sha256_file(filename): 635def sha256_file(filename):
559 """ 636 """
560 Return the hex string representation of the 256-bit SHA checksum of 637 Returns the hexadecimal representation of the 256-bit SHA checksum of
561 filename. 638 filename.
639
640 Arguments:
641
642 - ``filename``: path to the file.
562 """ 643 """
563 import hashlib 644 import hashlib
564 return _hasher(hashlib.sha256(), filename) 645 return _hasher(hashlib.sha256(), filename)
565 646
566def sha1_file(filename): 647def sha1_file(filename):
567 """ 648 """
568 Return the hex string representation of the SHA1 checksum of the filename 649 Returns the hexadecimal representation of the SHA1 checksum of the filename
650
651 Arguments:
652
653 - ``filename``: path to the file.
569 """ 654 """
570 import hashlib 655 import hashlib
571 return _hasher(hashlib.sha1(), filename) 656 return _hasher(hashlib.sha1(), filename)
572 657
573def sha384_file(filename): 658def sha384_file(filename):
574 """ 659 """
575 Return the hex string representation of the SHA384 checksum of the filename 660 Returns the hexadecimal representation of the SHA384 checksum of the filename
661
662 Arguments:
663
664 - ``filename``: path to the file.
576 """ 665 """
577 import hashlib 666 import hashlib
578 return _hasher(hashlib.sha384(), filename) 667 return _hasher(hashlib.sha384(), filename)
579 668
580def sha512_file(filename): 669def sha512_file(filename):
581 """ 670 """
582 Return the hex string representation of the SHA512 checksum of the filename 671 Returns the hexadecimal representation of the SHA512 checksum of the filename
672
673 Arguments:
674
675 - ``filename``: path to the file.
583 """ 676 """
584 import hashlib 677 import hashlib
585 return _hasher(hashlib.sha512(), filename) 678 return _hasher(hashlib.sha512(), filename)
586 679
680def goh1_file(filename):
681 """
682 Returns the hexadecimal string representation of the Go mod h1 checksum of the
683 filename. The Go mod h1 checksum uses the Go dirhash package. The package
684 defines hashes over directory trees and is used by go mod for mod files and
685 zip archives.
686
687 Arguments:
688
689 - ``filename``: path to the file.
690 """
691 import hashlib
692 import zipfile
693
694 lines = []
695 if zipfile.is_zipfile(filename):
696 with zipfile.ZipFile(filename) as archive:
697 for fn in sorted(archive.namelist()):
698 method = hashlib.sha256()
699 method.update(archive.read(fn))
700 hash = method.hexdigest()
701 lines.append("%s %s\n" % (hash, fn))
702 else:
703 hash = _hasher(hashlib.sha256(), filename)
704 lines.append("%s go.mod\n" % hash)
705 method = hashlib.sha256()
706 method.update("".join(lines).encode('utf-8'))
707 return method.hexdigest()
708
587def preserved_envvars_exported(): 709def preserved_envvars_exported():
588 """Variables which are taken from the environment and placed in and exported 710 """Returns the list of variables which are taken from the environment and
589 from the metadata""" 711 placed in and exported from the metadata."""
590 return [ 712 return [
591 'BB_TASKHASH', 713 'BB_TASKHASH',
592 'HOME', 714 'HOME',
@@ -600,7 +722,8 @@ def preserved_envvars_exported():
600 ] 722 ]
601 723
602def preserved_envvars(): 724def preserved_envvars():
603 """Variables which are taken from the environment and placed in the metadata""" 725 """Returns the list of variables which are taken from the environment and
726 placed in the metadata."""
604 v = [ 727 v = [
605 'BBPATH', 728 'BBPATH',
606 'BB_PRESERVE_ENV', 729 'BB_PRESERVE_ENV',
@@ -609,7 +732,9 @@ def preserved_envvars():
609 return v + preserved_envvars_exported() 732 return v + preserved_envvars_exported()
610 733
611def check_system_locale(): 734def check_system_locale():
612 """Make sure the required system locale are available and configured""" 735 """Make sure the required system locale are available and configured.
736
737 No return value."""
613 default_locale = locale.getlocale(locale.LC_CTYPE) 738 default_locale = locale.getlocale(locale.LC_CTYPE)
614 739
615 try: 740 try:
@@ -627,6 +752,12 @@ def filter_environment(good_vars):
627 """ 752 """
628 Create a pristine environment for bitbake. This will remove variables that 753 Create a pristine environment for bitbake. This will remove variables that
629 are not known and may influence the build in a negative way. 754 are not known and may influence the build in a negative way.
755
756 Arguments:
757
758 - ``good_vars``: list of variable to exclude from the filtering.
759
760 No return value.
630 """ 761 """
631 762
632 removed_vars = {} 763 removed_vars = {}
@@ -671,6 +802,8 @@ def clean_environment():
671 """ 802 """
672 Clean up any spurious environment variables. This will remove any 803 Clean up any spurious environment variables. This will remove any
673 variables the user hasn't chosen to preserve. 804 variables the user hasn't chosen to preserve.
805
806 No return value.
674 """ 807 """
675 if 'BB_PRESERVE_ENV' not in os.environ: 808 if 'BB_PRESERVE_ENV' not in os.environ:
676 good_vars = approved_variables() 809 good_vars = approved_variables()
@@ -681,6 +814,8 @@ def clean_environment():
681def empty_environment(): 814def empty_environment():
682 """ 815 """
683 Remove all variables from the environment. 816 Remove all variables from the environment.
817
818 No return value.
684 """ 819 """
685 for s in list(os.environ.keys()): 820 for s in list(os.environ.keys()):
686 os.unsetenv(s) 821 os.unsetenv(s)
@@ -689,6 +824,12 @@ def empty_environment():
689def build_environment(d): 824def build_environment(d):
690 """ 825 """
691 Build an environment from all exported variables. 826 Build an environment from all exported variables.
827
828 Arguments:
829
830 - ``d``: the data store.
831
832 No return value.
692 """ 833 """
693 import bb.data 834 import bb.data
694 for var in bb.data.keys(d): 835 for var in bb.data.keys(d):
@@ -713,7 +854,17 @@ def _check_unsafe_delete_path(path):
713 return False 854 return False
714 855
715def remove(path, recurse=False, ionice=False): 856def remove(path, recurse=False, ionice=False):
716 """Equivalent to rm -f or rm -rf""" 857 """Equivalent to rm -f or rm -rf.
858
859 Arguments:
860
861 - ``path``: path to file/directory to remove.
862 - ``recurse``: deletes recursively if ``True``.
863 - ``ionice``: prepends ``ionice -c 3`` to the ``rm`` command. See ``man
864 ionice``.
865
866 No return value.
867 """
717 if not path: 868 if not path:
718 return 869 return
719 if recurse: 870 if recurse:
@@ -734,7 +885,17 @@ def remove(path, recurse=False, ionice=False):
734 raise 885 raise
735 886
736def prunedir(topdir, ionice=False): 887def prunedir(topdir, ionice=False):
737 """ Delete everything reachable from the directory named in 'topdir'. """ 888 """
889 Delete everything reachable from the directory named in ``topdir``.
890
891 Arguments:
892
893 - ``topdir``: directory path.
894 - ``ionice``: prepends ``ionice -c 3`` to the ``rm`` command. See ``man
895 ionice``.
896
897 No return value.
898 """
738 # CAUTION: This is dangerous! 899 # CAUTION: This is dangerous!
739 if _check_unsafe_delete_path(topdir): 900 if _check_unsafe_delete_path(topdir):
740 raise Exception('bb.utils.prunedir: called with dangerous path "%s", refusing to delete!' % topdir) 901 raise Exception('bb.utils.prunedir: called with dangerous path "%s", refusing to delete!' % topdir)
@@ -746,8 +907,15 @@ def prunedir(topdir, ionice=False):
746# 907#
747def prune_suffix(var, suffixes, d): 908def prune_suffix(var, suffixes, d):
748 """ 909 """
749 See if var ends with any of the suffixes listed and 910 Check if ``var`` ends with any of the suffixes listed in ``suffixes`` and
750 remove it if found 911 remove it if found.
912
913 Arguments:
914
915 - ``var``: string to check for suffixes.
916 - ``suffixes``: list of strings representing suffixes to check for.
917
918 Returns the string ``var`` without the suffix.
751 """ 919 """
752 for suffix in suffixes: 920 for suffix in suffixes:
753 if suffix and var.endswith(suffix): 921 if suffix and var.endswith(suffix):
@@ -756,7 +924,13 @@ def prune_suffix(var, suffixes, d):
756 924
757def mkdirhier(directory): 925def mkdirhier(directory):
758 """Create a directory like 'mkdir -p', but does not complain if 926 """Create a directory like 'mkdir -p', but does not complain if
759 directory already exists like os.makedirs 927 directory already exists like ``os.makedirs()``.
928
929 Arguments:
930
931 - ``directory``: path to the directory.
932
933 No return value.
760 """ 934 """
761 if '${' in str(directory): 935 if '${' in str(directory):
762 bb.fatal("Directory name {} contains unexpanded bitbake variable. This may cause build failures and WORKDIR polution.".format(directory)) 936 bb.fatal("Directory name {} contains unexpanded bitbake variable. This may cause build failures and WORKDIR polution.".format(directory))
@@ -767,10 +941,24 @@ def mkdirhier(directory):
767 raise e 941 raise e
768 942
769def movefile(src, dest, newmtime = None, sstat = None): 943def movefile(src, dest, newmtime = None, sstat = None):
770 """Moves a file from src to dest, preserving all permissions and 944 """Moves a file from ``src`` to ``dest``, preserving all permissions and
771 attributes; mtime will be preserved even when moving across 945 attributes; mtime will be preserved even when moving across
772 filesystems. Returns true on success and false on failure. Move is 946 filesystems. Returns ``True`` on success and ``False`` on failure. Move is
773 atomic. 947 atomic.
948
949 Arguments:
950
951 - ``src`` -- Source file.
952 - ``dest`` -- Destination file.
953 - ``newmtime`` -- new mtime to be passed as float seconds since the epoch.
954 - ``sstat`` -- os.stat_result to use for the destination file.
955
956 Returns an ``os.stat_result`` of the destination file if the
957 source file is a symbolic link or the ``sstat`` argument represents a
958 symbolic link - in which case the destination file will also be created as
959 a symbolic link.
960
961 Otherwise, returns ``newmtime`` on success and ``False`` on failure.
774 """ 962 """
775 963
776 #print "movefile(" + src + "," + dest + "," + str(newmtime) + "," + str(sstat) + ")" 964 #print "movefile(" + src + "," + dest + "," + str(newmtime) + "," + str(sstat) + ")"
@@ -861,9 +1049,24 @@ def movefile(src, dest, newmtime = None, sstat = None):
861 1049
862def copyfile(src, dest, newmtime = None, sstat = None): 1050def copyfile(src, dest, newmtime = None, sstat = None):
863 """ 1051 """
864 Copies a file from src to dest, preserving all permissions and 1052 Copies a file from ``src`` to ``dest``, preserving all permissions and
865 attributes; mtime will be preserved even when moving across 1053 attributes; mtime will be preserved even when moving across
866 filesystems. Returns true on success and false on failure. 1054 filesystems.
1055
1056 Arguments:
1057
1058 - ``src``: Source file.
1059 - ``dest``: Destination file.
1060 - ``newmtime``: new mtime to be passed as float seconds since the epoch.
1061 - ``sstat``: os.stat_result to use for the destination file.
1062
1063 Returns an ``os.stat_result`` of the destination file if the
1064 source file is a symbolic link or the ``sstat`` argument represents a
1065 symbolic link - in which case the destination file will also be created as
1066 a symbolic link.
1067
1068 Otherwise, returns ``newmtime`` on success and ``False`` on failure.
1069
867 """ 1070 """
868 #print "copyfile(" + src + "," + dest + "," + str(newmtime) + "," + str(sstat) + ")" 1071 #print "copyfile(" + src + "," + dest + "," + str(newmtime) + "," + str(sstat) + ")"
869 try: 1072 try:
@@ -941,10 +1144,16 @@ def copyfile(src, dest, newmtime = None, sstat = None):
941 1144
942def break_hardlinks(src, sstat = None): 1145def break_hardlinks(src, sstat = None):
943 """ 1146 """
944 Ensures src is the only hardlink to this file. Other hardlinks, 1147 Ensures ``src`` is the only hardlink to this file. Other hardlinks,
945 if any, are not affected (other than in their st_nlink value, of 1148 if any, are not affected (other than in their st_nlink value, of
946 course). Returns true on success and false on failure. 1149 course).
1150
1151 Arguments:
1152
1153 - ``src``: source file path.
1154 - ``sstat``: os.stat_result to use when checking if the file is a link.
947 1155
1156 Returns ``True`` on success and ``False`` on failure.
948 """ 1157 """
949 try: 1158 try:
950 if not sstat: 1159 if not sstat:
@@ -958,11 +1167,24 @@ def break_hardlinks(src, sstat = None):
958 1167
959def which(path, item, direction = 0, history = False, executable=False): 1168def which(path, item, direction = 0, history = False, executable=False):
960 """ 1169 """
961 Locate `item` in the list of paths `path` (colon separated string like $PATH). 1170 Locate ``item`` in the list of paths ``path`` (colon separated string like
962 If `direction` is non-zero then the list is reversed. 1171 ``$PATH``).
963 If `history` is True then the list of candidates also returned as result,history. 1172
964 If `executable` is True then the candidate has to be an executable file, 1173 Arguments:
965 otherwise the candidate simply has to exist. 1174
1175 - ``path``: list of colon-separated paths.
1176 - ``item``: string to search for.
1177 - ``direction``: if non-zero then the list is reversed.
1178 - ``history``: if ``True`` then the list of candidates also returned as
1179 ``result,history`` where ``history`` is the list of previous path
1180 checked.
1181 - ``executable``: if ``True`` then the candidate defined by ``path`` has
1182 to be an executable file, otherwise if ``False`` the candidate simply
1183 has to exist.
1184
1185 Returns the item if found in the list of path, otherwise an empty string.
1186 If ``history`` is ``True``, return the list of previous path checked in a
1187 tuple with the found (or not found) item as ``(item, history)``.
966 """ 1188 """
967 1189
968 if executable: 1190 if executable:
@@ -989,10 +1211,29 @@ def which(path, item, direction = 0, history = False, executable=False):
989 return "", hist 1211 return "", hist
990 return "" 1212 return ""
991 1213
1214def to_filemode(input):
1215 """
1216 Take a bitbake variable contents defining a file mode and return
1217 the proper python representation of the number
1218
1219 Arguments:
1220
1221 - ``input``: a string or number to convert, e.g. a bitbake variable
1222 string, assumed to be an octal representation
1223
1224 Returns the python file mode as a number
1225 """
1226 # umask might come in as a number or text string..
1227 if type(input) is int:
1228 return input
1229 return int(input, 8)
1230
992@contextmanager 1231@contextmanager
993def umask(new_mask): 1232def umask(new_mask):
994 """ 1233 """
995 Context manager to set the umask to a specific mask, and restore it afterwards. 1234 Context manager to set the umask to a specific mask, and restore it afterwards.
1235
1236 No return value.
996 """ 1237 """
997 current_mask = os.umask(new_mask) 1238 current_mask = os.umask(new_mask)
998 try: 1239 try:
@@ -1003,7 +1244,17 @@ def umask(new_mask):
1003def to_boolean(string, default=None): 1244def to_boolean(string, default=None):
1004 """ 1245 """
1005 Check input string and return boolean value True/False/None 1246 Check input string and return boolean value True/False/None
1006 depending upon the checks 1247 depending upon the checks.
1248
1249 Arguments:
1250
1251 - ``string``: input string.
1252 - ``default``: default return value if the input ``string`` is ``None``,
1253 ``0``, ``False`` or an empty string.
1254
1255 Returns ``True`` if the string is one of "y", "yes", "1", "true", ``False``
1256 if the string is one of "n", "no", "0", or "false". Return ``default`` if
1257 the input ``string`` is ``None``, ``0``, ``False`` or an empty string.
1007 """ 1258 """
1008 if not string: 1259 if not string:
1009 return default 1260 return default
@@ -1024,18 +1275,17 @@ def contains(variable, checkvalues, truevalue, falsevalue, d):
1024 1275
1025 Arguments: 1276 Arguments:
1026 1277
1027 variable -- the variable name. This will be fetched and expanded (using 1278 - ``variable``: the variable name. This will be fetched and expanded (using
1028 d.getVar(variable)) and then split into a set(). 1279 d.getVar(variable)) and then split into a set().
1029 1280 - ``checkvalues``: if this is a string it is split on whitespace into a set(),
1030 checkvalues -- if this is a string it is split on whitespace into a set(), 1281 otherwise coerced directly into a set().
1031 otherwise coerced directly into a set(). 1282 - ``truevalue``: the value to return if checkvalues is a subset of variable.
1032 1283 - ``falsevalue``: the value to return if variable is empty or if checkvalues is
1033 truevalue -- the value to return if checkvalues is a subset of variable. 1284 not a subset of variable.
1034 1285 - ``d``: the data store.
1035 falsevalue -- the value to return if variable is empty or if checkvalues is
1036 not a subset of variable.
1037 1286
1038 d -- the data store. 1287 Returns ``True`` if the variable contains the values specified, ``False``
1288 otherwise.
1039 """ 1289 """
1040 1290
1041 val = d.getVar(variable) 1291 val = d.getVar(variable)
@@ -1055,18 +1305,17 @@ def contains_any(variable, checkvalues, truevalue, falsevalue, d):
1055 1305
1056 Arguments: 1306 Arguments:
1057 1307
1058 variable -- the variable name. This will be fetched and expanded (using 1308 - ``variable``: the variable name. This will be fetched and expanded (using
1059 d.getVar(variable)) and then split into a set(). 1309 d.getVar(variable)) and then split into a set().
1310 - ``checkvalues``: if this is a string it is split on whitespace into a set(),
1311 otherwise coerced directly into a set().
1312 - ``truevalue``: the value to return if checkvalues is a subset of variable.
1313 - ``falsevalue``: the value to return if variable is empty or if checkvalues is
1314 not a subset of variable.
1315 - ``d``: the data store.
1060 1316
1061 checkvalues -- if this is a string it is split on whitespace into a set(), 1317 Returns ``True`` if the variable contains any of the values specified,
1062 otherwise coerced directly into a set(). 1318 ``False`` otherwise.
1063
1064 truevalue -- the value to return if checkvalues is a subset of variable.
1065
1066 falsevalue -- the value to return if variable is empty or if checkvalues is
1067 not a subset of variable.
1068
1069 d -- the data store.
1070 """ 1319 """
1071 val = d.getVar(variable) 1320 val = d.getVar(variable)
1072 if not val: 1321 if not val:
@@ -1081,17 +1330,17 @@ def contains_any(variable, checkvalues, truevalue, falsevalue, d):
1081 return falsevalue 1330 return falsevalue
1082 1331
1083def filter(variable, checkvalues, d): 1332def filter(variable, checkvalues, d):
1084 """Return all words in the variable that are present in the checkvalues. 1333 """Return all words in the variable that are present in the ``checkvalues``.
1085 1334
1086 Arguments: 1335 Arguments:
1087 1336
1088 variable -- the variable name. This will be fetched and expanded (using 1337 - ``variable``: the variable name. This will be fetched and expanded (using
1089 d.getVar(variable)) and then split into a set(). 1338 d.getVar(variable)) and then split into a set().
1339 - ``checkvalues``: if this is a string it is split on whitespace into a set(),
1340 otherwise coerced directly into a set().
1341 - ``d``: the data store.
1090 1342
1091 checkvalues -- if this is a string it is split on whitespace into a set(), 1343 Returns a list of string.
1092 otherwise coerced directly into a set().
1093
1094 d -- the data store.
1095 """ 1344 """
1096 1345
1097 val = d.getVar(variable) 1346 val = d.getVar(variable)
@@ -1107,8 +1356,27 @@ def filter(variable, checkvalues, d):
1107 1356
1108def get_referenced_vars(start_expr, d): 1357def get_referenced_vars(start_expr, d):
1109 """ 1358 """
1110 :return: names of vars referenced in start_expr (recursively), in quasi-BFS order (variables within the same level 1359 Get the names of the variables referenced in a given expression.
1111 are ordered arbitrarily) 1360
1361 Arguments:
1362
1363 - ``start_expr``: the expression where to look for variables references.
1364
1365 For example::
1366
1367 ${VAR_A} string ${VAR_B}
1368
1369 Or::
1370
1371 ${@d.getVar('VAR')}
1372
1373 If a variables makes references to other variables, the latter are also
1374 returned recursively.
1375
1376 - ``d``: the data store.
1377
1378 Returns the names of vars referenced in ``start_expr`` (recursively), in
1379 quasi-BFS order (variables within the same level are ordered arbitrarily).
1112 """ 1380 """
1113 1381
1114 seen = set() 1382 seen = set()
@@ -1188,7 +1456,9 @@ def multiprocessingpool(*args, **kwargs):
1188 return multiprocessing.Pool(*args, **kwargs) 1456 return multiprocessing.Pool(*args, **kwargs)
1189 1457
1190def exec_flat_python_func(func, *args, **kwargs): 1458def exec_flat_python_func(func, *args, **kwargs):
1191 """Execute a flat python function (defined with def funcname(args):...)""" 1459 """Execute a flat python function (defined with ``def funcname(args): ...``)
1460
1461 Returns the return value of the function."""
1192 # Prepare a small piece of python code which calls the requested function 1462 # Prepare a small piece of python code which calls the requested function
1193 # To do this we need to prepare two things - a set of variables we can use to pass 1463 # To do this we need to prepare two things - a set of variables we can use to pass
1194 # the values of arguments into the calling function, and the list of arguments for 1464 # the values of arguments into the calling function, and the list of arguments for
@@ -1214,48 +1484,57 @@ def edit_metadata(meta_lines, variables, varfunc, match_overrides=False):
1214 """Edit lines from a recipe or config file and modify one or more 1484 """Edit lines from a recipe or config file and modify one or more
1215 specified variable values set in the file using a specified callback 1485 specified variable values set in the file using a specified callback
1216 function. Lines are expected to have trailing newlines. 1486 function. Lines are expected to have trailing newlines.
1217 Parameters: 1487
1218 meta_lines: lines from the file; can be a list or an iterable 1488 Arguments:
1219 (e.g. file pointer) 1489
1220 variables: a list of variable names to look for. Functions 1490 - ``meta_lines``: lines from the file; can be a list or an iterable
1221 may also be specified, but must be specified with '()' at 1491 (e.g. file pointer)
1222 the end of the name. Note that the function doesn't have 1492 - ``variables``: a list of variable names to look for. Functions
1223 any intrinsic understanding of :append, :prepend, :remove, 1493 may also be specified, but must be specified with ``()`` at
1224 or overrides, so these are considered as part of the name. 1494 the end of the name. Note that the function doesn't have
1225 These values go into a regular expression, so regular 1495 any intrinsic understanding of ``:append``, ``:prepend``, ``:remove``,
1226 expression syntax is allowed. 1496 or overrides, so these are considered as part of the name.
1227 varfunc: callback function called for every variable matching 1497 These values go into a regular expression, so regular
1228 one of the entries in the variables parameter. The function 1498 expression syntax is allowed.
1229 should take four arguments: 1499 - ``varfunc``: callback function called for every variable matching
1230 varname: name of variable matched 1500 one of the entries in the variables parameter.
1231 origvalue: current value in file 1501
1232 op: the operator (e.g. '+=') 1502 The function should take four arguments:
1233 newlines: list of lines up to this point. You can use 1503
1234 this to prepend lines before this variable setting 1504 - ``varname``: name of variable matched
1235 if you wish. 1505 - ``origvalue``: current value in file
1236 and should return a four-element tuple: 1506 - ``op``: the operator (e.g. ``+=``)
1237 newvalue: new value to substitute in, or None to drop 1507 - ``newlines``: list of lines up to this point. You can use
1238 the variable setting entirely. (If the removal 1508 this to prepend lines before this variable setting
1239 results in two consecutive blank lines, one of the 1509 if you wish.
1240 blank lines will also be dropped). 1510
1241 newop: the operator to use - if you specify None here, 1511 And should return a four-element tuple:
1242 the original operation will be used. 1512
1243 indent: number of spaces to indent multi-line entries, 1513 - ``newvalue``: new value to substitute in, or ``None`` to drop
1244 or -1 to indent up to the level of the assignment 1514 the variable setting entirely. (If the removal
1245 and opening quote, or a string to use as the indent. 1515 results in two consecutive blank lines, one of the
1246 minbreak: True to allow the first element of a 1516 blank lines will also be dropped).
1247 multi-line value to continue on the same line as 1517 - ``newop``: the operator to use - if you specify ``None`` here,
1248 the assignment, False to indent before the first 1518 the original operation will be used.
1249 element. 1519 - ``indent``: number of spaces to indent multi-line entries,
1250 To clarify, if you wish not to change the value, then you 1520 or ``-1`` to indent up to the level of the assignment
1251 would return like this: return origvalue, None, 0, True 1521 and opening quote, or a string to use as the indent.
1252 match_overrides: True to match items with _overrides on the end, 1522 - ``minbreak``: ``True`` to allow the first element of a
1253 False otherwise 1523 multi-line value to continue on the same line as
1524 the assignment, ``False`` to indent before the first
1525 element.
1526
1527 To clarify, if you wish not to change the value, then you
1528 would return like this::
1529
1530 return origvalue, None, 0, True
1531 - ``match_overrides``: True to match items with _overrides on the end,
1532 False otherwise
1533
1254 Returns a tuple: 1534 Returns a tuple:
1255 updated: 1535
1256 True if changes were made, False otherwise. 1536 - ``updated``: ``True`` if changes were made, ``False`` otherwise.
1257 newlines: 1537 - ``newlines``: Lines after processing.
1258 Lines after processing
1259 """ 1538 """
1260 1539
1261 var_res = {} 1540 var_res = {}
@@ -1399,12 +1678,13 @@ def edit_metadata(meta_lines, variables, varfunc, match_overrides=False):
1399 1678
1400 1679
1401def edit_metadata_file(meta_file, variables, varfunc): 1680def edit_metadata_file(meta_file, variables, varfunc):
1402 """Edit a recipe or config file and modify one or more specified 1681 """Edit a recipe or configuration file and modify one or more specified
1403 variable values set in the file using a specified callback function. 1682 variable values set in the file using a specified callback function.
1404 The file is only written to if the value(s) actually change. 1683 The file is only written to if the value(s) actually change.
1405 This is basically the file version of edit_metadata(), see that 1684 This is basically the file version of ``bb.utils.edit_metadata()``, see that
1406 function's description for parameter/usage information. 1685 function's description for parameter/usage information.
1407 Returns True if the file was written to, False otherwise. 1686
1687 Returns ``True`` if the file was written to, ``False`` otherwise.
1408 """ 1688 """
1409 with open(meta_file, 'r') as f: 1689 with open(meta_file, 'r') as f:
1410 (updated, newlines) = edit_metadata(f, variables, varfunc) 1690 (updated, newlines) = edit_metadata(f, variables, varfunc)
@@ -1415,23 +1695,25 @@ def edit_metadata_file(meta_file, variables, varfunc):
1415 1695
1416 1696
1417def edit_bblayers_conf(bblayers_conf, add, remove, edit_cb=None): 1697def edit_bblayers_conf(bblayers_conf, add, remove, edit_cb=None):
1418 """Edit bblayers.conf, adding and/or removing layers 1698 """Edit ``bblayers.conf``, adding and/or removing layers.
1419 Parameters: 1699
1420 bblayers_conf: path to bblayers.conf file to edit 1700 Arguments:
1421 add: layer path (or list of layer paths) to add; None or empty 1701
1422 list to add nothing 1702 - ``bblayers_conf``: path to ``bblayers.conf`` file to edit
1423 remove: layer path (or list of layer paths) to remove; None or 1703 - ``add``: layer path (or list of layer paths) to add; ``None`` or empty
1424 empty list to remove nothing 1704 list to add nothing
1425 edit_cb: optional callback function that will be called after 1705 - ``remove``: layer path (or list of layer paths) to remove; ``None`` or
1426 processing adds/removes once per existing entry. 1706 empty list to remove nothing
1707 - ``edit_cb``: optional callback function that will be called
1708 after processing adds/removes once per existing entry.
1709
1427 Returns a tuple: 1710 Returns a tuple:
1428 notadded: list of layers specified to be added but weren't
1429 (because they were already in the list)
1430 notremoved: list of layers that were specified to be removed
1431 but weren't (because they weren't in the list)
1432 """
1433 1711
1434 import fnmatch 1712 - ``notadded``: list of layers specified to be added but weren't
1713 (because they were already in the list)
1714 - ``notremoved``: list of layers that were specified to be removed
1715 but weren't (because they weren't in the list)
1716 """
1435 1717
1436 def remove_trailing_sep(pth): 1718 def remove_trailing_sep(pth):
1437 if pth and pth[-1] == os.sep: 1719 if pth and pth[-1] == os.sep:
@@ -1550,7 +1832,22 @@ def get_collection_res(d):
1550 1832
1551 1833
1552def get_file_layer(filename, d, collection_res={}): 1834def get_file_layer(filename, d, collection_res={}):
1553 """Determine the collection (as defined by a layer's layer.conf file) containing the specified file""" 1835 """Determine the collection (or layer name, as defined by a layer's
1836 ``layer.conf`` file) containing the specified file.
1837
1838 Arguments:
1839
1840 - ``filename``: the filename to look for.
1841 - ``d``: the data store.
1842 - ``collection_res``: dictionary with the layer names as keys and file
1843 patterns to match as defined with the BBFILE_COLLECTIONS and
1844 BBFILE_PATTERN variables respectively. The return value of
1845 ``bb.utils.get_collection_res()`` is the default if this variable is
1846 not specified.
1847
1848 Returns the layer name containing the file. If multiple layers contain the
1849 file, the last matching layer name from collection_res is returned.
1850 """
1554 if not collection_res: 1851 if not collection_res:
1555 collection_res = get_collection_res(d) 1852 collection_res = get_collection_res(d)
1556 1853
@@ -1588,7 +1885,13 @@ class PrCtlError(Exception):
1588 1885
1589def signal_on_parent_exit(signame): 1886def signal_on_parent_exit(signame):
1590 """ 1887 """
1591 Trigger signame to be sent when the parent process dies 1888 Trigger ``signame`` to be sent when the parent process dies.
1889
1890 Arguments:
1891
1892 - ``signame``: name of the signal. See ``man signal``.
1893
1894 No return value.
1592 """ 1895 """
1593 signum = getattr(signal, signame) 1896 signum = getattr(signal, signame)
1594 # http://linux.die.net/man/2/prctl 1897 # http://linux.die.net/man/2/prctl
@@ -1623,7 +1926,7 @@ def ioprio_set(who, cls, value):
1623 bb.warn("Unable to set IO Prio for arch %s" % _unamearch) 1926 bb.warn("Unable to set IO Prio for arch %s" % _unamearch)
1624 1927
1625def set_process_name(name): 1928def set_process_name(name):
1626 from ctypes import cdll, byref, create_string_buffer 1929 from ctypes import byref, create_string_buffer
1627 # This is nice to have for debugging, not essential 1930 # This is nice to have for debugging, not essential
1628 try: 1931 try:
1629 libc = cdll.LoadLibrary('libc.so.6') 1932 libc = cdll.LoadLibrary('libc.so.6')
@@ -1675,6 +1978,13 @@ def disable_network(uid=None, gid=None):
1675 Disable networking in the current process if the kernel supports it, else 1978 Disable networking in the current process if the kernel supports it, else
1676 just return after logging to debug. To do this we need to create a new user 1979 just return after logging to debug. To do this we need to create a new user
1677 namespace, then map back to the original uid/gid. 1980 namespace, then map back to the original uid/gid.
1981
1982 Arguments:
1983
1984 - ``uid``: original user id.
1985 - ``gid``: original user group id.
1986
1987 No return value.
1678 """ 1988 """
1679 libc = ctypes.CDLL('libc.so.6') 1989 libc = ctypes.CDLL('libc.so.6')
1680 1990
@@ -1744,9 +2054,14 @@ class LogCatcher(logging.Handler):
1744 2054
1745def is_semver(version): 2055def is_semver(version):
1746 """ 2056 """
1747 Is the version string following the semver semantic? 2057 Arguments:
2058
2059 - ``version``: the version string.
2060
2061 Returns ``True`` if the version string follow semantic versioning, ``False``
2062 otherwise.
1748 2063
1749 https://semver.org/spec/v2.0.0.html 2064 See https://semver.org/spec/v2.0.0.html.
1750 """ 2065 """
1751 regex = re.compile( 2066 regex = re.compile(
1752 r""" 2067 r"""
@@ -1784,6 +2099,8 @@ def rename(src, dst):
1784def environment(**envvars): 2099def environment(**envvars):
1785 """ 2100 """
1786 Context manager to selectively update the environment with the specified mapping. 2101 Context manager to selectively update the environment with the specified mapping.
2102
2103 No return value.
1787 """ 2104 """
1788 backup = dict(os.environ) 2105 backup = dict(os.environ)
1789 try: 2106 try:
@@ -1800,6 +2117,13 @@ def is_local_uid(uid=''):
1800 """ 2117 """
1801 Check whether uid is a local one or not. 2118 Check whether uid is a local one or not.
1802 Can't use pwd module since it gets all UIDs, not local ones only. 2119 Can't use pwd module since it gets all UIDs, not local ones only.
2120
2121 Arguments:
2122
2123 - ``uid``: user id. If not specified the user id is determined from
2124 ``os.getuid()``.
2125
2126 Returns ``True`` is the user id is local, ``False`` otherwise.
1803 """ 2127 """
1804 if not uid: 2128 if not uid:
1805 uid = os.getuid() 2129 uid = os.getuid()
@@ -1814,7 +2138,7 @@ def is_local_uid(uid=''):
1814 2138
1815def mkstemp(suffix=None, prefix=None, dir=None, text=False): 2139def mkstemp(suffix=None, prefix=None, dir=None, text=False):
1816 """ 2140 """
1817 Generates a unique filename, independent of time. 2141 Generates a unique temporary file, independent of time.
1818 2142
1819 mkstemp() in glibc (at least) generates unique file names based on the 2143 mkstemp() in glibc (at least) generates unique file names based on the
1820 current system time. When combined with highly parallel builds, and 2144 current system time. When combined with highly parallel builds, and
@@ -1823,6 +2147,18 @@ def mkstemp(suffix=None, prefix=None, dir=None, text=False):
1823 2147
1824 This function adds additional entropy to the file name so that a collision 2148 This function adds additional entropy to the file name so that a collision
1825 is independent of time and thus extremely unlikely. 2149 is independent of time and thus extremely unlikely.
2150
2151 Arguments:
2152
2153 - ``suffix``: filename suffix.
2154 - ``prefix``: filename prefix.
2155 - ``dir``: directory where the file will be created.
2156 - ``text``: if ``True``, the file is opened in text mode.
2157
2158 Returns a tuple containing:
2159
2160 - the file descriptor for the created file
2161 - the name of the file.
1826 """ 2162 """
1827 entropy = "".join(random.choices("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", k=20)) 2163 entropy = "".join(random.choices("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", k=20))
1828 if prefix: 2164 if prefix:
@@ -1833,12 +2169,20 @@ def mkstemp(suffix=None, prefix=None, dir=None, text=False):
1833 2169
1834def path_is_descendant(descendant, ancestor): 2170def path_is_descendant(descendant, ancestor):
1835 """ 2171 """
1836 Returns True if the path `descendant` is a descendant of `ancestor` 2172 Returns ``True`` if the path ``descendant`` is a descendant of ``ancestor``
1837 (including being equivalent to `ancestor` itself). Otherwise returns False. 2173 (including being equivalent to ``ancestor`` itself). Otherwise returns
2174 ``False``.
2175
1838 Correctly accounts for symlinks, bind mounts, etc. by using 2176 Correctly accounts for symlinks, bind mounts, etc. by using
1839 os.path.samestat() to compare paths 2177 ``os.path.samestat()`` to compare paths.
2178
2179 May raise any exception that ``os.stat()`` raises.
1840 2180
1841 May raise any exception that os.stat() raises 2181 Arguments:
2182
2183 - ``descendant``: path to check for being an ancestor.
2184 - ``ancestor``: path to the ancestor ``descendant`` will be checked
2185 against.
1842 """ 2186 """
1843 2187
1844 ancestor_stat = os.stat(ancestor) 2188 ancestor_stat = os.stat(ancestor)
@@ -1857,12 +2201,31 @@ def path_is_descendant(descendant, ancestor):
1857# If we don't have a timeout of some kind and a process/thread exits badly (for example 2201# If we don't have a timeout of some kind and a process/thread exits badly (for example
1858# OOM killed) and held a lock, we'd just hang in the lock futex forever. It is better 2202# OOM killed) and held a lock, we'd just hang in the lock futex forever. It is better
1859# we exit at some point than hang. 5 minutes with no progress means we're probably deadlocked. 2203# we exit at some point than hang. 5 minutes with no progress means we're probably deadlocked.
2204# This function can still deadlock python since it can't signal the other threads to exit
2205# (signals are handled in the main thread) and even os._exit() will wait on non-daemon threads
2206# to exit.
1860@contextmanager 2207@contextmanager
1861def lock_timeout(lock): 2208def lock_timeout(lock):
1862 held = lock.acquire(timeout=5*60)
1863 try: 2209 try:
2210 s = signal.pthread_sigmask(signal.SIG_BLOCK, signal.valid_signals())
2211 held = lock.acquire(timeout=5*60)
1864 if not held: 2212 if not held:
2213 bb.server.process.serverlog("Couldn't get the lock for 5 mins, timed out, exiting.\n%s" % traceback.format_stack())
1865 os._exit(1) 2214 os._exit(1)
1866 yield held 2215 yield held
1867 finally: 2216 finally:
1868 lock.release() 2217 lock.release()
2218 signal.pthread_sigmask(signal.SIG_SETMASK, s)
2219
2220# A version of lock_timeout without the check that the lock was locked and a shorter timeout
2221@contextmanager
2222def lock_timeout_nocheck(lock):
2223 l = False
2224 try:
2225 s = signal.pthread_sigmask(signal.SIG_BLOCK, signal.valid_signals())
2226 l = lock.acquire(timeout=10)
2227 yield l
2228 finally:
2229 if l:
2230 lock.release()
2231 signal.pthread_sigmask(signal.SIG_SETMASK, s)