From e761c2d4de27f9beac97fd563bebc09b94b91a71 Mon Sep 17 00:00:00 2001 From: Frediano Ziglio Date: Sun, 15 Dec 2019 15:09:24 +0000 Subject: [PATCH] log: Add spice_extra_assert This macro was suggested to simplify hot path expensive checks which should be disable in production environments. Signed-off-by: Frediano Ziglio Acked-by: Francesco Giudici --- common/log.h | 6 ++++++ tests/test-logging.c | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/common/log.h b/common/log.h index 201c87a..f38e80e 100644 --- a/common/log.h +++ b/common/log.h @@ -99,6 +99,12 @@ enum { spice_extra_checks = 1 }; enum { spice_extra_checks = 0 }; #endif +#define spice_extra_assert(x) G_STMT_START { \ + if (!spice_extra_checks || G_LIKELY(x)) { } else { \ + spice_error("assertion `%s' failed", #x); \ + } \ +} G_STMT_END + SPICE_END_DECLS #endif // H_SPICE_COMMON_LOG diff --git a/tests/test-logging.c b/tests/test-logging.c index 22afe1f..d151990 100644 --- a/tests/test-logging.c +++ b/tests/test-logging.c @@ -267,6 +267,30 @@ static void test_spice_g_messages_debug_all(void) g_test_trap_assert_stderr("*g_message\n*other_message\n"); } +/* Checks that spice_assert() aborts if condition fails */ +static void test_spice_assert(void) +{ + if (g_test_subprocess()) { + spice_assert(1 == 2); + return; + } + g_test_trap_subprocess(NULL, 0, 0); + g_test_trap_assert_failed(); + g_test_trap_assert_stderr("*assertion `1 == 2' failed*"); +} + +/* Checks that spice_extra_assert() aborts if condition fails */ +static void test_spice_extra_assert(void) +{ + if (g_test_subprocess()) { + spice_extra_assert(1 == 2); + return; + } + g_test_trap_subprocess(NULL, 0, 0); + g_test_trap_assert_failed(); + g_test_trap_assert_stderr("*assertion `1 == 2' failed*"); +} + static void handle_sigabrt(int sig G_GNUC_UNUSED) { _Exit(1); @@ -298,6 +322,10 @@ int main(int argc, char **argv) g_test_add_func("/spice-common/spice-fatal-return-if-fail", test_spice_fatal_return_if_fail); g_test_add_func("/spice-common/spice-non-fatal-greturn-if-fail", test_spice_non_fatal_g_return_if_fail); g_test_add_func("/spice-common/spice-fatal-warning", test_spice_fatal_warning); + g_test_add_func("/spice-common/spice-assert", test_spice_assert); + if (spice_extra_checks) { + g_test_add_func("/spice-common/spice-extra-assert", test_spice_extra_assert); + } return g_test_run(); }