Implement assert(3) properly.

This commit is contained in:
Jonas 'Sortie' Termansen 2012-09-06 21:36:55 +02:00
parent 13c0ab638a
commit 34970e63f3
3 changed files with 68 additions and 10 deletions

View File

@ -67,6 +67,7 @@ string.o \
error.o \
format.o \
access.o \
_assert.o \
chdir.o \
chmod.o \
close.o \

35
libmaxsi/_assert.cpp Normal file
View File

@ -0,0 +1,35 @@
/******************************************************************************
Copyright(C) Jonas 'Sortie' Termansen 2012.
This file is part of LibMaxsi.
LibMaxsi is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
LibMaxsi is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with LibMaxsi. If not, see <http://www.gnu.org/licenses/>.
_assert.cpp
Reports the occurence of an assertion failure.
******************************************************************************/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void _assert(const char* filename, unsigned int line, const char* functionname,
const char* expression)
{
fprintf(stderr, "Assertion failure: %s:%u: %s: %s\n", filename, line,
functionname, expression);
abort();
}

View File

@ -1,6 +1,6 @@
/******************************************************************************
COPYRIGHT(C) JONAS 'SORTIE' TERMANSEN 2012.
Copyright(C) Jonas 'Sortie' Termansen 2012.
This file is part of LibMaxsi.
@ -27,18 +27,40 @@
#include <features.h>
/* stdlib.h is not needed, but GCC fixincludes thinks it is, so fool it. */
#if 0
#include <stdlib.h>
#endif
__BEGIN_DECLS
#ifdef assert
#undef assert
#endif
#ifndef NDEBUG
/* #warning The assert macro is not implemented */
#endif
#define assert(ignore)((void) 0)
/* The actual implementation of assert. */
void _assert(const char* filename, unsigned int line, const char* functionname,
const char* expression) __attribute__ ((noreturn));
__END_DECLS
#endif
/* Rid ourselves of any previous declaration of assert. */
#ifdef assert
#undef assert
#endif
/* Redefine the assert macro on each <assert.h> inclusion. */
#ifdef NDEBUG
#define assert(ignore) ((void) 0)
#else /* !NDEBUG */
/* Use __builtin_expect to tell the compiler that we don't expect a failure to
happen and thus it can do better branch prediction. Naturally we don't
optimize for the case where the program is about to abort(). */
#define assert(invariant) \
if ( __builtin_expect(!(invariant), 0) ) \
{ \
_assert(__FILE__, __LINE__, __PRETTY_FUNCTION__, #invariant); \
}
#endif /* !NDEBUG */