aboutsummaryrefslogtreecommitdiff
path: root/reference_model/src/func_debug.cc
blob: 755f79f6f346ad5bd8b4a69979dd36a2899544ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344

// Copyright (c) 2020, ARM Limited.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//         http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

#include <ctype.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sstream>

#ifndef _MSC_VER
#include <execinfo.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <unistd.h>
#endif

#include "func_debug.h"

#define MAX_FRAMES 100

static bool str_case_equal(const std::string& a, const std::string& b)
{
    return std::equal(a.begin(), a.end(), b.begin(), b.end(),
                      [](char ac, char bc) { return tolower(ac) == tolower(bc); });
}

#ifndef _MSC_VER
pid_t func_print_backtrace_helper(int num_tries, int sig);
#endif

void func_print_backtrace(FILE* out, int sig)
{
#ifndef _MSC_VER
    for (int i = 0; i < 2; i++)
    {
        const pid_t child_pid = func_print_backtrace_helper(i, sig);
        if (child_pid < 0)
        {
            perror("Backtrace generation failed on fork");
            break;
        }

        int status = 0;
        waitpid(child_pid, &status, 0);
        if (WEXITSTATUS(status) == 0)
        {
            break;
        }
    }
#endif
}

#ifndef _MSC_VER
pid_t func_print_backtrace_helper(int num_tries, int sig)
{
    const pid_t child_pid = fork();

    if (child_pid)
    {
        return 0;
    }

    const pid_t ppid = getppid();

    printf("Attaching debugger to pid %d\n", ppid);
    // Check if we're in a debugger
    if (ptrace(PTRACE_ATTACH, ppid, 0, 0) == 0)
    {
        // If we reach this point, no debugger is present
        // Undo effects of PTRACE_ATTACH
        waitpid(ppid, NULL, 0);
        ptrace(PTRACE_CONT, 0, 0, 0);
        ptrace(PTRACE_DETACH, ppid, 0, 0);

        dup2(STDERR_FILENO, STDOUT_FILENO);

        char parent_pid[20];
        snprintf(parent_pid, sizeof(parent_pid), "attach %d", ppid);
        fprintf(stdout, "Caught signal %d (%s)\n", sig, strsignal(sig));

        execlp("gdb", "gdb", "--batch", "-n", "-ex",
               // Don't print startup messages for each thread
               "-ex", "set print thread-events off", "-ex", parent_pid,
               // Turn off pagination
               "-ex", "set height 0",
               // Print a backtrace for the current thread
               "-ex", "thread $_thread", "-ex", "bt",
               // Print a backtrace for the main thread (uncomment the next two lines, if desired)
               //"-ex", "thread 1",
               //"-ex", "bt",
               // Print a backtrace for all thread (TMI)
               //"-ex", "thread apply all bt",
               NULL);

        // If we reach this point, it is bad. Attempt to print an error before exiting.
        perror("Backtrace generation failed to invoke gdb");
        exit(1);
    }

    // Debugger present.  Exit here.
    exit(0);

    return 0;
}
#endif

void func_backtrace_signal_handler(int sig)
{
    func_print_backtrace(NULL, sig);
    exit(1);
}

// Note: this overwrites other signal handlers.  May want to make this
// more friendly sometime
void func_enable_signal_handlers()
{
    static const int sig_list[] = { SIGABRT, SIGSEGV, SIGILL, SIGFPE };

    if (getenv("FUNC_NO_SIG_HANDLERS"))
    {
        return;
    }

    for (size_t i = 0; i < sizeof(sig_list) / sizeof(int); i++)
    {
        struct sigaction act;

        bzero(&act, sizeof(act));
        act.sa_handler = func_backtrace_signal_handler;

        if (sigaction(sig_list[i], &act, NULL))
        {
            perror("Error calling sigaction");
        }
    }
}

static const std::vector<std::pair<std::string, uint32_t>> func_debug_verbosity_table = {
    { "NONE", DEBUG_VERB_NONE }, { "INFO", DEBUG_VERB_INFO }, { "IFACE", DEBUG_VERB_IFACE },
    { "LOW", DEBUG_VERB_LOW },   { "MED", DEBUG_VERB_MED },   { "HIGH", DEBUG_VERB_HIGH }
};

// Initialize the debug mode
int func_debug_t::init_debug(uint64_t inst_id)
{
    // Set the default debug settings
    set_mask(static_cast<uint64_t>(DEBUG_NONE));
    set_verbosity(DEBUG_VERB_NONE);
    set_inst_mask(DEBUG_INST_ALL);
    func_debug_file = stderr;
    this->inst_id = inst_id;

    return 0;
}

