diff --git a/IntegrationTests/run-tests.sh b/IntegrationTests/run-tests.sh index 53f56a4f5..acf9e1732 100755 --- a/IntegrationTests/run-tests.sh +++ b/IntegrationTests/run-tests.sh @@ -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)) diff --git a/IntegrationTests/tests_04_performance/test_01_allocation_counts_for_http1.sh b/IntegrationTests/tests_04_performance/test_01_allocation_counts_for_http1.sh index 71a90137a..c9e59c0d4 100644 --- a/IntegrationTests/tests_04_performance/test_01_allocation_counts_for_http1.sh +++ b/IntegrationTests/tests_04_performance/test_01_allocation_counts_for_http1.sh @@ -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 diff --git a/IntegrationTests/tests_04_performance/test_01_resources/README.md b/IntegrationTests/tests_04_performance/test_01_resources/README.md index 4607f13fc..e172a4fb7 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/README.md +++ b/IntegrationTests/tests_04_performance/test_01_resources/README.md @@ -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? diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/AtomicCounter/Sources/AtomicCounter/include/atomic-counter.h b/IntegrationTests/tests_04_performance/test_01_resources/template/AtomicCounter/Sources/AtomicCounter/include/atomic-counter.h index 4c24bfa7e..2ca4f17b5 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/AtomicCounter/Sources/AtomicCounter/include/atomic-counter.h +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/AtomicCounter/Sources/AtomicCounter/include/atomic-counter.h @@ -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 diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/AtomicCounter/Sources/AtomicCounter/src/atomic-counter.c b/IntegrationTests/tests_04_performance/test_01_resources/template/AtomicCounter/Sources/AtomicCounter/src/atomic-counter.c index b45831e9c..98f6e7fd0 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/AtomicCounter/Sources/AtomicCounter/src/atomic-counter.c +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/AtomicCounter/Sources/AtomicCounter/src/atomic-counter.c @@ -29,3 +29,4 @@ */ } MAKE_COUNTER(free) +MAKE_COUNTER(malloc) diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Sources/HookedFree/src/hooked-free.c b/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Sources/HookedFree/src/hooked-free.c deleted file mode 100644 index 4fb498772..000000000 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Sources/HookedFree/src/hooked-free.c +++ /dev/null @@ -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 -#include -#include - -#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 diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Package.swift b/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Package.swift similarity index 80% rename from IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Package.swift rename to IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Package.swift index bdcc9bf2d..cbfe2af04 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Package.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Package.swift @@ -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"]), ] ) diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Sources/HookedFree/include/hooked-free.h b/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Sources/HookedFunctions/include/hooked-functions.h similarity index 77% rename from IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Sources/HookedFree/include/hooked-free.h rename to IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Sources/HookedFunctions/include/hooked-functions.h index 8837d61cd..4f74479a8 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFree/Sources/HookedFree/include/hooked-free.h +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Sources/HookedFunctions/include/hooked-functions.h @@ -15,6 +15,11 @@ #ifndef HOOKED_FREE #define HOOKED_FREE +#include + +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 diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Sources/HookedFunctions/src/hooked-functions.c b/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Sources/HookedFunctions/src/hooked-functions.c new file mode 100644 index 000000000..40558e3d1 --- /dev/null +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/HookedFunctions/Sources/HookedFunctions/src/hooked-functions.c @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/Package.swift b/IntegrationTests/tests_04_performance/test_01_resources/template/Package.swift index 0e275fbb6..94b3f4c78 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/Package.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/Package.swift @@ -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"]), ] ) diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/SwiftBootstrap/SwiftMain.swift b/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/SwiftBootstrap/SwiftMain.swift index 033c0bca9..ef241450b 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/SwiftBootstrap/SwiftMain.swift +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/SwiftBootstrap/SwiftMain.swift @@ -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 diff --git a/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/bootstrap/main.c b/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/bootstrap/main.c index 8f614fae1..d4de9cc82 100644 --- a/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/bootstrap/main.c +++ b/IntegrationTests/tests_04_performance/test_01_resources/template/Sources/bootstrap/main.c @@ -16,12 +16,22 @@ #include #include #include -#include +#include +#include #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);