blob: a979bd29650977d4c6b46b9be784055682ff8105 [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__':
Brad Bishop316dfdd2018-06-25 12:45:53 -040092 import argparse, shutil
93
94 parser = argparse.ArgumentParser(description='Bashim detector for shell fragments in recipes.')
95 parser.add_argument("recipes", metavar="RECIPE", nargs="*", help="recipes to check (if not specified, all will be checked)")
96 parser.add_argument("--verbose", default=False, action="store_true")
97 args = parser.parse_args()
98
Patrick Williamsc0f7c042017-02-23 20:41:17 -060099 if shutil.which("checkbashisms.pl") is None:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500100 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 -0600101 sys.exit(1)
102
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500103 # The order of defining the worker function,
104 # initializing the pool and connecting to the
105 # bitbake server is crucial, don't change it.
106 def func(item):
107 (filename, key, lineno), script = item
Brad Bishop316dfdd2018-06-25 12:45:53 -0400108 if args.verbose:
109 print("Scanning %s:%s" % (filename, key))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500110 return process(filename, key, lineno, script)
111
112 import multiprocessing
113 pool = multiprocessing.Pool()
114
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600115 tinfoil = get_tinfoil()
116
117 # This is only the default configuration and should iterate over
118 # recipecaches to handle multiconfig environments
119 pkg_pn = tinfoil.cooker.recipecaches[""].pkg_pn
120
Brad Bishop316dfdd2018-06-25 12:45:53 -0400121 if args.recipes:
122 initial_pns = args.recipes
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600123 else:
124 initial_pns = sorted(pkg_pn)
125
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500126 pns = set()
127 scripts = {}
128 print("Generating scripts...")
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600129 for pn in initial_pns:
130 for fn in pkg_pn[pn]:
131 # There's no point checking multiple BBCLASSEXTENDed variants of the same recipe
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500132 # (at least in general - there is some risk that the variants contain different scripts)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600133 realfn, _, _ = bb.cache.virtualfn2realfn(fn)
134 if realfn not in pns:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500135 pns.add(realfn)
136 data = tinfoil.parse_recipe_file(realfn)
137 for key in data.keys():
138 if data.getVarFlag(key, "func") and not data.getVarFlag(key, "python"):
139 script = data.getVar(key, False)
140 if script:
141 filename = data.getVarFlag(key, "filename")
142 lineno = data.getVarFlag(key, "lineno")
143 # There's no point in checking a function multiple
144 # times just because different recipes include it.
145 # We identify unique scripts by file, name, and (just in case)
146 # line number.
147 attributes = (filename or realfn, key, lineno)
148 scripts.setdefault(attributes, script)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600149
150
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600151 print("Scanning scripts...\n")
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500152 for result in pool.imap(func, scripts.items()):
153 if result:
154 print(result)
155 tinfoil.shutdown()