xref: /4.0.0/platform/tests/backtrace_test.c (revision 4d17a68e)
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
18/* Test for print_backtrace - Setup a call stack of (at least) 3 frames,
19 * then call print_backtrace; verifying that we get at least 3 frames.
20 */
21
22#include "config.h"
23
24#include <stdio.h>
25
26#include <platform/backtrace.h>
27
28
29#ifdef WIN32
30    #define NOINLINE __declspec(noinline)
31#else
32    #define NOINLINE __attribute__((noinline))
33#endif
34
35NOINLINE static int leaf();
36NOINLINE static int middle();
37NOINLINE static int outer();
38
39// Variable used in each function in the chain; to defeat tail-call
40// optimization.
41static int dummy;
42
43// Count of how many frames we have seen.
44static int frames;
45static void* expected_ctx = (void*)0xcbdb;
46
47static void write_callback(void* ctx, const char* frame) {
48    cb_assert(ctx == expected_ctx);
49    cb_assert(frame != NULL);
50    cb_assert(strlen(frame) > 0);
51    printf("%s\n", frame);
52    frames++;
53}
54
55static int leaf() {
56    print_backtrace(write_callback, expected_ctx);
57    return dummy++;
58}
59
60static int middle() {
61    leaf();
62    return dummy++;
63}
64
65static int outer() {
66    middle();
67    return dummy++;
68}
69
70int main(void) {
71    outer();
72    cb_assert(frames >= 3);
73}
74