sodium_utils2.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include <stdlib.h>
  2. #include <sys/types.h>
  3. #include <limits.h>
  4. #include <signal.h>
  5. #define TEST_NAME "sodium_utils2"
  6. #include "cmptest.h"
  7. #ifdef __SANITIZE_ADDRESS__
  8. # warning The sodium_utils2 test is expected to fail with address sanitizer
  9. #endif
  10. __attribute__((noreturn)) static void
  11. segv_handler(int sig)
  12. {
  13. (void) sig;
  14. printf("Intentional segfault / bus error caught\n");
  15. printf("OK\n");
  16. #ifdef SIGSEGV
  17. signal(SIGSEGV, SIG_DFL);
  18. #endif
  19. #ifdef SIGBUS
  20. signal(SIGBUS, SIG_DFL);
  21. #endif
  22. #ifdef SIGABRT
  23. signal(SIGABRT, SIG_DFL);
  24. #endif
  25. exit(0);
  26. }
  27. int
  28. main(void)
  29. {
  30. void * buf;
  31. size_t size;
  32. unsigned int i;
  33. if (sodium_malloc(SIZE_MAX - 1U) != NULL) {
  34. return 1;
  35. }
  36. if (sodium_malloc(0U) == NULL) {
  37. return 1;
  38. }
  39. if (sodium_allocarray(SIZE_MAX / 2U + 1U, SIZE_MAX / 2U) != NULL) {
  40. return 1;
  41. }
  42. sodium_free(sodium_allocarray(0U, 0U));
  43. sodium_free(sodium_allocarray(0U, 1U));
  44. sodium_free(sodium_allocarray(1U, 0U));
  45. buf = sodium_allocarray(1000U, 50U);
  46. memset(buf, 0, 50000U);
  47. sodium_free(buf);
  48. sodium_free(sodium_malloc(0U));
  49. sodium_free(NULL);
  50. for (i = 0U; i < 10000U; i++) {
  51. size = 1U + randombytes_uniform(100000U);
  52. buf = sodium_malloc(size);
  53. assert(buf != NULL);
  54. memset(buf, i, size);
  55. sodium_mprotect_noaccess(buf);
  56. sodium_free(buf);
  57. }
  58. printf("OK\n");
  59. #ifdef SIGSEGV
  60. signal(SIGSEGV, segv_handler);
  61. #endif
  62. #ifdef SIGBUS
  63. signal(SIGBUS, segv_handler);
  64. #endif
  65. #ifdef SIGABRT
  66. signal(SIGABRT, segv_handler);
  67. #endif
  68. size = 1U + randombytes_uniform(100000U);
  69. buf = sodium_malloc(size);
  70. assert(buf != NULL);
  71. /* old versions of asan emit a warning because they don't support mlock*() */
  72. #ifndef __SANITIZE_ADDRESS__
  73. sodium_mprotect_readonly(buf);
  74. sodium_mprotect_readwrite(buf);
  75. #endif
  76. #if defined(HAVE_CATCHABLE_SEGV) && !defined(__EMSCRIPTEN__) && !defined(__SANITIZE_ADDRESS__)
  77. sodium_memzero(((unsigned char *) buf) + size, 1U);
  78. sodium_mprotect_noaccess(buf);
  79. sodium_free(buf);
  80. printf("Overflow not caught\n");
  81. #else
  82. segv_handler(0);
  83. #endif
  84. return 0;
  85. }