From 682f89d5bc1fbc28260ccf98f4ebc7798a5cd46c Mon Sep 17 00:00:00 2001 From: Michel Hermier Date: Tue, 14 Dec 2021 17:44:43 +0100 Subject: [PATCH] LibC: Allow multiple includes of `` ISO C requires in section 7.2: The assert macro is redefined according to the current state of NDEBUG each time that is included. Also add tests for `assert` multiple inclusion accordingly. --- Meta/check-style.py | 1 + Tests/LibC/TestAssert.cpp | 23 +++++++++++++++++++++++ Userland/Libraries/LibC/assert.h | 19 ++++++++++++------- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/Meta/check-style.py b/Meta/check-style.py index 24ea096b947..5e70d79ef9a 100755 --- a/Meta/check-style.py +++ b/Meta/check-style.py @@ -31,6 +31,7 @@ LICENSE_HEADER_CHECK_EXCLUDES = { # We check that "#pragma once" is present PRAGMA_ONCE_STRING = '#pragma once' PRAGMA_ONCE_CHECK_EXCLUDES = { + 'Userland/Libraries/LibC/assert.h', } # We make sure that there's a blank line before and after pragma once diff --git a/Tests/LibC/TestAssert.cpp b/Tests/LibC/TestAssert.cpp index 08eae12c236..2e7b5fb7067 100644 --- a/Tests/LibC/TestAssert.cpp +++ b/Tests/LibC/TestAssert.cpp @@ -6,6 +6,7 @@ #include +#undef NDEBUG #include #include @@ -20,3 +21,25 @@ TEST_CASE(assert) return Test::Crash::Failure::DidNotCrash; }); } + +#define NDEBUG +#include + +TEST_CASE(assert_reinclude) +{ + EXPECT_NO_CRASH("This should not assert", [] { + assert(!"This should not assert"); + return Test::Crash::Failure::DidNotCrash; + }); +} + +#undef NDEBUG +#include + +TEST_CASE(assert_rereinclude) +{ + EXPECT_CRASH("This should assert", [] { + assert(!"This should assert"); + return Test::Crash::Failure::DidNotCrash; + }); +} diff --git a/Userland/Libraries/LibC/assert.h b/Userland/Libraries/LibC/assert.h index 86c042281c7..c64b51ecd03 100644 --- a/Userland/Libraries/LibC/assert.h +++ b/Userland/Libraries/LibC/assert.h @@ -4,16 +4,25 @@ * SPDX-License-Identifier: BSD-2-Clause */ -#pragma once +#ifndef _ASSERT_H +# define _ASSERT_H + +# define __stringify_helper(x) # x +# define __stringify(x) __stringify_helper(x) + +# ifndef __cplusplus +# define static_assert _Static_assert +# endif +#endif #include +#undef assert + __BEGIN_DECLS #ifndef NDEBUG __attribute__((noreturn)) void __assertion_failed(const char* msg); -# define __stringify_helper(x) # x -# define __stringify(x) __stringify_helper(x) # define assert(expr) \ (__builtin_expect(!(expr), 0) \ ? __assertion_failed(#expr "\n" __FILE__ ":" __stringify(__LINE__)) \ @@ -23,8 +32,4 @@ __attribute__((noreturn)) void __assertion_failed(const char* msg); # define assert(expr) ((void)(0)) #endif -#ifndef __cplusplus -# define static_assert _Static_assert -#endif - __END_DECLS