|
| 1 | +/// @file status_reporting.c |
| 2 | +/// @brief Implements status reporting functionality |
| 3 | + |
| 4 | +#include <stdarg.h> |
| 5 | +#include <stdio.h> |
| 6 | +#include <stdlib.h> |
| 7 | + |
| 8 | +#include "status_reporting.h" |
| 9 | +#include "grackle.h" // GR_FAIL |
| 10 | + |
| 11 | +// this is the internal routine that everything else dispatches to |
| 12 | +static void vprint_err_( |
| 13 | + int internal_error, const struct grimpl_source_location_ locinfo, |
| 14 | + const char* msg, va_list vlist |
| 15 | +) { |
| 16 | + const char* santized_func_name = (locinfo.fn_name == NULL) |
| 17 | + ? "{unspecified}" : locinfo.fn_name; |
| 18 | + |
| 19 | + const char* fallback_msg_ = "{NULL encountered instead of error message}"; |
| 20 | + char* dynamic_msg_buf = NULL; |
| 21 | + const char* msg_buf; |
| 22 | + if (msg == NULL) { |
| 23 | + msg_buf = fallback_msg_; |
| 24 | + } else { |
| 25 | + // make a copy of the variadic function arguments |
| 26 | + va_list vlist_copy; |
| 27 | + va_copy(vlist_copy, vlist); |
| 28 | + |
| 29 | + // get the total size of the formatted message |
| 30 | + size_t msg_len = vsnprintf(NULL, 0, msg, vlist_copy) + 1; |
| 31 | + va_end(vlist_copy); |
| 32 | + |
| 33 | + // allocate the buffer to hold the message |
| 34 | + dynamic_msg_buf = malloc(sizeof(char) * msg_len); |
| 35 | + |
| 36 | + // actually format the message |
| 37 | + vsnprintf(dynamic_msg_buf, msg_len, msg, vlist); |
| 38 | + va_end(vlist); |
| 39 | + |
| 40 | + msg_buf = dynamic_msg_buf; |
| 41 | + } |
| 42 | + |
| 43 | + const char* descr = (internal_error == 1) ? "FATAL" : "ERROR"; |
| 44 | + |
| 45 | + fprintf( |
| 46 | + stderr, "Grackle-%s %s:%d in %s] %s\n", descr, locinfo.file, |
| 47 | + locinfo.lineno, santized_func_name, msg_buf |
| 48 | + ); |
| 49 | + |
| 50 | + if (dynamic_msg_buf != NULL) { free(dynamic_msg_buf); } |
| 51 | +} |
| 52 | + |
| 53 | +void grimpl_abort_with_internal_err_( |
| 54 | + const struct grimpl_source_location_ locinfo, const char* msg, ... |
| 55 | +) { |
| 56 | + va_list args; |
| 57 | + va_start(args, msg); |
| 58 | + vprint_err_(1, locinfo, msg, args); |
| 59 | + // while stderr should flush by default, people may overwrite this behavior. |
| 60 | + // We want to force flushing here since we are aborting the program |
| 61 | + fflush(stderr); |
| 62 | + abort(); |
| 63 | +} |
| 64 | + |
| 65 | +int grimpl_print_and_return_err_( |
| 66 | + const struct grimpl_source_location_ locinfo, const char* msg, ... |
| 67 | +) { |
| 68 | + va_list args; |
| 69 | + va_start(args, msg); |
| 70 | + vprint_err_(0, locinfo, msg, args); |
| 71 | + return GR_FAIL; |
| 72 | +} |
| 73 | + |
| 74 | +void grimpl_print_err_msg_( |
| 75 | + const struct grimpl_source_location_ locinfo, const char* msg, ... |
| 76 | +) { |
| 77 | + va_list args; |
| 78 | + va_start(args, msg); |
| 79 | + vprint_err_(0, locinfo, msg, args); |
| 80 | +} |
| 81 | + |
0 commit comments