1 // Copyright 2022 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include <stdio.h> 17 #include <stdlib.h> 18 19 #include "pw_assert/config.h" 20 21 #if PW_ASSERT_ENABLE_DEBUG 22 #define _PW_ASSERT_MACRO(type) "PW_" type "() or PW_D" type "()" 23 #else 24 #define _PW_ASSERT_MACRO(type) "PW_" type "()" 25 #endif // PW_ASSERT_ENABLE_DEBUG 26 27 #ifdef __GNUC__ 28 #define _PW_ASSERT_ABORT_FUNCTION __PRETTY_FUNCTION__ 29 #else 30 #define _PW_ASSERT_ABORT_FUNCTION __func__ 31 #endif // __GNUC__ 32 33 // This assert implementation prints the file path, line number, and assert 34 // expression using printf. Uses ANSI escape codes for colors. 35 // 36 // This is done with single printf to work better in multithreaded enironments. 37 #define PW_ASSERT_HANDLE_FAILURE(expression) \ 38 PW_ASSERT_PRINT_EXPRESSION("ASSERT", expression); \ 39 fflush(stderr); \ 40 abort() 41 42 #define PW_ASSERT_PRINT_EXPRESSION(macro, expression) \ 43 fflush(stdout); \ 44 fprintf(stderr, \ 45 "\033[41m\033[37m\033[1m%s:%d:\033[0m " \ 46 "\033[1m" \ 47 _PW_ASSERT_MACRO(macro) \ 48 " " \ 49 "\033[31mFAILED!\033[0m\n\n" \ 50 " FAILED ASSERTION\n\n" \ 51 " %s\n\n" \ 52 " FILE & LINE\n\n" \ 53 " %s:%d\n\n" \ 54 " FUNCTION\n\n" \ 55 " %s\n\n", \ 56 __FILE__, \ 57 __LINE__, \ 58 expression, \ 59 __FILE__, \ 60 __LINE__, \ 61 _PW_ASSERT_ABORT_FUNCTION) 62