Commit d9c30507 authored by Sean Anderson's avatar Sean Anderson Committed by Tom Rini
Browse files

checkpatch: Add warnings for using strn(cat|cpy)

strn(cat|cpy) has a bad habit of not nul-terminating the destination,
resulting in constructions like

	strncpy(foo, bar, sizeof(foo) - 1);
	foo[sizeof(foo) - 1] = '\0';

However, it is very easy to forget about this behavior and accidentally
leave a string unterminated. This has shown up in some recent coverity
scans [1, 2] (including code recently touched by yours truly).

Fortunately, the guys at OpenBSD came up with strl(cat|cpy), which always
nul-terminate strings. These functions are already in U-Boot, so we should
encourage new code to use them instead of strn(cat|cpy).


Signed-off-by: Sean Anderson's avatarSean Anderson <>
Reviewed-by: Simon Glass's avatarSimon Glass <>
parent 69a75298
......@@ -2365,6 +2365,12 @@ sub u_boot_line {
"Use 'if (IS_ENABLED(CONFIG...))' instead of '#if or #ifdef' where possible\n" . $herecurr);
# prefer strl(cpy|cat) over strn(cpy|cat)
if ($line =~ /\bstrn(cpy|cat)\s*\(/) {
"strl$1 is preferred over strn$1 because it always produces a nul-terminated string\n" . $herecurr);
# use defconfig to manage CONFIG_CMD options
if ($line =~ /\+\s*#\s*(define|undef)\s+(CONFIG_CMD\w*)\b/) {
......@@ -353,7 +353,7 @@ index 0000000..2234c87
pm: PatchMaker object to use
msg" Expected message (e.g. 'LIVETREE')
msg: Expected message (e.g. 'LIVETREE')
pmtype: Type of problem ('error', 'warning')
result = pm.run_checkpatch()
......@@ -439,6 +439,18 @@ index 0000000..2234c87
self.check_struct('per_device_auto', '_priv', 'DEVICE_PRIV_AUTO')
self.check_struct('per_device_plat_auto', '_plat', 'DEVICE_PLAT_AUTO')
def check_strl(self, func):
"""Check one of the checks for strn(cpy|cat)"""
pm = PatchMaker()
pm.add_line('common/main.c', "strn%s(foo, bar, sizeof(foo));" % func)
self.checkSingleMessage(pm, "STRL",
"strl%s is preferred over strn%s because it always produces a nul-terminated string\n"
% (func, func))
def testStrl(self):
"""Check for uses of strn(cat|cpy)"""
if __name__ == "__main__":
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment