xref: /6.6.0/platform/src/cbassert.c (revision d3e7c4b4)
1/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2/*
3 *     Copyright 2015 Couchbase, Inc
4 *
5 *   Licensed under the Apache License, Version 2.0 (the "License");
6 *   you may not use this file except in compliance with the License.
7 *   You may obtain a copy of the License at
8 *
9 *       http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *   Unless required by applicable law or agreed to in writing, software
12 *   distributed under the License is distributed on an "AS IS" BASIS,
13 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *   See the License for the specific language governing permissions and
15 *   limitations under the License.
16 */
17#include <platform/cbassert.h>
18#include <platform/backtrace.h>
19
20#if defined(WIN32)
21#include <folly/portability/Windows.h>
22#include <crtdbg.h>
23#endif
24
25#include <stdio.h>
26#include <stdlib.h>
27
28#if defined(WIN32) || ( defined(HAVE_BACKTRACE) && defined(HAVE_DLADDR))
29#  define HAVE_BACKTRACE_SUPPORT 1
30#endif
31
32#ifdef HAVE_BACKTRACE_SUPPORT
33static void write_callback(void* ctx, const char* frame) {
34    fprintf(stderr, "\t%s\n", frame);
35}
36#endif
37
38void cb_assert_die(const char *expression, const char *file, int line)
39{
40    (void)fprintf(stderr, "assertion failed [%s] at %s:%u\n",
41                  expression, file, line);
42
43#ifdef HAVE_BACKTRACE_SUPPORT
44    fprintf(stderr, "Called from:\n");
45    print_backtrace(write_callback, NULL);
46#endif
47
48    fflush(stderr);
49    abort();
50}
51
52#if defined(WIN32)
53
54int backtraceReportHook( int reportType, char *message, int *returnValue ) {
55    fprintf(stderr, message);
56    fprintf(stderr, "Called from:\n");
57    print_backtrace(write_callback, NULL);
58    return FALSE;
59}
60
61void setupWindowsDebugCRTAssertHandling() {
62    _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_WNDW);
63    _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR );
64    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_WNDW);
65    _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR );
66    _CrtSetReportHook(backtraceReportHook);
67}
68#else
69void setupWindowsDebugCRTAssertHandling() {
70}
71#endif
72