[utility perl script] strncmp() -> str_has_prefix() conversions

From: Joe Perches
Date: Fri Jan 11 2019 - 03:10:51 EST


On Fri, 2018-12-21 at 23:19 -0500, Steven Rostedt wrote:
> str_has_prefix

A coccinelle script could be more thorough but here
is a trivial perl script that can do most of the
strncmp() -> str_has_prefix()
conversions where there is a constant string as one of
the first two arguments of strncmp like any of:

strncmp(foo, "bar", 3)
strncmp(foo, "bar", strlen("bar"))
strncmp(foo, "bar", sizeof("bar") - 1)
strncmp("foo", bar, 3)
strncmp("foo", bar, strlen("foo"))
strncmp("foo", bar",
sizeof("foo") - 1)

It could be used with a particular path or file:

$ git grep -w --name-only strncmp <path> | \
grep -vP '^(tools|scripts)' | \
while read file ; do \
echo $file ; \
perl -i ./strncmp.perl $file ; \
done

It mostly works, but there are a few uses that
are not converted properly when the non const
string argument to strncmp is an expression like

strncmp(a+b, "foo", 3)

There are also strncmp uses that remain after
this script is run where strncmp should just
be converted to strcmp instead like:

strncmp(p, "foo", sizeof(foo))
and
strncmp(p, "foo", 4)

The script converts the most common cases:

## counted length of string
# strncmp(arg, string, counted length of string) == 0
# strncmp(arg, string, counted length of string) != 0
# !strncmp(arg, string, counted length of string)
# strncmp(arg, string, counted length of string)

## Reversed string/arg counted length of string uses
# strncmp(string, arg, counted length of string) == 0
# strncmp(string, arg, counted length of string) != 0
# !strncmp(string, arg, counted length of string)
# strncmp(string, arg, counted length of string)

## strlen uses
# strncmp(arg, string, strlen(string)) == 0
# !strncmp(arg, string, strlen(string))

## reversed string/arg strlen uses
# strncmp(string, arg, strlen(string)) == 0
# !strncmp(string, arg, strlen(string))

## 'sizeof(string) - 1' uses
# strncmp(arg, string, sizeof(string) - 1) == 0
# !strncmp(arg, string, sizeof(string) - 1)


On linux-next, running the script below

$ git grep -w --name-only strncmp | \
grep -vP '^(tools|scripts)' | \
while read file ; do \
echo $file ; \
perl -i ./strncmp.perl $file ; \
done

produces:

$ git diff --shortstat
437 files changed, 1483 insertions(+), 1500 deletions(-)

Attachment: strncmp.perl
Description: Perl program