lkml.org 
[lkml]   [2012]   [Apr]   [8]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
Patch in this message
/
From
Subject[PATCH 3/7] parse-events: Introduce extend_token()
Date
The __read_token() function has some duplicated code to handle
internal buffer overflow. Factor them out to new extend_token().

According to the man pages of realloc/free(3), they can handle
NULL pointer input so that it can be ended up to compact the code.
Also handle error path correctly.

Signed-off-by: Namhyung Kim <namhyung.kim@lge.com>
---
parse-events.c | 48 ++++++++++++++++++++++--------------------------
1 files changed, 22 insertions(+), 26 deletions(-)

diff --git a/parse-events.c b/parse-events.c
index f90af1a..0b1e40a 100644
--- a/parse-events.c
+++ b/parse-events.c
@@ -771,6 +771,23 @@ int pevent_peek_char(void)
return __peek_char();
}

+static int extend_token(char **tok, char *buf, int size)
+{
+ char *newtok = realloc(*tok, size);
+ if (!newtok) {
+ free(*tok);
+ *tok = NULL;
+ return -1;
+ }
+
+ if (!*tok)
+ strcpy(newtok, buf);
+ else
+ strcat(newtok, buf);
+ *tok = newtok;
+ return 0;
+}
+
static enum event_type force_token(const char *str, char **tok);

static enum event_type __read_token(char **tok)
@@ -855,17 +872,10 @@ static enum event_type __read_token(char **tok)
do {
if (i == (BUFSIZ - 1)) {
buf[i] = 0;
- if (*tok) {
- *tok = realloc(*tok, tok_size + BUFSIZ);
- if (!*tok)
- return EVENT_NONE;
- strcat(*tok, buf);
- } else
- *tok = strdup(buf);
+ tok_size += BUFSIZ;

- if (!*tok)
+ if (extend_token(tok, buf, tok_size) < 0)
return EVENT_NONE;
- tok_size += BUFSIZ;
i = 0;
}
last_ch = ch;
@@ -904,17 +914,10 @@ static enum event_type __read_token(char **tok)
while (get_type(__peek_char()) == type) {
if (i == (BUFSIZ - 1)) {
buf[i] = 0;
- if (*tok) {
- *tok = realloc(*tok, tok_size + BUFSIZ);
- if (!*tok)
- return EVENT_NONE;
- strcat(*tok, buf);
- } else
- *tok = strdup(buf);
+ tok_size += BUFSIZ;

- if (!*tok)
+ if (extend_token(tok, buf, tok_size) < 0)
return EVENT_NONE;
- tok_size += BUFSIZ;
i = 0;
}
ch = __read_char();
@@ -923,14 +926,7 @@ static enum event_type __read_token(char **tok)

out:
buf[i] = 0;
- if (*tok) {
- *tok = realloc(*tok, tok_size + i);
- if (!*tok)
- return EVENT_NONE;
- strcat(*tok, buf);
- } else
- *tok = strdup(buf);
- if (!*tok)
+ if (extend_token(tok, buf, tok_size + i + 1) < 0)
return EVENT_NONE;

if (type == EVENT_ITEM) {
--
1.7.7.6


\
 
 \ /
  Last update: 2012-04-09 04:59    [W:0.119 / U:0.236 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site