add a simple leak detector (#255)

Motivation:

Memory leaks are rare in Swift but they can happen. If we run a
realistic workload and the number of `malloc`s and `free`s is very close
to 0, we can be fairly sure we didn't have any (too bad) leaks.
Therefore this adds a simple leaks detector.

Modifications:

Add a leak detector.

Result:

We should now detect leaks even if the total number of allocations
doesn't increase.
This commit is contained in:
Johannes Weiß authored and GitHub committed 2018-03-29 18:43:49 +01:00
1 parent c84b19a399
commit 68db2325df
12 files changed
+216 -67

No files matched your search

+8 -1
View File
@@ -60,11 +60,15 @@ plugins_do init "$@"
shift $plugin_opts_ind
filter="."
while getopts "f:" opt; do
verbose=false
while getopts "f:v" opt; do
case $opt in
f)
filter="$OPTARG"
;;
v)
verbose=true
;;
\?)
usage
exit 1
@@ -93,6 +97,9 @@ for f in tests_*; do
if "$here/run-single-test.sh" "$here/$f/$t" "$test_tmp" "$here/.." >> "$out" 2>&1; then
plugins_do test_ok "$(time_diff_to_now $start)"
suite_ok=$((suite_ok+1))
if $verbose; then
cat "$out"
fi
else
plugins_do test_fail "$(time_diff_to_now $start)" "$out"
suite_fail=$((suite_fail+1))
@@ -32,7 +32,7 @@ function make_git_commit_all() {
git commit -m 'everything'
}
cd HookedFree
cd HookedFunctions
make_git_commit_all
cd ..
@@ -57,18 +57,22 @@ cd ..
"$swift_bin" run -c release > "$tmp/output"
)
for test in 1000_reqs_1_conn; do
allocs=$(grep "$test:" "$tmp/output" | cut -d: -f2 | sed 's/ //g')
for test in 1000_reqs_1_conn 1_reqs_1000_conn; do
cat "$tmp/output" # helps debugging
total_allocations=$(grep "^$test.total_allocations:" "$tmp/output" | cut -d: -f2 | sed 's/ //g')
not_freed_allocations=$(grep "^$test.remaining_allocations:" "$tmp/output" | cut -d: -f2 | sed 's/ //g')
max_allowed_env_name="MAX_ALLOCS_ALLOWED_$test"
assert_greater_than "$allocs" 1000
assert_less_than "$not_freed_allocations" 5 # allow some slack
assert_greater_than "$not_freed_allocations" -5 # allow some slack
assert_greater_than "$total_allocations" 1000
if [[ -z "${!max_allowed_env_name+x}" ]]; then
if [[ -z "${!max_allowed_env_name+x}" ]]; then
warn "no reference number of allocations set (set to \$$max_allowed_env_name)"
warn "to set current number:"
warn " export $max_allowed_env_name=$allocs"
warn " export $max_allowed_env_name=$total_allocations"
fi
else
assert_less_than_or_equal "$allocs" "${!max_allowed_env_name}"
assert_less_than_or_equal "$total_allocations" "${!max_allowed_env_name}"
fi
done
@@ -4,11 +4,11 @@ This briefly describes how the allocation counting test works.
## How does it work?
Basically it's the world's cheapest allocation counter, actually it is a memory `free` counter rather than a `malloc` counter. Why does it count `free` and not `malloc`? Because it's much easier. A correct implementation of `malloc` without relying on the system's `malloc` is non-trivial, an implementation of `free` however is trivial: just do nothing. Sure, you wouldn't want to run a real-world program with a free function that doesn't free the memory as you would run out of memory really quickly. For a short benchmark however it doesn't matter. The only thing that the hooked `free` function does is incrementing an atomic integer variable (representing the number of allocations) than can be read out elsewhere later.
This is possibly the simplest implementation that counts memory allocations (`malloc` and friends) and frees (mostly `free`). It just maintains two atomic variables which count the number of mallocs and the number of frees respectively. We run a simple HTTP1 example -- 1000 requests and responses generated by a simple SwiftNIO based client and server -- and then evaluate the number of mallocs and frees. The difference `mallocs - frees` should be pretty much 0 and the number of `mallocs` should remain stable (or decrease) across commits. We can't establish a perfect baseline as the exact number of allocations depends on your operating system, libc and Swift version.
### How is the free function hooked?
### How are the functions hooked?
Usually in UNIX it's enough to just define a function
Usually in UNIX it's enough to just define a function, for example
```C
void free(void *ptr) { ... }
@@ -18,7 +18,7 @@ in the main binary and all modules will use this `free` function instead of the
- `bootstrap`: The main executable's main module (written in C) so we can hook the `free` function on Linux.
- `BootstrapSwift`: A SwiftPM module (written in Swift) called in from `bootstrap` which implements the actual SwiftNIO benchmark (and therefore depends on the `NIO` module).
- `HookedFree`: A separate SwiftPM package that builds a shared library (`.so` on Linux, `.dylib` on Darwin) which contains the `replacement_free` function which just increments an atomic integer representing the number of allocations. On Darwin, we use `DYLD_INTERPOSE` in this module, interposing libc's `free` with our `replacement_free`. This needs to be a separate SwiftPM package as otherwise its code would just live inside of the `bootstrap` executable and the dyld interposing feature wouldn't work.
- `HookedFunctions`: A separate SwiftPM package that builds a shared library (`.so` on Linux, `.dylib` on Darwin) which contains the `replacement_malloc`, `replacement_free`, etc functions which just increment an atomic integers representing the number of operations. On Darwin, we use `DYLD_INTERPOSE` in this module, interposing libc functions with our `replacement_` functions. This needs to be a separate SwiftPM package as otherwise its code would just live inside of the `bootstrap` executable and the dyld interposing feature wouldn't work.
- `AtomicCounter`: SwiftPM package (written in C) that implements the atomic counters. It needs to be a separate package as both `BoostrapSwift` (to read the allocation counter) as well as `HookedFree` (to increment the allocation counter) depend on it.
## What benchmark is run?
@@ -18,4 +18,8 @@ void inc_free_counter(void);
void reset_free_counter(void);
long read_free_counter(void);
void inc_malloc_counter(void);
void reset_malloc_counter(void);
long read_malloc_counter(void);
#endif
@@ -29,3 +29,4 @@
*/ }
MAKE_COUNTER(free)
MAKE_COUNTER(malloc)
@@ -1,31 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#include <hooked-free.h>
#include <stdlib.h>
#include <atomic-counter.h>
#define DYLD_INTERPOSE(_replacement,_replacee) \
__attribute__((used)) static struct { const void *replacement; const void *replacee; } _interpose_##_replacee \
__attribute__ ((section("__DATA,__interpose"))) = { (const void *)(unsigned long)&_replacement, (const void *)(unsigned long)&_replacee };
void replacement_free(void *ptr) {
if (ptr) {
inc_free_counter();
}
}
#if __APPLE__
DYLD_INTERPOSE(replacement_free, free)
#endif
@@ -17,14 +17,14 @@
import PackageDescription
let package = Package(
name: "HookedFree",
name: "HookedFunctions",
products: [
.library(name: "HookedFree", type: .dynamic, targets: ["HookedFree"]),
.library(name: "HookedFunctions", type: .dynamic, targets: ["HookedFunctions"]),
],
dependencies: [
.package(url: "../AtomicCounter/", .branch("master")),
],
targets: [
.target(name: "HookedFree", dependencies: ["AtomicCounter"]),
.target(name: "HookedFunctions", dependencies: ["AtomicCounter"]),
]
)
@@ -15,6 +15,11 @@
#ifndef HOOKED_FREE
#define HOOKED_FREE
#include <stdlib.h>
void *replacement_malloc(size_t size);
void replacement_free(void *ptr);
void *replacement_calloc(size_t nmemb, size_t size);
void *replacement_realloc(void *ptr, size_t size);
#endif
@@ -0,0 +1,125 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#define _GNU_SOURCE
#include <atomic-counter.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <hooked-functions.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define DYLD_INTERPOSE(_replacement,_replacee) \
__attribute__((used)) static struct { const void *replacement; const void *replacee; } _interpose_##_replacee \
__attribute__ ((section("__DATA,__interpose"))) = { (const void *)(unsigned long)&_replacement, (const void *)(unsigned long)&_replacee };
#define LIBC_SYMBOL(_fun) "" # _fun
void replacement_free(void *ptr) {
if (ptr) {
inc_free_counter();
}
}
__thread bool g_in_malloc = false;
__thread bool g_in_realloc = false;
__thread void *(*g_libc_malloc)(size_t) = NULL;
__thread void *(*g_libc_realloc)(void *, size_t) = NULL;
// this is called if malloc is called whilst trying to resolve libc's realloc.
static void *recursive_malloc(size_t size) {
/* a very cheap (as in bad) and inefficient malloc implementation that we just use
if malloc calls itself. */
int fd = open("/dev/zero", O_RDWR);
void *ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
close(fd);
return ptr;
}
// this is called if realloc is called whilst trying to resolve libc's realloc.
static void *recursive_realloc(void *ptr, size_t size) {
// not implemented yet...
abort();
}
#if __APPLE__
/* on Darwin calling the original function is super easy, just call it, done. */
#define JUMP_INTO_LIBC_FUN(_fun, ...) /* \
*/ do { /* \
*/ return _fun(__VA_ARGS__); /* \
*/ } while(0)
#else
/* on other UNIX systems this is slightly harder. Basically we see if we already
* have a thread local variable that is a pointer to the original libc function.
* If yes, easy, call it. If no, we need to resolve it which we do by using
* dlsym. There's only one slight problem: dlsym might call back into the
* function we're just trying to resolve (it does call malloc). In that case
* we need to emulate that function (named recursive_*). But that's all then.
*/
#define JUMP_INTO_LIBC_FUN(_fun, ...) /* \
*/ do { /* \
*/ if (!g_libc_ ## _fun) { /* \
*/ if (!g_in_ ## _fun) { /* \
*/ g_in_ ## _fun = true; /* \
*/ g_libc_ ## _fun = dlsym(RTLD_NEXT, LIBC_SYMBOL(_fun)); /* \
*/ } else { /* \
*/ return recursive_ ## _fun (__VA_ARGS__); /* \
*/ } /* \
*/ } /*
*/ g_in_ ## _fun = false; /* \
*/ return g_libc_ ## _fun (__VA_ARGS__); /*
*/ } while(0)
#endif
void *replacement_malloc(size_t size) {
inc_malloc_counter();
JUMP_INTO_LIBC_FUN(malloc, size);
}
void *replacement_realloc(void *ptr, size_t size) {
if (0 == size) {
replacement_free(ptr);
return NULL;
}
if (!ptr) {
return replacement_malloc(size);
}
inc_free_counter();
inc_malloc_counter();
JUMP_INTO_LIBC_FUN(realloc, ptr, size);
}
void *replacement_calloc(size_t count, size_t size) {
void *ptr = replacement_malloc(count * size);
memset(ptr, 0, count * size);
return ptr;
}
#if __APPLE__
DYLD_INTERPOSE(replacement_free, free)
DYLD_INTERPOSE(replacement_malloc, malloc)
DYLD_INTERPOSE(replacement_realloc, realloc)
DYLD_INTERPOSE(replacement_calloc, calloc)
#endif
@@ -6,7 +6,7 @@ import PackageDescription
let package = Package(
name: "swift-malloc-info",
dependencies: [
.package(url: "HookedFree/", .branch("master")),
.package(url: "HookedFunctions/", .branch("master")),
.package(url: "swift-nio/", .branch("master")),
],
targets: [
@@ -15,6 +15,6 @@ let package = Package(
dependencies: ["NIO", "NIOHTTP1"]),
.target(
name: "bootstrap",
dependencies: ["SwiftBootstrap", "HookedFree"]),
dependencies: ["SwiftBootstrap", "HookedFunctions"]),
]
)
@@ -96,35 +96,38 @@ public func swiftMain() -> Int {
}
}
func measure(_ fn: () -> Int) -> [Int] {
func measureOne(_ fn: () -> Int) -> Int {
func measure(_ fn: () -> Int) -> [[String: Int]] {
func measureOne(_ fn: () -> Int) -> [String: Int] {
AtomicCounter.reset_free_counter()
_ = fn()
return AtomicCounter.read_free_counter()
AtomicCounter.reset_malloc_counter()
//autoreleasepool {
_ = fn()
//}
let frees = AtomicCounter.read_free_counter()
let mallocs = AtomicCounter.read_malloc_counter()
return ["total_allocations": mallocs,
"remaining_allocations": mallocs - frees]
}
_ = measureOne(fn) /* pre-heat and throw away */
var measurements: [Int] = []
var measurements: [[String: Int]] = []
for _ in 0..<10 {
measurements.append(measureOne(fn))
}
return measurements
}
func measureAndPrint(desc: String, fn: () -> Int) -> Void {
print("\(desc): ", terminator: "")
let measurements = measure(fn)
print(measurements.min() ?? -1)
for k in measurements[0].keys {
let vs = measurements.map { $0[k]! }
print("\(desc).\(k): \(vs.min() ?? -1)")
}
print("DEBUG: \(measurements)")
}
measureAndPrint(desc: "1000_reqs_1_conn") {
let group = MultiThreadedEventLoopGroup(numThreads: System.coreCount)
defer {
try! group.syncShutdownGracefully()
}
let serverChannel = try! ServerBootstrap(group: group)
func doRequests(group: EventLoopGroup, number numberOfRequests: Int) throws -> Int {
let serverChannel = try ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true).then {
@@ -137,9 +140,9 @@ public func swiftMain() -> Int {
}
let repeatedRequestsHandler = RepeatedRequests(numberOfRequests: 1000, eventLoop: group.next())
let repeatedRequestsHandler = RepeatedRequests(numberOfRequests: numberOfRequests, eventLoop: group.next())
let clientChannel = try! ClientBootstrap(group: group)
let clientChannel = try ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.addHTTPClientHandlers().then {
channel.pipeline.add(handler: repeatedRequestsHandler)
@@ -149,8 +152,29 @@ public func swiftMain() -> Int {
.wait()
clientChannel.write(NIOAny(HTTPClientRequestPart.head(RepeatedRequests.requestHead)), promise: nil)
try! clientChannel.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil))).wait()
return try! repeatedRequestsHandler.wait()
try clientChannel.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil))).wait()
return try repeatedRequestsHandler.wait()
}
let group = MultiThreadedEventLoopGroup(numThreads: System.coreCount)
defer {
try! group.syncShutdownGracefully()
}
measureAndPrint(desc: "1000_reqs_1_conn") {
let numberDone = try! doRequests(group: group, number: 1000)
precondition(numberDone == 1000)
return numberDone
}
measureAndPrint(desc: "1_reqs_1000_conn") {
var numberDone = 1
for _ in 0..<1000 {
let newDones = try! doRequests(group: group, number: 1)
precondition(newDones == 1)
numberDone += newDones
}
return numberDone
}
return 0
@@ -16,12 +16,22 @@
#include <stdio.h>
#include <dlfcn.h>
#include <atomic-counter.h>
#include <hooked-free.h>
#include <hooked-functions.h>
#include <stdlib.h>
#if !__APPLE__
void free(void *ptr) {
replacement_free(ptr);
}
void *malloc(size_t size) {
return replacement_malloc(size);
}
void *calloc(size_t nmemb, size_t size) {
return replacement_calloc(nmemb, size);
}
void *realloc(void *ptr, size_t size) {
return replacement_realloc(ptr, size);
}
#endif
void swift_main(void);