Skip to content

Commit 97ed50f

Browse files
committed
git-config: fix regexp memory leaks on error conditions
The get_value function has a goto label for cleaning up on errors, but it only cleans up half of what the function might allocate. Let's also clean up the key and regexp variables there. Note that we need to take special care when compiling the regex fails to clean it up ourselves, since it is in a half-constructed state (we would want to free it, but not regfree it). Similarly, we fix git_config_parse_key to return NULL when it fails, not a pointer to some already-freed memory. Signed-off-by: Jeff King <[email protected]>
1 parent 35998c8 commit 97ed50f

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

builtin/config.c

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,8 @@ static int get_value(const char *key_, const char *regex_)
195195
key_regexp = (regex_t*)xmalloc(sizeof(regex_t));
196196
if (regcomp(key_regexp, key, REG_EXTENDED)) {
197197
fprintf(stderr, "Invalid key pattern: %s\n", key_);
198-
free(key);
198+
free(key_regexp);
199+
key_regexp = NULL;
199200
ret = CONFIG_INVALID_PATTERN;
200201
goto free_strings;
201202
}
@@ -215,6 +216,8 @@ static int get_value(const char *key_, const char *regex_)
215216
regexp = (regex_t*)xmalloc(sizeof(regex_t));
216217
if (regcomp(regexp, regex_, REG_EXTENDED)) {
217218
fprintf(stderr, "Invalid pattern: %s\n", regex_);
219+
free(regexp);
220+
regexp = NULL;
218221
ret = CONFIG_INVALID_PATTERN;
219222
goto free_strings;
220223
}
@@ -247,6 +250,15 @@ static int get_value(const char *key_, const char *regex_)
247250
if (!do_all && !seen && system_wide)
248251
git_config_from_file(fn, system_wide, data);
249252

253+
if (do_all)
254+
ret = !seen;
255+
else
256+
ret = (seen == 1) ? 0 : seen > 1 ? 2 : 1;
257+
258+
free_strings:
259+
free(repo_config);
260+
free(global);
261+
free(xdg);
250262
free(key);
251263
if (key_regexp) {
252264
regfree(key_regexp);
@@ -257,15 +269,6 @@ static int get_value(const char *key_, const char *regex_)
257269
free(regexp);
258270
}
259271

260-
if (do_all)
261-
ret = !seen;
262-
else
263-
ret = (seen == 1) ? 0 : seen > 1 ? 2 : 1;
264-
265-
free_strings:
266-
free(repo_config);
267-
free(global);
268-
free(xdg);
269272
return ret;
270273
}
271274

config.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1280,6 +1280,7 @@ int git_config_parse_key(const char *key, char **store_key, int *baselen_)
12801280

12811281
out_free_ret_1:
12821282
free(*store_key);
1283+
*store_key = NULL;
12831284
return -CONFIG_INVALID_KEY;
12841285
}
12851286

0 commit comments

Comments
 (0)