[lsan] Add leak_check_at_exit flag.

We needed a way to tell LSan to invoke leak checking only if __do_leak_check()
is called explicitly. This can now be achieved by setting
leak_check_at_exit=false.

git-svn-id: https://llvm.org/svn/llvm-project/compiler-rt/trunk@187578 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/lsan/lit_tests/TestCases/leak_check_at_exit.cc b/lib/lsan/lit_tests/TestCases/leak_check_at_exit.cc
new file mode 100644
index 0000000..441012a
--- /dev/null
+++ b/lib/lsan/lit_tests/TestCases/leak_check_at_exit.cc
@@ -0,0 +1,19 @@
+// Test for the leak_check_at_exit flag.
+// RUN: %clangxx_lsan %s -o %t
+// RUN: LSAN_OPTIONS="verbosity=1" %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
+// RUN: LSAN_OPTIONS="verbosity=1" %t 2>&1 | FileCheck %s --check-prefix=CHECK-do
+// RUN: LSAN_OPTIONS="verbosity=1:leak_check_at_exit=0" ASAN_OPTIONS="$ASAN_OPTIONS:leak_check_at_exit=0" %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
+// RUN: LSAN_OPTIONS="verbosity=1:leak_check_at_exit=0" ASAN_OPTIONS="$ASAN_OPTIONS:leak_check_at_exit=0" %t 2>&1 | FileCheck %s --check-prefix=CHECK-dont
+
+#include <stdio.h>
+#include <sanitizer/lsan_interface.h>
+
+int main(int argc, char *argv[]) {
+  printf("printf to break optimization\n");
+  if (argc > 1)
+    __lsan_do_leak_check();
+  return 0;
+}
+
+// CHECK-do: SUMMARY: LeakSanitizer:
+// CHECK-dont-NOT: SUMMARY: LeakSanitizer:
diff --git a/lib/lsan/lsan.cc b/lib/lsan/lsan.cc
index 79e593f..22e18e2 100644
--- a/lib/lsan/lsan.cc
+++ b/lib/lsan/lsan.cc
@@ -31,6 +31,7 @@
   cf->fast_unwind_on_malloc = true;
   cf->malloc_context_size = 30;
   cf->detect_leaks = true;
+  cf->leak_check_at_exit = true;
 
   ParseCommonFlagsFromString(GetEnv("LSAN_OPTIONS"));
 }
@@ -59,7 +60,8 @@
   }
 
   InitCommonLsan();
-  Atexit(DoLeakCheck);
+  if (common_flags()->detect_leaks && common_flags()->leak_check_at_exit)
+    Atexit(DoLeakCheck);
 }
 
 }  // namespace __lsan