int func_debug_t::fini_debug()
{
    return 0;
}

int func_debug_t::set_file(const std::string& filename)
{
    // Open the debug output file
    func_debug_file = fopen(filename.c_str(), "w");

    if (!func_debug_file)
    {
        perror(NULL);
        FATAL_ERROR("Cannot open debug output file: %s\n", filename.c_str());
        return 1;
    }
    if (is_output_unbuffered)
    {
        setvbuf(func_debug_file, nullptr, _IONBF, 0);
    }

    return 0;
}

void func_debug_t::set_verbosity(const std::string& str)
{
    for (auto& verb : func_debug_verbosity_table)
    {
        if (str_case_equal(str, verb.first))
        {
            set_verbosity(verb.second);
            return;
        }
    }

    FATAL_ERROR("Invalid debug verbosity: %s", str.c_str());
}

void func_debug_t::set_verbosity(const uint32_t verb)
{
    uint32_t new_mask = verb;

    switch (verb)
    {
        case DEBUG_VERB_NONE:
            new_mask = DEBUG_VERB_NONE;
            break;
        case DEBUG_VERB_INFO:
            new_mask = DEBUG_VERB_INFO;
            break;
        case DEBUG_VERB_IFACE:
            new_mask = DEBUG_VERB_IFACE;
            break;
        case DEBUG_VERB_HIGH:
            new_mask |= DEBUG_VERB_HIGH;
            // Intentional fallthrough
        case DEBUG_VERB_MED:
            new_mask |= DEBUG_VERB_MED;
            // Intentional fallthrough
        case DEBUG_VERB_LOW:
            new_mask |= DEBUG_VERB_LOW;
            new_mask |= DEBUG_VERB_INFO;
            new_mask |= DEBUG_VERB_IFACE;
            break;
    }

    func_debug_verbosity = new_mask;
}

void func_debug_t::set_mask(const uint64_t mask)
{
    if (mask == DEBUG_NONE)
        func_debug_mask = mask;
    else
        func_debug_mask |= mask;

    // Set a minimum verbosity level
    if (func_debug_verbosity == DEBUG_VERB_NONE)
        func_debug_verbosity = DEBUG_VERB_INFO;
}

void func_debug_t::set_inst_mask(const char* mask)
{
    uint64_t val;

    val = strtoul(mask, NULL, 0);

    return set_inst_mask(val);
}

void func_debug_t::set_inst_mask(const uint64_t mask)
{
    if (mask == 0)
        func_debug_inst_mask = DEBUG_INST_ALL;
    else
        func_debug_inst_mask = mask;
}

std::vector<std::pair<std::string, int>> debug_str_table = {
#define DEBUG_MODE(NAME, BIT) {#NAME, BIT},
#include "debug_modes.def"
#undef DEBUG_MODE
};

void func_debug_t::set_mask(const std::string& str)
{
    if (str == "all")
    {
        set_mask(UINT64_MAX - 1);
        return;
    }
    for (auto& mode : debug_str_table)
    {
        if (mode.first == str)
        {
            set_mask(mode.second);
            return;
        }
    }
    print_masks(stderr);

    FATAL_ERROR("Invalid debug mask: %s", str.c_str());
}

void func_debug_t::print_masks(FILE* out)
{
    fprintf(out, "Available debug masks:\n");
    for (auto& mode : debug_str_table)
    {
        fprintf(out, "[%d] %s\n", mode.second, mode.first.c_str());
    }
}

void func_debug_t::set_output_unbuffered(const bool is_unbuffered)
{
    is_output_unbuffered = is_unbuffered;
}

// Print warnings to the debug file or optionally store them in a buffer instead
// Note that the buffer is circular and can be overwritten if enough messages are
// written before removing a warning from the front.
void func_debug_warning(
    func_debug_t* func_debug, const char* file, const char* func, const int line, const char* fmt, ...)
{
    va_list args;
    va_start(args, fmt);

    // Print to the debug file (e.g., stderr)
    fprintf(func_debug->func_debug_file, "WARNING AT %s:%d %s():\n", file, line, func);
    vfprintf(func_debug->func_debug_file, fmt, args);
    fprintf(func_debug->func_debug_file, "\n");

    va_end(args);
}

std::string func_debug_t::get_debug_mask_help_string()
{
    std::string rval = "Set debug mask. Valid values are: ";
    for (auto& mask : debug_str_table) {
        rval += mask.first + " ";
    }
    return rval;
}

std::string func_debug_t::get_debug_verbosity_help_string()
{
    std::string rval = "Set logging level. Valid values are: ";
    for (auto& verb : func_debug_verbosity_table)
    {
        rval += verb.first + " ";
    }
    return rval;
}