blob: dab64ef50199ad6aa1f2a315f4f1db5d15df52a9 [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001#!/usr/bin/env python3
2
3import sys, os, subprocess, re, shutil
4
5whitelist = (
6 # type is supported by dash
7 'if type systemctl >/dev/null 2>/dev/null; then',
8 'if type systemd-tmpfiles >/dev/null 2>/dev/null; then',
Brad Bishop6e60e8b2018-02-01 10:27:11 -05009 'type update-rc.d >/dev/null 2>/dev/null; then',
Patrick Williamsc0f7c042017-02-23 20:41:17 -060010 'command -v',
11 # HOSTNAME is set locally
12 'buildhistory_single_commit "$CMDLINE" "$HOSTNAME"',
13 # False-positive, match is a grep not shell expression
14 'grep "^$groupname:[^:]*:[^:]*:\\([^,]*,\\)*$username\\(,[^,]*\\)*"',
15 # TODO verify dash's '. script args' behaviour
16 '. $target_sdk_dir/${oe_init_build_env_path} $target_sdk_dir >> $LOGFILE'
17 )
18
19def is_whitelisted(s):
20 for w in whitelist:
21 if w in s:
22 return True
23 return False
24
Brad Bishop6e60e8b2018-02-01 10:27:11 -050025SCRIPT_LINENO_RE = re.compile(r' line (\d+) ')
26BASHISM_WARNING = re.compile(r'^(possible bashism in.*)$', re.MULTILINE)
27
28def process(filename, function, lineno, script):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060029 import tempfile
30
31 if not script.startswith("#!"):
32 script = "#! /bin/sh\n" + script
33
34 fn = tempfile.NamedTemporaryFile(mode="w+t")
35 fn.write(script)
36 fn.flush()
37
38 try:
39 subprocess.check_output(("checkbashisms.pl", fn.name), universal_newlines=True, stderr=subprocess.STDOUT)
40 # No bashisms, so just return
41 return
42 except subprocess.CalledProcessError as e:
43 # TODO check exit code is 1
44
45 # Replace the temporary filename with the function and split it
Brad Bishop6e60e8b2018-02-01 10:27:11 -050046 output = e.output.replace(fn.name, function)
47 if not output or not output.startswith('possible bashism'):
48 # Probably starts with or contains only warnings. Dump verbatim
49 # with one space indention. Can't do the splitting and whitelist
50 # checking below.
51 return '\n'.join([filename,
52 ' Unexpected output from checkbashisms.pl'] +
53 [' ' + x for x in output.splitlines()])
Patrick Williamsc0f7c042017-02-23 20:41:17 -060054
Brad Bishop6e60e8b2018-02-01 10:27:11 -050055 # We know that the first line matches and that therefore the first
56 # list entry will be empty - skip it.
57 output = BASHISM_WARNING.split(output)[1:]
58 # Turn the output into a single string like this:
59 # /.../foobar.bb
60 # possible bashism in updatercd_postrm line 2 (type):
61 # if ${@use_updatercd(d)} && type update-rc.d >/dev/null 2>/dev/null; then
62 # ...
63 # ...
Patrick Williamsc0f7c042017-02-23 20:41:17 -060064 result = []
65 # Check the results against the whitelist
66 for message, source in zip(output[0::2], output[1::2]):
67 if not is_whitelisted(source):
Brad Bishop6e60e8b2018-02-01 10:27:11 -050068 if lineno is not None:
69 message = SCRIPT_LINENO_RE.sub(lambda m: ' line %d ' % (int(m.group(1)) + int(lineno) - 1),
70 message)
71 result.append(' ' + message.strip())
72 result.extend([' %s' % x for x in source.splitlines()])
73 if result:
74 result.insert(0, filename)
75 return '\n'.join(result)
76 else:
77 return None
Patrick Williamsc0f7c042017-02-23 20:41:17 -060078
79def get_tinfoil():
80 scripts_path = os.path.dirname(os.path.realpath(__file__))
81 lib_path = scripts_path + '/lib'
82 sys.path = sys.path + [lib_path]
83 import scriptpath
84 scriptpath.add_bitbake_lib_path()
85 import bb.tinfoil
86 tinfoil = bb.tinfoil.Tinfoil()
87 tinfoil.prepare()
88 # tinfoil.logger.setLevel(logging.WARNING)
89 return tinfoil
90
91if __name__=='__main__':
92 import shutil
93 if shutil.which("checkbashisms.pl") is None:
Brad Bishop6e60e8b2018-02-01 10:27:11 -050094 print("Cannot find checkbashisms.pl on $PATH, get it from https://anonscm.debian.org/cgit/collab-maint/devscripts.git/plain/scripts/checkbashisms.pl")
Patrick Williamsc0f7c042017-02-23 20:41:17 -060095 sys.exit(1)
96
Brad Bishop6e60e8b2018-02-01 10:27:11 -050097 # The order of defining the worker function,
98 # initializing the pool and connecting to the
99 # bitbake server is crucial, don't change it.
100 def func(item):
101 (filename, key, lineno), script = item
102 return process(filename, key, lineno, script)
103
104 import multiprocessing
105 pool = multiprocessing.Pool()
106
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600107 tinfoil = get_tinfoil()
108
109 # This is only the default configuration and should iterate over
110 # recipecaches to handle multiconfig environments
111 pkg_pn = tinfoil.cooker.recipecaches[""].pkg_pn
112
113 # TODO: use argparse and have --help
114 if len(sys.argv) > 1:
115 initial_pns = sys.argv[1:]
116 else:
117 initial_pns = sorted(pkg_pn)
118
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500119 pns = set()
120 scripts = {}
121 print("Generating scripts...")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600122 for pn in initial_pns:
123 for fn in pkg_pn[pn]:
124 # There's no point checking multiple BBCLASSEXTENDed variants of the same recipe
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500125 # (at least in general - there is some risk that the variants contain different scripts)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600126 realfn, _, _ = bb.cache.virtualfn2realfn(fn)
127 if realfn not in pns:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500128 pns.add(realfn)
129 data = tinfoil.parse_recipe_file(realfn)
130 for key in data.keys():
131 if data.getVarFlag(key, "func") and not data.getVarFlag(key, "python"):
132 script = data.getVar(key, False)
133 if script:
134 filename = data.getVarFlag(key, "filename")
135 lineno = data.getVarFlag(key, "lineno")
136 # There's no point in checking a function multiple
137 # times just because different recipes include it.
138 # We identify unique scripts by file, name, and (just in case)
139 # line number.
140 attributes = (filename or realfn, key, lineno)
141 scripts.setdefault(attributes, script)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600142
143
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600144 print("Scanning scripts...\n")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500145 for result in pool.imap(func, scripts.items()):
146 if result:
147 print(result)
148 tinfoil.shutdown()