From 0e8d7c9268b65f54d817913e318f91fa56d4807a Mon Sep 17 00:00:00 2001 From: Frank Denis Date: Mon, 17 Jul 2017 01:00:00 +0200 Subject: [PATCH] Implement sodium_set_misuse_handler() --- src/libsodium/include/sodium/core.h | 3 +++ src/libsodium/sodium/core.c | 23 ++++++++++++++++++++++- test/default/sodium_core.c | 15 +++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/libsodium/include/sodium/core.h b/src/libsodium/include/sodium/core.h index 090e8f87..7aa82509 100644 --- a/src/libsodium/include/sodium/core.h +++ b/src/libsodium/include/sodium/core.h @@ -14,6 +14,9 @@ int sodium_init(void) /* ---- */ +SODIUM_EXPORT +int sodium_set_misuse_handler(void (*handler)(const char *err)); + SODIUM_EXPORT void sodium_misuse(const char *err) __attribute__ ((noreturn)); diff --git a/src/libsodium/sodium/core.c b/src/libsodium/sodium/core.c index 12a950ce..5a06f69e 100644 --- a/src/libsodium/sodium/core.c +++ b/src/libsodium/sodium/core.c @@ -171,9 +171,30 @@ sodium_crit_leave(void) #endif +static void (*_misuse_handler)(const char *err); + void sodium_misuse(const char *err) { - (void) err; + void (*handler)(const char *err); + + if (sodium_crit_enter() == 0) { + handler = _misuse_handler; + if (sodium_crit_leave() == 0 && handler != NULL) { + handler(err); + } + } abort(); } + +int +sodium_set_misuse_handler(void (*handler)(const char *err)) +{ + if (sodium_crit_enter() != 0) { + return -1; + } + _misuse_handler = handler; + if (sodium_crit_leave() != 0) { + return -1; + } +} diff --git a/test/default/sodium_core.c b/test/default/sodium_core.c index 7f957759..64c63629 100644 --- a/test/default/sodium_core.c +++ b/test/default/sodium_core.c @@ -2,9 +2,20 @@ #define TEST_NAME "sodium_core" #include "cmptest.h" +static void +misuse_handler(const char *err) +{ + printf("misuse_handler(): [%s]\n", err); + exit(0); +} + int main(void) { + sodium_set_misuse_handler(NULL); + sodium_set_misuse_handler(misuse_handler); + sodium_set_misuse_handler(NULL); + printf("%d\n", sodium_init()); (void) sodium_runtime_has_neon(); @@ -15,5 +26,9 @@ main(void) (void) sodium_runtime_has_pclmul(); (void) sodium_runtime_has_aesni(); + sodium_set_misuse_handler(misuse_handler); + sodium_misuse("TEST"); + printf("Misuse handler returned\n"); + return 0; }