xref: /aosp_15_r20/external/pigweed/pw_log_string/wrap_newlib_assert.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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 
15 // This file provides an implementation of assert that can be used with ld's
16 // --wrap option to wrap NEWLIB's underlying assert function. This can be used
17 // in cases where replacing the assert macro via include overrides isn't
18 // feasible, but you still need to wrap third party codes usage of assert.
19 //
20 // It redirect assert calls to a PW_LOG_LEVEL_FATAL message with the asserts
21 // filename, line info and failed expression.
22 
23 #include <assert.h>  // __assert_func
24 
25 #include "pw_log/levels.h"
26 #include "pw_log/options.h"
27 #include "pw_log_string/handler.h"
28 
29 // Get the name of the wrapper function for "function",
30 // according to GNU ld's --wrap option.
31 #define WRAPPER(function) __wrap_##function
32 
33 #ifdef __NEWLIB__
34 // newlib assert() calls __assert_func().
35 //
36 // __NEWLIB__ is defined in <_newlib_version.h> which gets included indirectly
37 // via <assert.h>.
38 
39 // Ensure our function signature matches the real function.
40 extern "C" decltype(__assert_func) WRAPPER(__assert_func);
41 
42 // Wrap newlib's __assert_func() to redirect assert() failures to our
43 // pw_log_string:handler implementation.
WRAPPER(__assert_func)44 extern "C" void WRAPPER(__assert_func)(const char* filename,
45                                        int line,
46                                        const char* /* function */,
47                                        const char* expr) {
48   pw_log_string_HandleMessage(PW_LOG_LEVEL_FATAL,
49                               PW_LOG_FLAGS,
50                               PW_LOG_MODULE_NAME,
51                               filename,
52                               line,
53                               "assert() failed: %s",
54                               expr);
55 }
56 
57 #endif  // __NEWLIB__
58