Skip to content

Commit 475f7b5

Browse files
committed
parse-options: fix memory leak when calling parse_options
call parse_options twice and occasionally meet unknown option in the same place would cause memory leak, since the second `xstrdup` in `parse_options_step` would make the first `xstrdup` unreachable. One solution is allocate one more magic byte for the unknown option to indicate that argv[?] stores a heap allocated arg. Assume for all arg, `*((char *)arg - 1)` is valid, we could put a magic number before the unknown option. Next time calling "xstrdup" will check the magic number first, and frees the previous heap allocated memory. Signed-off-by: Lidong Yan <[email protected]>
1 parent 6f84262 commit 475f7b5

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

parse-options.c

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,8 @@ enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
886886
const char * const usagestr[])
887887
{
888888
int internal_help = !(ctx->flags & PARSE_OPT_NO_INTERNAL_HELP);
889+
char *magic_ptr = NULL;
890+
size_t opt_sz = 0;
889891

890892
/* we must reset ->opt, unknown short option leave it dangling */
891893
ctx->opt = NULL;
@@ -981,7 +983,15 @@ enum parse_opt_result parse_options_step(struct parse_opt_ctx_t *ctx,
981983
*
982984
* This is leaky, too bad.
983985
*/
984-
ctx->argv[0] = xstrdup(ctx->opt - 1);
986+
magic_ptr = (char *)ctx->argv[0] - 1;
987+
if (*magic_ptr == OPT_MAGIC)
988+
free(magic_ptr);
989+
opt_sz = strlen(ctx->opt - 1) + 1;
990+
magic_ptr = xmalloc(opt_sz + 1);
991+
*magic_ptr = OPT_MAGIC;
992+
ctx->argv[0] = magic_ptr + 1;
993+
memcpy((char *)ctx->argv[0],
994+
ctx->opt - 1, opt_sz);
985995
*(char *)ctx->argv[0] = '-';
986996
goto unknown;
987997
case PARSE_OPT_NON_OPTION:

parse-options.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,8 @@ static inline void die_for_incompatible_opt2(int opt1, const char *opt1_name,
477477
BUG("option callback expects an argument"); \
478478
} while(0)
479479

480+
#define OPT_MAGIC ((char)(0xee))
481+
480482
/*----- incremental advanced APIs -----*/
481483

482484
struct parse_opt_cmdmode_list;

0 commit comments

Comments
 (0)