add UNLEAK annotation for reducing leak false positives

It's a common pattern in git commands to allocate some memory that should last for the lifetime of the program and then not bother to free it, relying on the OS to throw it away. This keeps the code simple, and it's fast (we don't waste time traversing structures or calling free at the end of the program). But it also triggers warnings from memory-leak checkers like valgrind or LSAN. They know that the memory was still allocated at program exit, but they don't know _when_ the leaked memory stopped being useful. If it was early in the program, then it's probably a real and important leak. But if it was used right up until program exit, it's not an interesting leak and we'd like to suppress it so that we can see the real leaks. This patch introduces an UNLEAK() macro that lets us do so. To understand its design, let's first look at some of the alternatives. Unfortunately the suppression systems offered by leak-checking tools don't quite do what we want. A leak-checker basically knows two things: 1. Which blocks were allocated via malloc, and the callstack during the allocation. 2. Which blocks were left un-freed at the end of the program (and which are unreachable, but more on that later). Their suppressions work by mentioning the function or callstack of a particular allocation, and marking it as OK to leak. So imagine you have code like this: int cmd_foo(...) { /* this allocates some memory */ char *p = some_function(); printf("%s", p); return 0; } You can say "ignore allocations from some_function(), they're not leaks". But that's not right. That function may be called elsewhere, too, and we would potentially want to know about those leaks. So you can say "ignore the callstack when main calls some_function". That works, but your annotations are brittle. In this case it's only two functions, but you can imagine that the actual allocation is much deeper. If any of the intermediate code changes, you have to update the suppression. What we _really_ want to say is that "the value assigned to p at the end of the function is not a real leak". But leak-checkers can't understand that; they don't know about "p" in the first place. However, we can do something a little bit tricky if we make some assumptions about how leak-checkers work. They generally don't just report all un-freed blocks. That would report even globals which are still accessible when the leak-check is run. Instead they take some set of memory (like BSS) as a root and mark it as "reachable". Then they scan the reachable blocks for anything that looks like a pointer to a malloc'd block, and consider that block reachable. And then they scan those blocks, and so on, transitively marking anything reachable from a global as "not leaked" (or at least leaked in a different category). So we can mark the value of "p" as reachable by putting it into a variable with program lifetime. One way to do that is to just mark "p" as static. But that actually affects the run-time behavior if the function is called twice (you aren't likely to call main() twice, but some of our cmd_*() functions are called from other commands). Instead, we can trick the leak-checker by putting the value into _any_ reachable bytes. This patch keeps a global linked-list of bytes copied from "unleaked" variables. That list is reachable even at program exit, which confers recursive reachability on whatever values we unleak. In other words, you can do: int cmd_foo(...) { char *p = some_function(); printf("%s", p); UNLEAK(p); return 0; } to annotate "p" and suppress the leak report. But wait, couldn't we just say "free(p)"? In this toy example, yes. But UNLEAK()'s byte-copying strategy has several advantages over actually freeing the memory: 1. It's recursive across structures. In many cases our "p" is not just a pointer, but a complex struct whose fields may have been allocated by a sub-function. And in some cases (e.g., dir_struct) we don't even have a function which knows how to free all of the struct members. By marking the struct itself as reachable, that confers reachability on any pointers it contains (including those found in embedded structs, or reachable by walking heap blocks recursively. 2. It works on cases where we're not sure if the value is allocated or not. For example: char *p = argc > 1 ? argv[1] : some_function(); It's safe to use UNLEAK(p) here, because it's not freeing any memory. In the case that we're pointing to argv here, the reachability checker will just ignore our bytes. 3. Likewise, it works even if the variable has _already_ been freed. We're just copying the pointer bytes. If the block has been freed, the leak-checker will skip over those bytes as uninteresting. 4. Because it's not actually freeing memory, you can UNLEAK() before we are finished accessing the variable. This is helpful in cases like this: char *p = some_function(); return another_function(p); Writing this with free() requires: int ret; char *p = some_function(); ret = another_function(p); free(p); return ret; But with unleak we can just write: char *p = some_function(); UNLEAK(p); return another_function(p); This patch adds the UNLEAK() macro and enables it automatically when Git is compiled with SANITIZE=leak. In normal builds it's a noop, so we pay no runtime cost. It also adds some UNLEAK() annotations to show off how the feature works. On top of other recent leak fixes, these are enough to get t0000 and t0001 to pass when compiled with LSAN. Note the case in commit.c which actually converts a strbuf_release() into an UNLEAK. This code was already non-leaky, but the free didn't do anything useful, since we're exiting. Converting it to an annotation means that non-leak-checking builds pay no runtime cost. The cost is minimal enough that it's probably not worth going on a crusade to convert these kinds of frees to UNLEAKS. I did it here for consistency with the "sb" leak (though it would have been equally correct to go the other way, and turn them both into strbuf_release() calls). Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Sep 8, 2017 at 02:38 UTC 0e5bba53af7d6f911e99589d736cdf06badad0fe
9 files changed +51 -1
Makefile
+3
@@ -1036,6 +1036,9 @@ BASIC_CFLAGS += -fno-omit-frame-pointer
1036 ifneq ($(filter undefined,$(SANITIZERS)),)
1037 BASIC_CFLAGS += -DNO_UNALIGNED_LOADS
1038 endif
1039 +ifneq ($(filter leak,$(SANITIZERS)),)
1040 +BASIC_CFLAGS += -DSUPPRESS_ANNOTATED_LEAKS
1041 +endif
1042 endif
1043
1044 ifndef sysconfdir
builtin/add.c
+2
@@ -515,5 +515,7 @@ finish:
515 die(_("Unable to write new index file"));
516 }
517
518 + UNLEAK(pathspec);
519 + UNLEAK(dir);
520 return exit_status;
521 }
builtin/commit.c
+2 -1
@@ -1818,6 +1818,7 @@ int cmd_commit(int argc, const char **argv, const char *prefix)
1818 if (!quiet)
1819 print_summary(prefix, &oid, !current_head);
1820
1821 - strbuf_release(&err);
1821 + UNLEAK(err);
1822 + UNLEAK(sb);
1823 return 0;
1824 }
builtin/config.c
+4
@@ -631,6 +631,7 @@ int cmd_config(int argc, const char **argv, const char *prefix)
631 check_write();
632 check_argc(argc, 2, 2);
633 value = normalize_value(argv[0], argv[1]);
634 + UNLEAK(value);
635 ret = git_config_set_in_file_gently(given_config_source.file, argv[0], value);
636 if (ret == CONFIG_NOTHING_SET)
637 error(_("cannot overwrite multiple values with a single value\n"
@@ -641,6 +642,7 @@ int cmd_config(int argc, const char **argv, const char *prefix)
642 check_write();
643 check_argc(argc, 2, 3);
644 value = normalize_value(argv[0], argv[1]);
645 + UNLEAK(value);
646 return git_config_set_multivar_in_file_gently(given_config_source.file,
647 argv[0], value, argv[2], 0);
648 }
@@ -648,6 +650,7 @@ int cmd_config(int argc, const char **argv, const char *prefix)
650 check_write();
651 check_argc(argc, 2, 2);
652 value = normalize_value(argv[0], argv[1]);
653 + UNLEAK(value);
654 return git_config_set_multivar_in_file_gently(given_config_source.file,
655 argv[0], value,
656 CONFIG_REGEX_NONE, 0);
@@ -656,6 +659,7 @@ int cmd_config(int argc, const char **argv, const char *prefix)
659 check_write();
660 check_argc(argc, 2, 3);
661 value = normalize_value(argv[0], argv[1]);
662 + UNLEAK(value);
663 return git_config_set_multivar_in_file_gently(given_config_source.file,
664 argv[0], value, argv[2], 1);
665 }
builtin/init-db.c
+2
@@ -579,6 +579,8 @@ int cmd_init_db(int argc, const char **argv, const char *prefix)
579 set_git_work_tree(work_tree);
580 }
581
582 + UNLEAK(real_git_dir);
583 +
584 flags |= INIT_DB_EXIST_OK;
585 return init_db(git_dir, real_git_dir, template_dir, flags);
586 }
builtin/ls-files.c
+1
@@ -673,5 +673,6 @@ int cmd_ls_files(int argc, const char **argv, const char *cmd_prefix)
673 return bad ? 1 : 0;
674 }
675
676 + UNLEAK(dir);
677 return 0;
678 }
builtin/worktree.c
+2
@@ -381,6 +381,8 @@ static int add(int ac, const char **av, const char *prefix)
381 branch = opts.new_branch;
382 }
383
384 + UNLEAK(path);
385 + UNLEAK(opts);
386 return add_worktree(path, branch, &opts);
387 }
388
git-compat-util.h
+20
@@ -1169,4 +1169,24 @@ static inline int is_missing_file_error(int errno_)
1169
1170 extern int cmd_main(int, const char **);
1171
1172 +/*
1173 + * You can mark a stack variable with UNLEAK(var) to avoid it being
1174 + * reported as a leak by tools like LSAN or valgrind. The argument
1175 + * should generally be the variable itself (not its address and not what
1176 + * it points to). It's safe to use this on pointers which may already
1177 + * have been freed, or on pointers which may still be in use.
1178 + *
1179 + * Use this _only_ for a variable that leaks by going out of scope at
1180 + * program exit (so only from cmd_* functions or their direct helpers).
1181 + * Normal functions, especially those which may be called multiple
1182 + * times, should actually free their memory. This is only meant as
1183 + * an annotation, and does nothing in non-leak-checking builds.
1184 + */
1185 +#ifdef SUPPRESS_ANNOTATED_LEAKS
1186 +extern void unleak_memory(const void *ptr, size_t len);
1187 +#define UNLEAK(var) unleak_memory(&(var), sizeof(var));
1188 +#else
1189 +#define UNLEAK(var)
1190 +#endif
1191 +
1192 #endif
usage.c
+15
@@ -241,3 +241,18 @@ NORETURN void BUG(const char *fmt, ...)
241 va_end(ap);
242 }
243 #endif
244 +
245 +#ifdef SUPPRESS_ANNOTATED_LEAKS
246 +void unleak_memory(const void *ptr, size_t len)
247 +{
248 + static struct suppressed_leak_root {
249 + struct suppressed_leak_root *next;
250 + char data[FLEX_ARRAY];
251 + } *suppressed_leaks;
252 + struct suppressed_leak_root *root;
253 +
254 + FLEX_ALLOC_MEM(root, data, ptr, len);
255 + root->next = suppressed_leaks;
256 + suppressed_leaks = root;
257 +}
258 +#endif