Skip to content

Commit affb1dc

Browse files
ScaledLizardslaren
authored andcommitted
ggml : Callback before abort (ggml-org#14481)
* 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. * Return previous callback to allow callback chaining * style fixes --------- Co-authored-by: Diego Devesa <slarengh@gmail.com>
1 parent 0994184 commit affb1dc

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

ggml/src/ggml.c

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,19 +202,34 @@ 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 ggml_abort_callback_t ggml_set_abort_callback(ggml_abort_callback_t callback) {
209+
ggml_abort_callback_t ret_val = g_abort_callback;
210+
g_abort_callback = callback;
211+
return ret_val;
212+
}
213+
205214
void ggml_abort(const char * file, int line, const char * fmt, ...) {
206215
fflush(stdout);
207216

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

210220
va_list args;
211221
va_start(args, fmt);
212-
vfprintf(stderr, fmt, args);
222+
vsnprintf(message + offset, sizeof(message) - offset, fmt, args);
213223
va_end(args);
214224

215-
fprintf(stderr, "\n");
225+
if (g_abort_callback) {
226+
g_abort_callback(message);
227+
} else {
228+
// default: print error and backtrace to stderr
229+
fprintf(stderr, "%s\n", message);
230+
ggml_print_backtrace();
231+
}
216232

217-
ggml_print_backtrace();
218233
abort();
219234
}
220235

0 commit comments

Comments
 (0)