Skip to content

Commit d930d3f

Browse files
committed
Add a callback that will be called just before abort. This allows apps without a console to display a message to the user and save data if needed.
1 parent 343b6e9 commit d930d3f

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

ggml/include/ggml.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,12 @@
314314
extern "C" {
315315
#endif
316316

317+
// Function type used in fatal error callbacks
318+
typedef void (*ggml_abort_callback_t)(const char * error_message);
319+
320+
// Set the abort callback (passing null will restore original abort functionality: printing a message to stdout)
321+
GGML_API void ggml_set_abort_callback(ggml_abort_callback_t callback);
322+
317323
GGML_NORETURN GGML_ATTRIBUTE_FORMAT(3, 4)
318324
GGML_API void ggml_abort(const char * file, int line, const char * fmt, ...);
319325

ggml/src/ggml.c

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,19 +202,32 @@ void ggml_print_backtrace(void) {
202202
}
203203
#endif
204204

205+
static ggml_abort_callback_t g_abort_callback = NULL;
206+
207+
// Set the abort callback (passing null will restore original abort functionality: printing a message to stdout)
208+
GGML_API void ggml_set_abort_callback(ggml_abort_callback_t callback) {
209+
g_abort_callback = callback;
210+
}
211+
205212
void ggml_abort(const char * file, int line, const char * fmt, ...) {
206213
fflush(stdout);
207214

208-
fprintf(stderr, "%s:%d: ", file, line);
215+
char message[2048];
216+
int offset = snprintf(message, sizeof(message), "%s:%d: ", file, line);
209217

210218
va_list args;
211219
va_start(args, fmt);
212-
vfprintf(stderr, fmt, args);
220+
vsnprintf(message + offset, sizeof(message) - offset, fmt, args);
213221
va_end(args);
214222

215-
fprintf(stderr, "\n");
223+
if (g_abort_callback) {
224+
g_abort_callback(message);
225+
} else {
226+
// default: print to stderr and abort
227+
fprintf(stderr, "%s\n", message);
228+
ggml_print_backtrace();
229+
}
216230

217-
ggml_print_backtrace();
218231
abort();
219232
}
220233

0 commit comments

Comments
 (0)