@matheusbsbs / matheus-bagliano / commits / 09f2825147
Fork 0

git-grep: don't use sscanf

If you use scanf or sscanf to parse integers, your code probably accepts bogus inputs. For example, builtin-grep (aka git-grep) uses sscanf(scan, "%u", &num) to parse the integer argument to -A, -B, -C. Currently, "-C 1,000" and "-C 4294967297" are both treated just like "-C 1": $ git-grep -h -C 4294967297 juggle out and you may find it easier to switch back and forth if you juggle multiple lines of development simultaneously. Of course, you will pay the price of more disk usage to hold The obvious fix is to use strtoul instead. But using a bare strtoul is too messy, at least when done properly, so I've added a wrapper function. The new function in the patch below belongs elsewhere if it would be useful in replacing any of the four remaining uses of sscanf. One final note: With this change, I get a slightly different diagnostic depending on the context size: $ ./git-grep -h -C 4294967296 juggle fatal: 4294967296: invalid context length argument [Exit 128] $ ./git-grep -h -C 4294967295 juggle grep: 4294967295: invalid context length argument [Exit 1] A common convention that makes it easy to identify the source of a diagnostic is to include the program name before the first ":". Whether that should be "git" or "git-grep" is another question. Using "grep" or "fatal" is misleading. Signed-off-by: Jim Meyering <jim@meyering.net> Signed-off-by: Junio C Hamano <junkio@cox.net>

Jim Meyering committed Mar 12, 2007 at 13:11 UTC 09f2825147d44bd0333f7f47d8ab3837f0848867
1 file changed +14 -1
builtin-grep.c
+14 -1
@@ -431,6 +431,19 @@ static const char emsg_missing_context_len[] =
431 static const char emsg_missing_argument[] =
432 "option requires an argument -%s";
433
434 +static int strtoul_ui(char const *s, unsigned int *result)
435 +{
436 + unsigned long ul;
437 + char *p;
438 +
439 + errno = 0;
440 + ul = strtoul(s, &p, 10);
441 + if (errno || *p || p == s || (unsigned int) ul != ul)
442 + return -1;
443 + *result = ul;
444 + return 0;
445 +}
446 +
447 int cmd_grep(int argc, const char **argv, const char *prefix)
448 {
449 int hit = 0;
@@ -553,7 +566,7 @@ int cmd_grep(int argc, const char **argv, const char *prefix)
566 scan = arg + 1;
567 break;
568 }
556 - if (sscanf(scan, "%u", &num) != 1)
569 + if (strtoul_ui(scan, &num))
570 die(emsg_invalid_context_len, scan);
571 switch (arg[1]) {
572 case 'A':