/* printf/va_list stay in C so the line callback has the same ABI on each CPU. */ #ifndef V_ALPM_NATIVE_LOG_H #define V_ALPM_NATIVE_LOG_H #include #include #include #include typedef void (*v_alpm_log_callback)(void *, uint32_t, const char *, va_list); typedef void (*v_alpm_log_line_callback)(void *, uint32_t, const char *); typedef struct v_alpm_log_line_state { v_alpm_log_line_callback callback; void *context; } v_alpm_log_line_state; static void v_alpm_log_line(void *context, uint32_t level, const char *format, va_list args) { v_alpm_log_line_state *state = context; if(!state || !state->callback || !format) { return; } char buffer[4096]; va_list copy; va_copy(copy, args); int length = vsnprintf(buffer, sizeof(buffer), format, copy); va_end(copy); if(length < 0) { return; } char *message = buffer; if((size_t)length >= sizeof(buffer)) { message = malloc((size_t)length + 1); if(message) { va_copy(copy, args); vsnprintf(message, (size_t)length + 1, format, copy); va_end(copy); } else { message = buffer; } } state->callback(state->context, level, message); if(message != buffer) { free(message); } } static void v_alpm_log_emit_format(v_alpm_log_callback callback, void *context, uint32_t level, const char *format, ...) { va_list args; va_start(args, format); callback(context, level, format, args); va_end(args); } static void v_alpm_log_emit(v_alpm_log_callback callback, void *context, uint32_t level, const char *message) { if(callback) { v_alpm_log_emit_format(callback, context, level, "%s", message); } } static v_alpm_log_callback v_alpm_log_line_function(void) { return v_alpm_log_line; } static void *v_alpm_log_line_create(v_alpm_log_line_callback callback, void *context) { v_alpm_log_line_state *state = malloc(sizeof(*state)); if(state) { state->callback = callback; state->context = context; } return state; } static v_alpm_log_line_callback v_alpm_log_line_receiver(void *context) { return context ? ((v_alpm_log_line_state *)context)->callback : NULL; } static void *v_alpm_log_line_context(void *context) { return context ? ((v_alpm_log_line_state *)context)->context : NULL; } #endif