1//===-- Definition of a libc internal assert macro --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_LIBC_SRC___SUPPORT_LIBC_ASSERT_H
10#define LLVM_LIBC_SRC___SUPPORT_LIBC_ASSERT_H
11
12#if defined(LIBC_COPT_USE_C_ASSERT) || !defined(LIBC_FULL_BUILD)
13
14// The build is configured to just use the public <assert.h> API
15// for libc's internal assertions.
16
17#ifndef LIBC_ASSERT
18#include <assert.h>
19
20#define LIBC_ASSERT(COND) assert(COND)
21#endif // LIBC_ASSERT
22
23#else // Not LIBC_COPT_USE_C_ASSERT
24
25#include "src/__support/OSUtil/exit.h"
26#include "src/__support/OSUtil/io.h"
27#include "src/__support/integer_to_string.h"
28#include "src/__support/macros/attributes.h" // For LIBC_INLINE
29#include "src/__support/macros/config.h"
30#include "src/__support/macros/macro-utils.h"
31#include "src/__support/macros/optimization.h" // For LIBC_UNLIKELY
32
33namespace LIBC_NAMESPACE_DECL {
34
35// This is intended to be removed in a future patch to use a similar design to
36// below, but it's necessary for the external assert.
37LIBC_INLINE void report_assertion_failure(const char *assertion,
38 const char *filename, unsigned line,
39 const char *funcname) {
40 const IntegerToString<unsigned> line_buffer(line);
41 write_to_stderr(filename);
42 write_to_stderr(":");
43 write_to_stderr(line_buffer.view());
44 write_to_stderr(": Assertion failed: '");
45 write_to_stderr(assertion);
46 write_to_stderr("' in function: '");
47 write_to_stderr(funcname);
48 write_to_stderr("'\n");
49}
50
51} // namespace LIBC_NAMESPACE_DECL
52
53#ifdef LIBC_ASSERT
54#error "Unexpected: LIBC_ASSERT macro already defined"
55#endif
56
57// The public "assert" macro calls abort on failure. Should it be same here?
58// The libc internal assert can fire from anywhere inside the libc. So, to
59// avoid potential chicken-and-egg problems, it is simple to do an exit
60// on assertion failure instead of calling abort. We also don't want to use
61// __builtin_trap as it could potentially be implemented using illegal
62// instructions which can be very misleading when debugging.
63#ifdef NDEBUG
64#define LIBC_ASSERT(COND) \
65 do { \
66 } while (false)
67#else
68
69#define LIBC_ASSERT(COND) \
70 do { \
71 if (LIBC_UNLIKELY(!(COND))) { \
72 LIBC_NAMESPACE::write_to_stderr(__FILE__ ":" LLVM_LIBC_STRINGIFY( \
73 __LINE__) ": Assertion failed: '" #COND "' in function: '"); \
74 LIBC_NAMESPACE::write_to_stderr(__PRETTY_FUNCTION__); \
75 LIBC_NAMESPACE::write_to_stderr("'\n"); \
76 LIBC_NAMESPACE::internal::exit(0xFF); \
77 } \
78 } while (false)
79#endif // NDEBUG
80
81#endif // LIBC_COPT_USE_C_ASSERT
82
83#endif // LLVM_LIBC_SRC___SUPPORT_LIBC_ASSERT_H
84