Skip to contentSkip to conversation

lib/parser: cleanup match_number()

PATCH In review Namhyung Kim 2 participants 2 messages Oct 8, 2010 Library code

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 lib/parser: cleanup match_number()

Use new variable 'len' to make code more readable.

---
 lib/parser.c |    7 ++++---
 1 files changed, 4 insertions(+), 3 deletions(-)
lib/parser.c +4 -3
index fb34977..6e89eca 100644
@@ -128,12 +128,13 @@ static int match_number(substring_t *s, int *result, int base)
 	char *endp;
 	char *buf;
 	int ret;
+	size_t len = s->to - s->from;
 
-	buf = kmalloc(s->to - s->from + 1, GFP_KERNEL);
+	buf = kmalloc(len + 1, GFP_KERNEL);
 	if (!buf)
 		return -ENOMEM;
-	memcpy(buf, s->from, s->to - s->from);
-	buf[s->to - s->from] = '\0';
+	memcpy(buf, s->from, len);
+	buf[len] = '\0';
 	*result = simple_strtol(buf, &endp, base);
 	ret = 0;
 	if (endp == buf)
Signature · 1 line
1.7.0.4
maintainer
#1 lore raw
Quoted 18 lines · On Sat, 9 Oct 2010 00:44:17 +0900 Namhyung Kim <[email protected]> wrote:

Use new variable 'len' to make code more readable.

---
 lib/parser.c |    7 ++++---
 1 files changed, 4 insertions(+), 3 deletions(-)
lib/parser.c +1 -1
index fb34977..6e89eca 100644
@@ -128,12 +128,13 @@ static int match_number(substring_t *s, int *result, int base)
 	char *endp;
 	char *buf;
 	int ret;
+	size_t len = s->to - s->from;
 
-	buf = kmalloc(s->to - s->from + 1, GFP_KERNEL);

lib/parser.c static int match_number(substring_t *s, int *result, int base) · line 140

Quoted 10 lines
lib/parser.c +3 -2
+	buf = kmalloc(len + 1, GFP_KERNEL);
 	if (!buf)
 		return -ENOMEM;
-	memcpy(buf, s->from, s->to - s->from);
-	buf[s->to - s->from] = '\0';
+	memcpy(buf, s->from, len);
+	buf[len] = '\0';
 	*result = simple_strtol(buf, &endp, base);
 	ret = 0;
 	if (endp == buf)

Fair enough. `len' should strictly be ptrdiff_t and then later on it wants to be size_t. I can't think of much to do about that...

The function itself looks a bit buggy to me:

static int match_number(substring_t *s, int *result, int base)

{
	char *endp;
	char *buf;
	int ret;
	size_t len = s->to - s->from;

	buf = kmalloc(len + 1, GFP_KERNEL);
	if (!buf)
		return -ENOMEM;
	memcpy(buf, s->from, len);
	buf[len] = '\0';
	*result = simple_strtol(buf, &endp, base);
	ret = 0;
	if (endp == buf)
		ret = -EINVAL;
	kfree(buf);
	return ret;
}

afaict, if you feed it "12q34" then simple_strtoul() will return a pointer to the 'q' and the result is 12. The `if (endp == buf)' check will return false, so this function's attempt to check that all digits were valid doesn't work right.

If I'm correct, that's fixable by using strict_strtol() or by switching the test to "if (*endp == '\0')" or similar. But fixing this may easily break existing kernel code and existing machine installations, so we need to tread carefully.