Re: [PATCH] fetch--tool: fix uninitialized buffer when reading from stdin
- From
Junio C Hamano <junkio@cox.net>
- Date
- Feb 26, 2007, 19:37 UTC
- Message-ID
- <7vfy8sn20o.fsf@assigned-by-dhcp.cox.net>
- In-Reply-To
- <Pine.LNX.4.64.0702261003480.12485@woody.linux-foundation.org>
Linus Torvalds <torvalds@linux-foundation.org> writes:
Show 9 quoted lines
> Well, that CHUNK_SIZE is just silly. I don't see why you'd have a > chunk-size of a megabyte to begin with, IO doesn't really get any more > efficient that way. And yeah, in this case it would easily hide the bug, > because in practice nobody would ever test with that much input data. > > It might make sense to make the chunk-size smaller just from a testability > standpoint (not to mention that it's probably currently just wasting > memory for most users - although at least under Linux, if you never use a > page, none will be allocated for you, so the OS may hide the wastage).
How about doing this instead?
-- >8 -- [PATCH] fetch--tool: fix uninitialized buffer when reading from stdin
The original code allocates too much space and forgets to NUL terminate the string.
Signed-off-by: Junio C Hamano <junkio@cox.net> ---
builtin-fetch--tool.c | 19 +++++++++++++------ 1 files changed, 13 insertions(+), 6 deletions(-)
diff --git a/builtin-fetch--tool.c b/builtin-fetch--tool.c index 48de08d..a068f8d 100644 --- a/builtin-fetch--tool.c +++ b/builtin-fetch--tool.c @@ -2,17 +2,24 @@ #include "refs.h" #include "commit.h" -#define CHUNK_SIZE (1048576) +#define CHUNK_SIZE 1024 static char *get_stdin(void) { + int offset = 0; char *data = xmalloc(CHUNK_SIZE); - int offset = 0, read = 0; - read = xread(0, data, CHUNK_SIZE); - while (read == CHUNK_SIZE) { - offset += CHUNK_SIZE; + + while (1) { + int cnt = xread(0, data + offset, CHUNK_SIZE); + if (cnt < 0) + die("error reading standard input: %s", + strerror(errno)); + if (cnt == 0) { + data[offset] = 0; + break; + } + offset += cnt; data = xrealloc(data, offset + CHUNK_SIZE); - read = xread(0, data + offset, CHUNK_SIZE); } return data; }