mem.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /*
  2. * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include "internal/e_os.h"
  10. #include "internal/cryptlib.h"
  11. #include "crypto/cryptlib.h"
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <limits.h>
  15. #include <openssl/crypto.h>
  16. /*
  17. * the following pointers may be changed as long as 'allow_customize' is set
  18. */
  19. static int allow_customize = 1;
  20. static CRYPTO_malloc_fn malloc_impl = CRYPTO_malloc;
  21. static CRYPTO_realloc_fn realloc_impl = CRYPTO_realloc;
  22. static CRYPTO_free_fn free_impl = CRYPTO_free;
  23. #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
  24. # include "internal/tsan_assist.h"
  25. # ifdef TSAN_REQUIRES_LOCKING
  26. # define INCREMENT(x) /* empty */
  27. # define LOAD(x) 0
  28. # else /* TSAN_REQUIRES_LOCKING */
  29. static TSAN_QUALIFIER int malloc_count;
  30. static TSAN_QUALIFIER int realloc_count;
  31. static TSAN_QUALIFIER int free_count;
  32. # define INCREMENT(x) tsan_counter(&(x))
  33. # define LOAD(x) tsan_load(&x)
  34. # endif /* TSAN_REQUIRES_LOCKING */
  35. static char *md_failstring;
  36. static long md_count;
  37. static int md_fail_percent = 0;
  38. static int md_tracefd = -1;
  39. static void parseit(void);
  40. static int shouldfail(void);
  41. # define FAILTEST() if (shouldfail()) return NULL
  42. #else
  43. # define INCREMENT(x) /* empty */
  44. # define FAILTEST() /* empty */
  45. #endif
  46. int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,
  47. CRYPTO_realloc_fn realloc_fn,
  48. CRYPTO_free_fn free_fn)
  49. {
  50. if (!allow_customize)
  51. return 0;
  52. if (malloc_fn != NULL)
  53. malloc_impl = malloc_fn;
  54. if (realloc_fn != NULL)
  55. realloc_impl = realloc_fn;
  56. if (free_fn != NULL)
  57. free_impl = free_fn;
  58. return 1;
  59. }
  60. void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn,
  61. CRYPTO_realloc_fn *realloc_fn,
  62. CRYPTO_free_fn *free_fn)
  63. {
  64. if (malloc_fn != NULL)
  65. *malloc_fn = malloc_impl;
  66. if (realloc_fn != NULL)
  67. *realloc_fn = realloc_impl;
  68. if (free_fn != NULL)
  69. *free_fn = free_impl;
  70. }
  71. #if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
  72. void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount)
  73. {
  74. if (mcount != NULL)
  75. *mcount = LOAD(malloc_count);
  76. if (rcount != NULL)
  77. *rcount = LOAD(realloc_count);
  78. if (fcount != NULL)
  79. *fcount = LOAD(free_count);
  80. }
  81. /*
  82. * Parse a "malloc failure spec" string. This likes like a set of fields
  83. * separated by semicolons. Each field has a count and an optional failure
  84. * percentage. For example:
  85. * 100@0;100@25;0@0
  86. * or 100;100@25;0
  87. * This means 100 mallocs succeed, then next 100 fail 25% of the time, and
  88. * all remaining (count is zero) succeed.
  89. * The failure percentge can have 2 digits after the comma. For example:
  90. * 0@0.01
  91. * This means 0.01% of all allocations will fail.
  92. */
  93. static void parseit(void)
  94. {
  95. char *semi = strchr(md_failstring, ';');
  96. char *atsign;
  97. if (semi != NULL)
  98. *semi++ = '\0';
  99. /* Get the count (atol will stop at the @ if there), and percentage */
  100. md_count = atol(md_failstring);
  101. atsign = strchr(md_failstring, '@');
  102. md_fail_percent = atsign == NULL ? 0 : (int)(atof(atsign + 1) * 100 + 0.5);
  103. if (semi != NULL)
  104. md_failstring = semi;
  105. }
  106. /*
  107. * Windows doesn't have random() and srandom(), but it has rand() and srand().
  108. * Some rand() implementations aren't good, but we're not
  109. * dealing with secure randomness here.
  110. */
  111. # ifdef _WIN32
  112. # define random() rand()
  113. # define srandom(seed) srand(seed)
  114. # endif
  115. /*
  116. * See if the current malloc should fail.
  117. */
  118. static int shouldfail(void)
  119. {
  120. int roll = (int)(random() % 10000);
  121. int shoulditfail = roll < md_fail_percent;
  122. # ifndef _WIN32
  123. /* suppressed on Windows as POSIX-like file descriptors are non-inheritable */
  124. int len;
  125. char buff[80];
  126. if (md_tracefd > 0) {
  127. BIO_snprintf(buff, sizeof(buff),
  128. "%c C%ld %%%d R%d\n",
  129. shoulditfail ? '-' : '+', md_count, md_fail_percent, roll);
  130. len = strlen(buff);
  131. if (write(md_tracefd, buff, len) != len)
  132. perror("shouldfail write failed");
  133. }
  134. # endif
  135. if (md_count) {
  136. /* If we used up this one, go to the next. */
  137. if (--md_count == 0)
  138. parseit();
  139. }
  140. return shoulditfail;
  141. }
  142. void ossl_malloc_setup_failures(void)
  143. {
  144. const char *cp = getenv("OPENSSL_MALLOC_FAILURES");
  145. if (cp != NULL && (md_failstring = strdup(cp)) != NULL)
  146. parseit();
  147. if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL)
  148. md_tracefd = atoi(cp);
  149. if ((cp = getenv("OPENSSL_MALLOC_SEED")) != NULL)
  150. srandom(atoi(cp));
  151. }
  152. #endif
  153. void *CRYPTO_malloc(size_t num, const char *file, int line)
  154. {
  155. void *ptr;
  156. INCREMENT(malloc_count);
  157. if (malloc_impl != CRYPTO_malloc) {
  158. ptr = malloc_impl(num, file, line);
  159. if (ptr != NULL || num == 0)
  160. return ptr;
  161. goto err;
  162. }
  163. if (num == 0)
  164. return NULL;
  165. FAILTEST();
  166. if (allow_customize) {
  167. /*
  168. * Disallow customization after the first allocation. We only set this
  169. * if necessary to avoid a store to the same cache line on every
  170. * allocation.
  171. */
  172. allow_customize = 0;
  173. }
  174. ptr = malloc(num);
  175. if (ptr != NULL)
  176. return ptr;
  177. err:
  178. /*
  179. * ossl_err_get_state_int() in err.c uses CRYPTO_zalloc(num, NULL, 0) for
  180. * ERR_STATE allocation. Prevent mem alloc error loop while reporting error.
  181. */
  182. if (file != NULL || line != 0) {
  183. ERR_new();
  184. ERR_set_debug(file, line, NULL);
  185. ERR_set_error(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE, NULL);
  186. }
  187. return NULL;
  188. }
  189. void *CRYPTO_zalloc(size_t num, const char *file, int line)
  190. {
  191. void *ret;
  192. ret = CRYPTO_malloc(num, file, line);
  193. if (ret != NULL)
  194. memset(ret, 0, num);
  195. return ret;
  196. }
  197. void *CRYPTO_aligned_alloc(size_t num, size_t alignment, void **freeptr,
  198. const char *file, int line)
  199. {
  200. void *ret;
  201. *freeptr = NULL;
  202. #if defined(OPENSSL_SMALL_FOOTPRINT)
  203. ret = freeptr = NULL;
  204. return ret;
  205. #endif
  206. #if defined (_BSD_SOURCE) || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L)
  207. if (posix_memalign(&ret, alignment, num))
  208. return NULL;
  209. *freeptr = ret;
  210. return ret;
  211. #elif defined(_ISOC11_SOURCE)
  212. ret = *freeptr = aligned_alloc(alignment, num);
  213. return ret;
  214. #else
  215. /* we have to do this the hard way */
  216. /*
  217. * Note: Windows supports an _aligned_malloc call, but we choose
  218. * not to use it here, because allocations from that function
  219. * require that they be freed via _aligned_free. Given that
  220. * we can't differentiate plain malloc blocks from blocks obtained
  221. * via _aligned_malloc, just avoid its use entirely
  222. */
  223. /*
  224. * Step 1: Allocate an amount of memory that is <alignment>
  225. * bytes bigger than requested
  226. */
  227. *freeptr = malloc(num + alignment);
  228. if (*freeptr == NULL)
  229. return NULL;
  230. /*
  231. * Step 2: Add <alignment - 1> bytes to the pointer
  232. * This will cross the alignment boundary that is
  233. * requested
  234. */
  235. ret = (void *)((char *)*freeptr + (alignment - 1));
  236. /*
  237. * Step 3: Use the alignment as a mask to translate the
  238. * least significant bits of the allocation at the alignment
  239. * boundary to 0. ret now holds a pointer to the memory
  240. * buffer at the requested alignment
  241. * NOTE: It is a documented requirement that alignment be a
  242. * power of 2, which is what allows this to work
  243. */
  244. ret = (void *)((uintptr_t)ret & (uintptr_t)(~(alignment - 1)));
  245. return ret;
  246. #endif
  247. }
  248. void *CRYPTO_realloc(void *str, size_t num, const char *file, int line)
  249. {
  250. INCREMENT(realloc_count);
  251. if (realloc_impl != CRYPTO_realloc)
  252. return realloc_impl(str, num, file, line);
  253. if (str == NULL)
  254. return CRYPTO_malloc(num, file, line);
  255. if (num == 0) {
  256. CRYPTO_free(str, file, line);
  257. return NULL;
  258. }
  259. FAILTEST();
  260. return realloc(str, num);
  261. }
  262. void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num,
  263. const char *file, int line)
  264. {
  265. void *ret = NULL;
  266. if (str == NULL)
  267. return CRYPTO_malloc(num, file, line);
  268. if (num == 0) {
  269. CRYPTO_clear_free(str, old_len, file, line);
  270. return NULL;
  271. }
  272. /* Can't shrink the buffer since memcpy below copies |old_len| bytes. */
  273. if (num < old_len) {
  274. OPENSSL_cleanse((char*)str + num, old_len - num);
  275. return str;
  276. }
  277. ret = CRYPTO_malloc(num, file, line);
  278. if (ret != NULL) {
  279. memcpy(ret, str, old_len);
  280. CRYPTO_clear_free(str, old_len, file, line);
  281. }
  282. return ret;
  283. }
  284. void CRYPTO_free(void *str, const char *file, int line)
  285. {
  286. INCREMENT(free_count);
  287. if (free_impl != CRYPTO_free) {
  288. free_impl(str, file, line);
  289. return;
  290. }
  291. free(str);
  292. }
  293. void CRYPTO_clear_free(void *str, size_t num, const char *file, int line)
  294. {
  295. if (str == NULL)
  296. return;
  297. if (num)
  298. OPENSSL_cleanse(str, num);
  299. CRYPTO_free(str, file, line);
  300. }
  301. #if !defined(OPENSSL_NO_CRYPTO_MDEBUG)
  302. # ifndef OPENSSL_NO_DEPRECATED_3_0
  303. int CRYPTO_mem_ctrl(int mode)
  304. {
  305. (void)mode;
  306. return -1;
  307. }
  308. int CRYPTO_set_mem_debug(int flag)
  309. {
  310. (void)flag;
  311. return -1;
  312. }
  313. int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
  314. {
  315. (void)info; (void)file; (void)line;
  316. return 0;
  317. }
  318. int CRYPTO_mem_debug_pop(void)
  319. {
  320. return 0;
  321. }
  322. void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag,
  323. const char *file, int line)
  324. {
  325. (void)addr; (void)num; (void)flag; (void)file; (void)line;
  326. }
  327. void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag,
  328. const char *file, int line)
  329. {
  330. (void)addr1; (void)addr2; (void)num; (void)flag; (void)file; (void)line;
  331. }
  332. void CRYPTO_mem_debug_free(void *addr, int flag,
  333. const char *file, int line)
  334. {
  335. (void)addr; (void)flag; (void)file; (void)line;
  336. }
  337. int CRYPTO_mem_leaks(BIO *b)
  338. {
  339. (void)b;
  340. return -1;
  341. }
  342. # ifndef OPENSSL_NO_STDIO
  343. int CRYPTO_mem_leaks_fp(FILE *fp)
  344. {
  345. (void)fp;
  346. return -1;
  347. }
  348. # endif
  349. int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
  350. void *u)
  351. {
  352. (void)cb; (void)u;
  353. return -1;
  354. }
  355. # endif
  356. #endif