memory.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. /* memory.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #ifdef WOLFSSL_LINUXKM
  25. /* inhibit "#undef current" in linuxkm_wc_port.h, included from wc_port.h,
  26. * because needed in linuxkm_memory.c, included below.
  27. */
  28. #define WOLFSSL_NEED_LINUX_CURRENT
  29. #endif
  30. #include <wolfssl/wolfcrypt/types.h>
  31. /*
  32. Possible memory options:
  33. * NO_WOLFSSL_MEMORY: Disables wolf memory callback support. When not defined settings.h defines USE_WOLFSSL_MEMORY.
  34. * WOLFSSL_STATIC_MEMORY: Turns on the use of static memory buffers and functions.
  35. This allows for using static memory instead of dynamic.
  36. * WOLFSSL_STATIC_ALIGN: Define defaults to 16 to indicate static memory alignment.
  37. * HAVE_IO_POOL: Enables use of static thread safe memory pool for input/output buffers.
  38. * XMALLOC_OVERRIDE: Allows override of the XMALLOC, XFREE and XREALLOC macros.
  39. * XMALLOC_USER: Allows custom XMALLOC, XFREE and XREALLOC functions to be defined.
  40. * WOLFSSL_NO_MALLOC: Disables the fall-back case to use STDIO malloc/free when no callbacks are set.
  41. * WOLFSSL_TRACK_MEMORY: Enables memory tracking for total stats and list of allocated memory.
  42. * WOLFSSL_DEBUG_MEMORY: Enables extra function and line number args for memory callbacks.
  43. * WOLFSSL_DEBUG_MEMORY_PRINT: Enables printing of each malloc/free.
  44. * WOLFSSL_MALLOC_CHECK: Reports malloc or alignment failure using WOLFSSL_STATIC_ALIGN
  45. * WOLFSSL_FORCE_MALLOC_FAIL_TEST: Used for internal testing to induce random malloc failures.
  46. * WOLFSSL_HEAP_TEST: Used for internal testing of heap hint
  47. * WOLFSSL_MEM_FAIL_COUNT: Fail memory allocation at a count from
  48. * environment variable: MEM_FAIL_CNT.
  49. */
  50. #ifdef WOLFSSL_ZEPHYR
  51. #undef realloc
  52. void *z_realloc(void *ptr, size_t size)
  53. {
  54. if (ptr == NULL)
  55. ptr = malloc(size);
  56. else
  57. ptr = realloc(ptr, size);
  58. return ptr;
  59. }
  60. #define realloc z_realloc
  61. #endif
  62. #ifdef USE_WOLFSSL_MEMORY
  63. #include <wolfssl/wolfcrypt/memory.h>
  64. #include <wolfssl/wolfcrypt/error-crypt.h>
  65. #include <wolfssl/wolfcrypt/logging.h>
  66. #if defined(WOLFSSL_DEBUG_MEMORY) && defined(WOLFSSL_DEBUG_MEMORY_PRINT)
  67. #include <stdio.h>
  68. #endif
  69. #ifdef WOLFSSL_FORCE_MALLOC_FAIL_TEST
  70. static int gMemFailCountSeed;
  71. static int gMemFailCount;
  72. void wolfSSL_SetMemFailCount(int memFailCount)
  73. {
  74. if (gMemFailCountSeed == 0) {
  75. gMemFailCountSeed = memFailCount;
  76. gMemFailCount = memFailCount;
  77. }
  78. }
  79. #endif
  80. #if defined(WOLFSSL_MALLOC_CHECK) || defined(WOLFSSL_TRACK_MEMORY_FULL) || \
  81. defined(WOLFSSL_MEMORY_LOG)
  82. #include <stdio.h>
  83. #endif
  84. /* Set these to default values initially. */
  85. static wolfSSL_Malloc_cb malloc_function = NULL;
  86. static wolfSSL_Free_cb free_function = NULL;
  87. static wolfSSL_Realloc_cb realloc_function = NULL;
  88. int wolfSSL_SetAllocators(wolfSSL_Malloc_cb mf,
  89. wolfSSL_Free_cb ff,
  90. wolfSSL_Realloc_cb rf)
  91. {
  92. malloc_function = mf;
  93. free_function = ff;
  94. realloc_function = rf;
  95. return 0;
  96. }
  97. int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf,
  98. wolfSSL_Free_cb* ff,
  99. wolfSSL_Realloc_cb* rf)
  100. {
  101. if (mf) *mf = malloc_function;
  102. if (ff) *ff = free_function;
  103. if (rf) *rf = realloc_function;
  104. return 0;
  105. }
  106. #ifdef WOLFSSL_MEM_FAIL_COUNT
  107. static wolfSSL_Mutex memFailMutex;
  108. int mem_fail_allocs = 0;
  109. int mem_fail_frees = 0;
  110. int mem_fail_cnt = 0;
  111. void wc_MemFailCount_Init()
  112. {
  113. char* cnt;
  114. wc_InitMutex(&memFailMutex);
  115. cnt = getenv("MEM_FAIL_CNT");
  116. if (cnt != NULL) {
  117. fprintf(stderr, "MemFailCount At: %d\n", mem_fail_cnt);
  118. mem_fail_cnt = atoi(cnt);
  119. }
  120. }
  121. static int wc_MemFailCount_AllocMem(void)
  122. {
  123. int ret = 1;
  124. wc_LockMutex(&memFailMutex);
  125. if ((mem_fail_cnt > 0) && (mem_fail_cnt <= mem_fail_allocs + 1)) {
  126. ret = 0;
  127. }
  128. else {
  129. mem_fail_allocs++;
  130. }
  131. wc_UnLockMutex(&memFailMutex);
  132. return ret;
  133. }
  134. static void wc_MemFailCount_FreeMem(void)
  135. {
  136. wc_LockMutex(&memFailMutex);
  137. mem_fail_frees++;
  138. wc_UnLockMutex(&memFailMutex);
  139. }
  140. void wc_MemFailCount_Free()
  141. {
  142. wc_FreeMutex(&memFailMutex);
  143. fprintf(stderr, "MemFailCount Total: %d\n", mem_fail_allocs);
  144. fprintf(stderr, "MemFailCount Frees: %d\n", mem_fail_frees);
  145. }
  146. #endif
  147. #ifndef WOLFSSL_STATIC_MEMORY
  148. #ifdef WOLFSSL_CHECK_MEM_ZERO
  149. #ifndef WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN
  150. /* Number of entries in table of addresses to check. */
  151. #define WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN 256
  152. #endif
  153. /* Alignment to maintain when adding length to allocated pointer.
  154. * Intel x64 wants to use aligned loads of XMM registers.
  155. */
  156. #define MEM_ALIGN 16
  157. /* An address that is meant to be all zeros for its length. */
  158. typedef struct MemZero {
  159. /* Name of address to check. */
  160. const char* name;
  161. /* Address to check. */
  162. const void* addr;
  163. /* Length of data that must be zero. */
  164. size_t len;
  165. } MemZero;
  166. /* List of addresses to check. */
  167. static MemZero memZero[WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN];
  168. /* Next index to place address at.
  169. * -1 indicates uninitialized.
  170. * If nextIdx is equal to WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN then all entries
  171. * have been used.
  172. */
  173. static int nextIdx = -1;
  174. /* Mutex to protect modifying list of addresses to check. */
  175. static wolfSSL_Mutex zeroMutex;
  176. /* Initialize the table of addresses and the mutex.
  177. */
  178. void wc_MemZero_Init()
  179. {
  180. /* Clear the table to more easily see what is valid. */
  181. XMEMSET(memZero, 0, sizeof(memZero));
  182. /* Initialize mutex. */
  183. wc_InitMutex(&zeroMutex);
  184. /* Next index is first entry. */
  185. nextIdx = 0;
  186. }
  187. /* Free the mutex and check we have not any uncheck addresses.
  188. */
  189. void wc_MemZero_Free()
  190. {
  191. /* Free mutex. */
  192. wc_FreeMutex(&zeroMutex);
  193. /* Make sure we checked all addresses. */
  194. if (nextIdx > 0) {
  195. int i;
  196. fprintf(stderr, "[MEM_ZERO] Unseen: %d\n", nextIdx);
  197. for (i = 0; i < nextIdx; i++) {
  198. fprintf(stderr, " %s - %p:%ld\n", memZero[i].name, memZero[i].addr,
  199. memZero[i].len);
  200. }
  201. }
  202. /* Uninitialized value in next index. */
  203. nextIdx = -1;
  204. }
  205. /* Add an address to check.
  206. *
  207. * @param [in] name Name of address to check.
  208. * @param [in] addr Address that needs to be checked.
  209. * @param [in] len Length of data that must be zero.
  210. */
  211. void wc_MemZero_Add(const char* name, const void* addr, size_t len)
  212. {
  213. /* Initialize if not done. */
  214. if (nextIdx == -1) {
  215. wc_MemZero_Init();
  216. }
  217. /* Add an entry to the table while locked. */
  218. wc_LockMutex(&zeroMutex);
  219. if (nextIdx < WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN) {
  220. /* Fill in the next entry and update next index. */
  221. memZero[nextIdx].name = name;
  222. memZero[nextIdx].addr = addr;
  223. memZero[nextIdx].len = len;
  224. nextIdx++;
  225. }
  226. else {
  227. /* Abort when too many entries. */
  228. fprintf(stderr, "\n[MEM_ZERO] Too many addresses to check\n");
  229. fprintf(stderr, "[MEM_ZERO] WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN\n");
  230. abort();
  231. }
  232. wc_UnLockMutex(&zeroMutex);
  233. }
  234. /* Check the memory in the range of the address for memory that must be zero.
  235. *
  236. * @param [in] addr Start address of memory that is to be checked.
  237. * @param [in] len Length of data associated with address.
  238. */
  239. void wc_MemZero_Check(void* addr, size_t len)
  240. {
  241. int i;
  242. size_t j;
  243. wc_LockMutex(&zeroMutex);
  244. /* Look at each address for overlap with address passes in. */
  245. for (i = 0; i < nextIdx; i++) {
  246. if ((memZero[i].addr < addr) ||
  247. ((size_t)memZero[i].addr >= (size_t)addr + len)) {
  248. /* Check address not part of memory to check. */
  249. continue;
  250. }
  251. /* Address is in range of memory being freed - check each byte zero. */
  252. for (j = 0; j < memZero[i].len; j++) {
  253. if (((unsigned char*)memZero[i].addr)[j] != 0) {
  254. /* Byte not zero - abort! */
  255. fprintf(stderr, "\n[MEM_ZERO] %s:%p + %ld is not zero\n",
  256. memZero[i].name, memZero[i].addr, j);
  257. fprintf(stderr, "[MEM_ZERO] Checking %p:%ld\n", addr, len);
  258. abort();
  259. }
  260. }
  261. /* Update next index to write to. */
  262. nextIdx--;
  263. if (nextIdx > 0) {
  264. /* Remove entry. */
  265. XMEMCPY(memZero + i, memZero + i + 1,
  266. sizeof(MemZero) * (nextIdx - i));
  267. /* Clear out top to make it easier to see what is to be checked. */
  268. XMEMSET(&memZero[nextIdx], 0, sizeof(MemZero));
  269. }
  270. /* Need to check this index again with new data. */
  271. i--;
  272. }
  273. wc_UnLockMutex(&zeroMutex);
  274. }
  275. #endif /* WOLFSSL_CHECK_MEM_ZERO */
  276. #ifdef WOLFSSL_DEBUG_MEMORY
  277. void* wolfSSL_Malloc(size_t size, const char* func, unsigned int line)
  278. #else
  279. void* wolfSSL_Malloc(size_t size)
  280. #endif
  281. {
  282. void* res = 0;
  283. #ifdef WOLFSSL_MEM_FAIL_COUNT
  284. if (!wc_MemFailCount_AllocMem()) {
  285. WOLFSSL_MSG("MemFailCnt: Fail malloc");
  286. return NULL;
  287. }
  288. #endif
  289. #ifdef WOLFSSL_CHECK_MEM_ZERO
  290. /* Space for requested size. */
  291. size += MEM_ALIGN;
  292. #endif
  293. if (malloc_function) {
  294. #ifdef WOLFSSL_DEBUG_MEMORY
  295. res = malloc_function(size, func, line);
  296. #else
  297. res = malloc_function(size);
  298. #endif
  299. }
  300. else {
  301. #ifndef WOLFSSL_NO_MALLOC
  302. #ifdef WOLFSSL_TRAP_MALLOC_SZ
  303. if (size > WOLFSSL_TRAP_MALLOC_SZ) {
  304. WOLFSSL_MSG("Malloc too big!");
  305. return NULL;
  306. }
  307. #endif
  308. res = malloc(size);
  309. #else
  310. WOLFSSL_MSG("No malloc available");
  311. #endif
  312. }
  313. #ifdef WOLFSSL_CHECK_MEM_ZERO
  314. /* Restore size to requested value. */
  315. size -= MEM_ALIGN;
  316. if (res != NULL) {
  317. /* Place size at front of allocated data and move pointer passed it. */
  318. *(size_t*)res = size;
  319. res = ((unsigned char*)res) + MEM_ALIGN;
  320. }
  321. #endif
  322. #ifdef WOLFSSL_DEBUG_MEMORY
  323. #if defined(WOLFSSL_DEBUG_MEMORY_PRINT) && !defined(WOLFSSL_TRACK_MEMORY)
  324. fprintf(stderr, "Alloc: %p -> %u at %s:%u\n", res, (word32)size, func, line);
  325. #else
  326. (void)func;
  327. (void)line;
  328. #endif
  329. #endif
  330. #ifdef WOLFSSL_MALLOC_CHECK
  331. if (res == NULL)
  332. WOLFSSL_MSG("wolfSSL_malloc failed");
  333. #endif
  334. #ifdef WOLFSSL_FORCE_MALLOC_FAIL_TEST
  335. if (res && --gMemFailCount == 0) {
  336. fprintf(stderr, "\n---FORCED MEM FAIL TEST---\n");
  337. if (free_function) {
  338. #ifdef WOLFSSL_DEBUG_MEMORY
  339. free_function(res, func, line);
  340. #else
  341. free_function(res);
  342. #endif
  343. }
  344. else {
  345. free(res); /* clear */
  346. }
  347. gMemFailCount = gMemFailCountSeed; /* reset */
  348. return NULL;
  349. }
  350. #endif
  351. return res;
  352. }
  353. #ifdef WOLFSSL_DEBUG_MEMORY
  354. void wolfSSL_Free(void *ptr, const char* func, unsigned int line)
  355. #else
  356. void wolfSSL_Free(void *ptr)
  357. #endif
  358. {
  359. #ifdef WOLFSSL_DEBUG_MEMORY
  360. #if defined(WOLFSSL_DEBUG_MEMORY_PRINT) && !defined(WOLFSSL_TRACK_MEMORY)
  361. fprintf(stderr, "Free: %p at %s:%u\n", ptr, func, line);
  362. #else
  363. (void)func;
  364. (void)line;
  365. #endif
  366. #endif
  367. #ifdef WOLFSSL_CHECK_MEM_ZERO
  368. /* Move pointer back to originally allocated pointer. */
  369. ptr = ((unsigned char*)ptr) - MEM_ALIGN;
  370. /* Check that the pointer is zero where required. */
  371. wc_MemZero_Check(((unsigned char*)ptr) + MEM_ALIGN, *(size_t*)ptr);
  372. #endif
  373. #ifdef WOLFSSL_MEM_FAIL_COUNT
  374. wc_MemFailCount_FreeMem();
  375. #endif
  376. if (free_function) {
  377. #ifdef WOLFSSL_DEBUG_MEMORY
  378. free_function(ptr, func, line);
  379. #else
  380. free_function(ptr);
  381. #endif
  382. }
  383. else {
  384. #ifndef WOLFSSL_NO_MALLOC
  385. free(ptr);
  386. #else
  387. WOLFSSL_MSG("No free available");
  388. #endif
  389. }
  390. }
  391. #ifdef WOLFSSL_DEBUG_MEMORY
  392. void* wolfSSL_Realloc(void *ptr, size_t size, const char* func, unsigned int line)
  393. #else
  394. void* wolfSSL_Realloc(void *ptr, size_t size)
  395. #endif
  396. {
  397. #ifdef WOLFSSL_CHECK_MEM_ZERO
  398. /* Can't check data that has been freed during realloc.
  399. * Manually allocated new memory, copy data and free original pointer.
  400. */
  401. #ifdef WOLFSSL_DEBUG_MEMORY
  402. void* res = wolfSSL_Malloc(size, func, line);
  403. #else
  404. void* res = wolfSSL_Malloc(size);
  405. #endif
  406. if (ptr != NULL) {
  407. /* Copy the minimum of old and new size. */
  408. size_t copySize = *(size_t*)(((unsigned char*)ptr) - MEM_ALIGN);
  409. if (size < copySize) {
  410. copySize = size;
  411. }
  412. XMEMCPY(res, ptr, copySize);
  413. /* Dispose of old pointer. */
  414. #ifdef WOLFSSL_DEBUG_MEMORY
  415. wolfSSL_Free(ptr, func, line);
  416. #else
  417. wolfSSL_Free(ptr);
  418. #endif
  419. }
  420. /* Return new pointer with data copied into it. */
  421. return res;
  422. #else
  423. void* res = 0;
  424. #ifdef WOLFSSL_MEM_FAIL_COUNT
  425. if (!wc_MemFailCount_AllocMem()) {
  426. WOLFSSL_MSG("MemFailCnt: Fail realloc");
  427. return NULL;
  428. }
  429. #endif
  430. if (realloc_function) {
  431. #ifdef WOLFSSL_DEBUG_MEMORY
  432. res = realloc_function(ptr, size, func, line);
  433. #else
  434. res = realloc_function(ptr, size);
  435. #endif
  436. }
  437. else {
  438. #ifndef WOLFSSL_NO_MALLOC
  439. res = realloc(ptr, size);
  440. #else
  441. WOLFSSL_MSG("No realloc available");
  442. #endif
  443. }
  444. #ifdef WOLFSSL_MEM_FAIL_COUNT
  445. if (ptr != NULL) {
  446. wc_MemFailCount_FreeMem();
  447. }
  448. #endif
  449. return res;
  450. #endif
  451. }
  452. #endif /* WOLFSSL_STATIC_MEMORY */
  453. #ifdef WOLFSSL_STATIC_MEMORY
  454. struct wc_Memory {
  455. byte* buffer;
  456. struct wc_Memory* next;
  457. word32 sz;
  458. };
  459. /* returns amount of memory used on success. On error returns negative value
  460. wc_Memory** list is the list that new buckets are prepended to
  461. */
  462. static int create_memory_buckets(byte* buffer, word32 bufSz,
  463. word32 buckSz, word32 buckNum, wc_Memory** list) {
  464. word32 i;
  465. byte* pt = buffer;
  466. int ret = 0;
  467. word32 memSz = (word32)sizeof(wc_Memory);
  468. word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1);
  469. /* if not enough space available for bucket size then do not try */
  470. if (buckSz + memSz + padSz > bufSz) {
  471. return ret;
  472. }
  473. for (i = 0; i < buckNum; i++) {
  474. if ((buckSz + memSz + padSz) <= (bufSz - ret)) {
  475. /* create a new struct and set its values */
  476. wc_Memory* mem = (struct wc_Memory*)(pt);
  477. mem->sz = buckSz;
  478. mem->buffer = (byte*)pt + padSz + memSz;
  479. mem->next = NULL;
  480. /* add the newly created struct to front of list */
  481. if (*list == NULL) {
  482. *list = mem;
  483. } else {
  484. mem->next = *list;
  485. *list = mem;
  486. }
  487. /* advance pointer and keep track of memory used */
  488. ret += buckSz + padSz + memSz;
  489. pt += buckSz + padSz + memSz;
  490. }
  491. else {
  492. break; /* not enough space left for more buckets of this size */
  493. }
  494. }
  495. return ret;
  496. }
  497. int wolfSSL_init_memory_heap(WOLFSSL_HEAP* heap)
  498. {
  499. word32 wc_MemSz[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_BUCKETS };
  500. word32 wc_Dist[WOLFMEM_DEF_BUCKETS] = { WOLFMEM_DIST };
  501. if (heap == NULL) {
  502. return BAD_FUNC_ARG;
  503. }
  504. XMEMSET(heap, 0, sizeof(WOLFSSL_HEAP));
  505. XMEMCPY(heap->sizeList, wc_MemSz, sizeof(wc_MemSz));
  506. XMEMCPY(heap->distList, wc_Dist, sizeof(wc_Dist));
  507. if (wc_InitMutex(&(heap->memory_mutex)) != 0) {
  508. WOLFSSL_MSG("Error creating heap memory mutex");
  509. return BAD_MUTEX_E;
  510. }
  511. return 0;
  512. }
  513. int wc_LoadStaticMemory(WOLFSSL_HEAP_HINT** pHint,
  514. unsigned char* buf, unsigned int sz, int flag, int maxSz)
  515. {
  516. int ret;
  517. WOLFSSL_HEAP* heap;
  518. WOLFSSL_HEAP_HINT* hint;
  519. word32 idx = 0;
  520. if (pHint == NULL || buf == NULL) {
  521. return BAD_FUNC_ARG;
  522. }
  523. if ((sizeof(WOLFSSL_HEAP) + sizeof(WOLFSSL_HEAP_HINT)) > sz - idx) {
  524. return BUFFER_E; /* not enough memory for structures */
  525. }
  526. /* check if hint has already been assigned */
  527. if (*pHint == NULL) {
  528. heap = (WOLFSSL_HEAP*)buf;
  529. idx += sizeof(WOLFSSL_HEAP);
  530. hint = (WOLFSSL_HEAP_HINT*)(buf + idx);
  531. idx += sizeof(WOLFSSL_HEAP_HINT);
  532. ret = wolfSSL_init_memory_heap(heap);
  533. if (ret != 0) {
  534. return ret;
  535. }
  536. XMEMSET(hint, 0, sizeof(WOLFSSL_HEAP_HINT));
  537. hint->memory = heap;
  538. }
  539. else {
  540. #ifdef WOLFSSL_HEAP_TEST
  541. /* do not load in memory if test has been set */
  542. if (heap == (void*)WOLFSSL_HEAP_TEST) {
  543. return 0;
  544. }
  545. #endif
  546. hint = (WOLFSSL_HEAP_HINT*)(*pHint);
  547. heap = hint->memory;
  548. }
  549. ret = wolfSSL_load_static_memory(buf + idx, sz - idx, flag, heap);
  550. if (ret != 1) {
  551. WOLFSSL_MSG("Error partitioning memory");
  552. return -1;
  553. }
  554. /* determine what max applies too */
  555. if ((flag & WOLFMEM_IO_POOL) || (flag & WOLFMEM_IO_POOL_FIXED)) {
  556. heap->maxIO = maxSz;
  557. }
  558. else { /* general memory used in handshakes */
  559. heap->maxHa = maxSz;
  560. }
  561. heap->flag |= flag;
  562. *pHint = hint;
  563. (void)maxSz;
  564. return 0;
  565. }
  566. int wolfSSL_load_static_memory(byte* buffer, word32 sz, int flag,
  567. WOLFSSL_HEAP* heap)
  568. {
  569. word32 ava = sz;
  570. byte* pt = buffer;
  571. int ret = 0;
  572. word32 memSz = (word32)sizeof(wc_Memory);
  573. word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1);
  574. WOLFSSL_ENTER("wolfSSL_load_static_memory");
  575. if (buffer == NULL) {
  576. return BAD_FUNC_ARG;
  577. }
  578. /* align pt */
  579. while ((wc_ptr_t)pt % WOLFSSL_STATIC_ALIGN && pt < (buffer + sz)) {
  580. *pt = 0x00;
  581. pt++;
  582. ava--;
  583. }
  584. #ifdef WOLFSSL_DEBUG_MEMORY
  585. fprintf(stderr, "Allocated %d bytes for static memory @ %p\n", ava, pt);
  586. #endif
  587. /* divide into chunks of memory and add them to available list */
  588. while (ava >= (heap->sizeList[0] + padSz + memSz)) {
  589. /* creating only IO buffers from memory passed in, max TLS is 16k */
  590. if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) {
  591. if ((ret = create_memory_buckets(pt, ava,
  592. WOLFMEM_IO_SZ, 1, &(heap->io))) < 0) {
  593. WOLFSSL_LEAVE("wolfSSL_load_static_memory", ret);
  594. return ret;
  595. }
  596. /* check if no more room left for creating IO buffers */
  597. if (ret == 0) {
  598. break;
  599. }
  600. /* advance pointer in buffer for next buckets and keep track
  601. of how much memory is left available */
  602. pt += ret;
  603. ava -= ret;
  604. }
  605. else {
  606. int i;
  607. /* start at largest and move to smaller buckets */
  608. for (i = (WOLFMEM_MAX_BUCKETS - 1); i >= 0; i--) {
  609. if ((heap->sizeList[i] + padSz + memSz) <= ava) {
  610. if ((ret = create_memory_buckets(pt, ava, heap->sizeList[i],
  611. heap->distList[i], &(heap->ava[i]))) < 0) {
  612. WOLFSSL_LEAVE("wolfSSL_load_static_memory", ret);
  613. return ret;
  614. }
  615. /* advance pointer in buffer for next buckets and keep track
  616. of how much memory is left available */
  617. pt += ret;
  618. ava -= ret;
  619. }
  620. }
  621. }
  622. }
  623. return 1;
  624. }
  625. /* returns the size of management memory needed for each bucket.
  626. * This is memory that is used to keep track of and align memory buckets. */
  627. int wolfSSL_MemoryPaddingSz(void)
  628. {
  629. word32 memSz = (word32)sizeof(wc_Memory);
  630. word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1);
  631. return memSz + padSz;
  632. }
  633. /* Used to calculate memory size for optimum use with buckets.
  634. returns the suggested size rounded down to the nearest bucket. */
  635. int wolfSSL_StaticBufferSz(byte* buffer, word32 sz, int flag)
  636. {
  637. word32 bucketSz[WOLFMEM_MAX_BUCKETS] = {WOLFMEM_BUCKETS};
  638. word32 distList[WOLFMEM_MAX_BUCKETS] = {WOLFMEM_DIST};
  639. word32 ava = sz;
  640. byte* pt = buffer;
  641. word32 memSz = (word32)sizeof(wc_Memory);
  642. word32 padSz = -(int)memSz & (WOLFSSL_STATIC_ALIGN - 1);
  643. WOLFSSL_ENTER("wolfSSL_static_size");
  644. if (buffer == NULL) {
  645. return BAD_FUNC_ARG;
  646. }
  647. /* align pt */
  648. while ((wc_ptr_t)pt % WOLFSSL_STATIC_ALIGN && pt < (buffer + sz)) {
  649. pt++;
  650. ava--;
  651. }
  652. /* creating only IO buffers from memory passed in, max TLS is 16k */
  653. if (flag & WOLFMEM_IO_POOL || flag & WOLFMEM_IO_POOL_FIXED) {
  654. if (ava < (memSz + padSz + WOLFMEM_IO_SZ)) {
  655. return 0; /* not enough room for even one bucket */
  656. }
  657. ava = ava % (memSz + padSz + WOLFMEM_IO_SZ);
  658. }
  659. else {
  660. int i, k;
  661. if (ava < (bucketSz[0] + padSz + memSz)) {
  662. return 0; /* not enough room for even one bucket */
  663. }
  664. while ((ava >= (bucketSz[0] + padSz + memSz)) && (ava > 0)) {
  665. /* start at largest and move to smaller buckets */
  666. for (i = (WOLFMEM_MAX_BUCKETS - 1); i >= 0; i--) {
  667. for (k = distList[i]; k > 0; k--) {
  668. if ((bucketSz[i] + padSz + memSz) <= ava) {
  669. ava -= bucketSz[i] + padSz + memSz;
  670. }
  671. }
  672. }
  673. }
  674. }
  675. return sz - ava; /* round down */
  676. }
  677. int FreeFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io)
  678. {
  679. WOLFSSL_MSG("Freeing fixed IO buffer");
  680. /* check if fixed buffer was set */
  681. if (*io == NULL) {
  682. return 1;
  683. }
  684. if (heap == NULL) {
  685. WOLFSSL_MSG("No heap to return fixed IO too");
  686. }
  687. else {
  688. /* put IO buffer back into IO pool */
  689. (*io)->next = heap->io;
  690. heap->io = *io;
  691. *io = NULL;
  692. }
  693. return 1;
  694. }
  695. int SetFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io)
  696. {
  697. WOLFSSL_MSG("Setting fixed IO for SSL");
  698. if (heap == NULL) {
  699. return MEMORY_E;
  700. }
  701. *io = heap->io;
  702. if (*io != NULL) {
  703. heap->io = (*io)->next;
  704. (*io)->next = NULL;
  705. }
  706. else { /* failed to grab an IO buffer */
  707. return 0;
  708. }
  709. return 1;
  710. }
  711. int wolfSSL_GetMemStats(WOLFSSL_HEAP* heap, WOLFSSL_MEM_STATS* stats)
  712. {
  713. word32 i;
  714. wc_Memory* pt;
  715. XMEMSET(stats, 0, sizeof(WOLFSSL_MEM_STATS));
  716. stats->totalAlloc = heap->alloc;
  717. stats->totalFr = heap->frAlc;
  718. stats->curAlloc = stats->totalAlloc - stats->totalFr;
  719. stats->maxHa = heap->maxHa;
  720. stats->maxIO = heap->maxIO;
  721. for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
  722. stats->blockSz[i] = heap->sizeList[i];
  723. for (pt = heap->ava[i]; pt != NULL; pt = pt->next) {
  724. stats->avaBlock[i] += 1;
  725. }
  726. }
  727. for (pt = heap->io; pt != NULL; pt = pt->next) {
  728. stats->avaIO++;
  729. }
  730. stats->flag = heap->flag; /* flag used */
  731. return 1;
  732. }
  733. #ifdef WOLFSSL_DEBUG_MEMORY
  734. void* wolfSSL_Malloc(size_t size, void* heap, int type, const char* func, unsigned int line)
  735. #else
  736. void* wolfSSL_Malloc(size_t size, void* heap, int type)
  737. #endif
  738. {
  739. void* res = 0;
  740. wc_Memory* pt = NULL;
  741. int i;
  742. /* check for testing heap hint was set */
  743. #ifdef WOLFSSL_HEAP_TEST
  744. if (heap == (void*)WOLFSSL_HEAP_TEST) {
  745. return malloc(size);
  746. }
  747. #endif
  748. /* if no heap hint then use dynamic memory*/
  749. if (heap == NULL) {
  750. #ifdef WOLFSSL_HEAP_TEST
  751. /* allow using malloc for creating ctx and method */
  752. if (type == DYNAMIC_TYPE_CTX || type == DYNAMIC_TYPE_METHOD ||
  753. type == DYNAMIC_TYPE_CERT_MANAGER) {
  754. WOLFSSL_MSG("ERROR allowing null heap hint for ctx/method");
  755. res = malloc(size);
  756. }
  757. else {
  758. WOLFSSL_MSG("ERROR null heap hint passed into XMALLOC");
  759. res = NULL;
  760. }
  761. #else
  762. #ifndef WOLFSSL_NO_MALLOC
  763. #ifdef FREERTOS
  764. res = pvPortMalloc(size);
  765. #elif defined(WOLFSSL_EMBOS)
  766. res = OS_HEAP_malloc(size);
  767. #else
  768. res = malloc(size);
  769. #endif
  770. #ifdef WOLFSSL_DEBUG_MEMORY
  771. fprintf(stderr, "Alloc: %p -> %u at %s:%d\n", res, (word32)size, func, line);
  772. #endif
  773. #else
  774. WOLFSSL_MSG("No heap hint found to use and no malloc");
  775. #ifdef WOLFSSL_DEBUG_MEMORY
  776. fprintf(stderr, "ERROR: at %s:%d\n", func, line);
  777. #endif
  778. #endif /* WOLFSSL_NO_MALLOC */
  779. #endif /* WOLFSSL_HEAP_TEST */
  780. }
  781. else {
  782. WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap;
  783. WOLFSSL_HEAP* mem = hint->memory;
  784. if (wc_LockMutex(&(mem->memory_mutex)) != 0) {
  785. WOLFSSL_MSG("Bad memory_mutex lock");
  786. return NULL;
  787. }
  788. /* case of using fixed IO buffers */
  789. if (mem->flag & WOLFMEM_IO_POOL_FIXED &&
  790. (type == DYNAMIC_TYPE_OUT_BUFFER ||
  791. type == DYNAMIC_TYPE_IN_BUFFER)) {
  792. if (type == DYNAMIC_TYPE_OUT_BUFFER) {
  793. pt = hint->outBuf;
  794. }
  795. if (type == DYNAMIC_TYPE_IN_BUFFER) {
  796. pt = hint->inBuf;
  797. }
  798. }
  799. else {
  800. /* check if using IO pool flag */
  801. if (mem->flag & WOLFMEM_IO_POOL &&
  802. (type == DYNAMIC_TYPE_OUT_BUFFER ||
  803. type == DYNAMIC_TYPE_IN_BUFFER)) {
  804. if (mem->io != NULL) {
  805. pt = mem->io;
  806. mem->io = pt->next;
  807. }
  808. }
  809. /* general static memory */
  810. if (pt == NULL) {
  811. for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
  812. if ((word32)size <= mem->sizeList[i]) {
  813. if (mem->ava[i] != NULL) {
  814. pt = mem->ava[i];
  815. mem->ava[i] = pt->next;
  816. break;
  817. }
  818. #ifdef WOLFSSL_DEBUG_STATIC_MEMORY
  819. else {
  820. fprintf(stderr, "Size: %ld, Empty: %d\n", size,
  821. mem->sizeList[i]);
  822. }
  823. #endif
  824. }
  825. }
  826. }
  827. }
  828. if (pt != NULL) {
  829. mem->inUse += pt->sz;
  830. mem->alloc += 1;
  831. res = pt->buffer;
  832. #ifdef WOLFSSL_DEBUG_MEMORY
  833. fprintf(stderr, "Alloc: %p -> %u at %s:%d\n", pt->buffer, pt->sz, func, line);
  834. #endif
  835. /* keep track of connection statistics if flag is set */
  836. if (mem->flag & WOLFMEM_TRACK_STATS) {
  837. WOLFSSL_MEM_CONN_STATS* stats = hint->stats;
  838. if (stats != NULL) {
  839. stats->curMem += pt->sz;
  840. if (stats->peakMem < stats->curMem) {
  841. stats->peakMem = stats->curMem;
  842. }
  843. stats->curAlloc++;
  844. if (stats->peakAlloc < stats->curAlloc) {
  845. stats->peakAlloc = stats->curAlloc;
  846. }
  847. stats->totalAlloc++;
  848. }
  849. }
  850. }
  851. else {
  852. WOLFSSL_MSG("ERROR ran out of static memory");
  853. #ifdef WOLFSSL_DEBUG_MEMORY
  854. fprintf(stderr, "Looking for %lu bytes at %s:%d\n", size, func, line);
  855. #endif
  856. }
  857. wc_UnLockMutex(&(mem->memory_mutex));
  858. }
  859. #ifdef WOLFSSL_MALLOC_CHECK
  860. if ((wc_ptr_t)res % WOLFSSL_STATIC_ALIGN) {
  861. WOLFSSL_MSG("ERROR memory is not aligned");
  862. res = NULL;
  863. }
  864. #endif
  865. (void)i;
  866. (void)pt;
  867. (void)type;
  868. return res;
  869. }
  870. #ifdef WOLFSSL_DEBUG_MEMORY
  871. void wolfSSL_Free(void *ptr, void* heap, int type, const char* func, unsigned int line)
  872. #else
  873. void wolfSSL_Free(void *ptr, void* heap, int type)
  874. #endif
  875. {
  876. int i;
  877. wc_Memory* pt;
  878. if (ptr) {
  879. /* check for testing heap hint was set */
  880. #ifdef WOLFSSL_HEAP_TEST
  881. if (heap == (void*)WOLFSSL_HEAP_TEST) {
  882. #ifdef WOLFSSL_DEBUG_MEMORY
  883. fprintf(stderr, "Free: %p at %s:%d\n", pt, func, line);
  884. #endif
  885. return free(ptr);
  886. }
  887. #endif
  888. if (heap == NULL) {
  889. #ifdef WOLFSSL_HEAP_TEST
  890. /* allow using malloc for creating ctx and method */
  891. if (type == DYNAMIC_TYPE_CTX || type == DYNAMIC_TYPE_METHOD ||
  892. type == DYNAMIC_TYPE_CERT_MANAGER) {
  893. WOLFSSL_MSG("ERROR allowing null heap hint for ctx/method");
  894. }
  895. else {
  896. WOLFSSL_MSG("ERROR null heap hint passed into XFREE");
  897. }
  898. #endif
  899. #ifndef WOLFSSL_NO_MALLOC
  900. #ifdef FREERTOS
  901. vPortFree(ptr);
  902. #elif defined(WOLFSSL_EMBOS)
  903. OS_HEAP_free(ptr);
  904. #else
  905. free(ptr);
  906. #endif
  907. #else
  908. WOLFSSL_MSG("Error trying to call free when turned off");
  909. #endif /* WOLFSSL_NO_MALLOC */
  910. }
  911. else {
  912. WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap;
  913. WOLFSSL_HEAP* mem = hint->memory;
  914. word32 padSz = -(int)sizeof(wc_Memory) & (WOLFSSL_STATIC_ALIGN - 1);
  915. /* get memory struct and add it to available list */
  916. pt = (wc_Memory*)((byte*)ptr - sizeof(wc_Memory) - padSz);
  917. if (wc_LockMutex(&(mem->memory_mutex)) != 0) {
  918. WOLFSSL_MSG("Bad memory_mutex lock");
  919. return;
  920. }
  921. /* case of using fixed IO buffers */
  922. if (mem->flag & WOLFMEM_IO_POOL_FIXED &&
  923. (type == DYNAMIC_TYPE_OUT_BUFFER ||
  924. type == DYNAMIC_TYPE_IN_BUFFER)) {
  925. /* fixed IO pools are free'd at the end of SSL lifetime
  926. using FreeFixedIO(WOLFSSL_HEAP* heap, wc_Memory** io) */
  927. }
  928. else if (mem->flag & WOLFMEM_IO_POOL && pt->sz == WOLFMEM_IO_SZ &&
  929. (type == DYNAMIC_TYPE_OUT_BUFFER ||
  930. type == DYNAMIC_TYPE_IN_BUFFER)) {
  931. pt->next = mem->io;
  932. mem->io = pt;
  933. }
  934. else { /* general memory free */
  935. for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
  936. if (pt->sz == mem->sizeList[i]) {
  937. pt->next = mem->ava[i];
  938. mem->ava[i] = pt;
  939. break;
  940. }
  941. }
  942. }
  943. mem->inUse -= pt->sz;
  944. mem->frAlc += 1;
  945. #ifdef WOLFSSL_DEBUG_MEMORY
  946. fprintf(stderr, "Free: %p -> %u at %s:%d\n", pt->buffer, pt->sz, func, line);
  947. #endif
  948. /* keep track of connection statistics if flag is set */
  949. if (mem->flag & WOLFMEM_TRACK_STATS) {
  950. WOLFSSL_MEM_CONN_STATS* stats = hint->stats;
  951. if (stats != NULL) {
  952. /* avoid under flow */
  953. if (stats->curMem > pt->sz) {
  954. stats->curMem -= pt->sz;
  955. }
  956. else {
  957. stats->curMem = 0;
  958. }
  959. if (stats->curAlloc > 0) {
  960. stats->curAlloc--;
  961. }
  962. stats->totalFr++;
  963. }
  964. }
  965. wc_UnLockMutex(&(mem->memory_mutex));
  966. }
  967. }
  968. (void)i;
  969. (void)pt;
  970. (void)type;
  971. }
  972. #ifdef WOLFSSL_DEBUG_MEMORY
  973. void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type, const char* func, unsigned int line)
  974. #else
  975. void* wolfSSL_Realloc(void *ptr, size_t size, void* heap, int type)
  976. #endif
  977. {
  978. void* res = 0;
  979. wc_Memory* pt = NULL;
  980. int i;
  981. /* check for testing heap hint was set */
  982. #ifdef WOLFSSL_HEAP_TEST
  983. if (heap == (void*)WOLFSSL_HEAP_TEST) {
  984. return realloc(ptr, size);
  985. }
  986. #endif
  987. if (heap == NULL) {
  988. #ifdef WOLFSSL_HEAP_TEST
  989. WOLFSSL_MSG("ERROR null heap hint passed in to XREALLOC");
  990. #endif
  991. #ifndef WOLFSSL_NO_MALLOC
  992. res = realloc(ptr, size);
  993. #else
  994. WOLFSSL_MSG("NO heap found to use for realloc");
  995. #endif /* WOLFSSL_NO_MALLOC */
  996. }
  997. else {
  998. WOLFSSL_HEAP_HINT* hint = (WOLFSSL_HEAP_HINT*)heap;
  999. WOLFSSL_HEAP* mem = hint->memory;
  1000. word32 padSz = -(int)sizeof(wc_Memory) & (WOLFSSL_STATIC_ALIGN - 1);
  1001. if (ptr == NULL) {
  1002. #ifdef WOLFSSL_DEBUG_MEMORY
  1003. return wolfSSL_Malloc(size, heap, type, func, line);
  1004. #else
  1005. return wolfSSL_Malloc(size, heap, type);
  1006. #endif
  1007. }
  1008. if (wc_LockMutex(&(mem->memory_mutex)) != 0) {
  1009. WOLFSSL_MSG("Bad memory_mutex lock");
  1010. return NULL;
  1011. }
  1012. /* case of using fixed IO buffers or IO pool */
  1013. if (((mem->flag & WOLFMEM_IO_POOL)||(mem->flag & WOLFMEM_IO_POOL_FIXED))
  1014. && (type == DYNAMIC_TYPE_OUT_BUFFER ||
  1015. type == DYNAMIC_TYPE_IN_BUFFER)) {
  1016. /* no realloc, is fixed size */
  1017. pt = (wc_Memory*)((byte*)ptr - padSz - sizeof(wc_Memory));
  1018. if (pt->sz < size) {
  1019. WOLFSSL_MSG("Error IO memory was not large enough");
  1020. res = NULL; /* return NULL in error case */
  1021. }
  1022. res = pt->buffer;
  1023. }
  1024. else {
  1025. /* general memory */
  1026. for (i = 0; i < WOLFMEM_MAX_BUCKETS; i++) {
  1027. if ((word32)size <= mem->sizeList[i]) {
  1028. if (mem->ava[i] != NULL) {
  1029. pt = mem->ava[i];
  1030. mem->ava[i] = pt->next;
  1031. break;
  1032. }
  1033. }
  1034. }
  1035. if (pt != NULL && res == NULL) {
  1036. res = pt->buffer;
  1037. /* copy over original information and free ptr */
  1038. word32 prvSz = ((wc_Memory*)((byte*)ptr - padSz -
  1039. sizeof(wc_Memory)))->sz;
  1040. prvSz = (prvSz > pt->sz)? pt->sz: prvSz;
  1041. XMEMCPY(pt->buffer, ptr, prvSz);
  1042. mem->inUse += pt->sz;
  1043. mem->alloc += 1;
  1044. /* free memory that was previously being used */
  1045. wc_UnLockMutex(&(mem->memory_mutex));
  1046. wolfSSL_Free(ptr, heap, type
  1047. #ifdef WOLFSSL_DEBUG_MEMORY
  1048. , func, line
  1049. #endif
  1050. );
  1051. if (wc_LockMutex(&(mem->memory_mutex)) != 0) {
  1052. WOLFSSL_MSG("Bad memory_mutex lock");
  1053. return NULL;
  1054. }
  1055. }
  1056. }
  1057. wc_UnLockMutex(&(mem->memory_mutex));
  1058. }
  1059. #ifdef WOLFSSL_MALLOC_CHECK
  1060. if ((wc_ptr_t)res % WOLFSSL_STATIC_ALIGN) {
  1061. WOLFSSL_MSG("ERROR memory is not aligned");
  1062. res = NULL;
  1063. }
  1064. #endif
  1065. (void)i;
  1066. (void)pt;
  1067. (void)type;
  1068. return res;
  1069. }
  1070. #endif /* WOLFSSL_STATIC_MEMORY */
  1071. #endif /* USE_WOLFSSL_MEMORY */
  1072. #ifdef HAVE_IO_POOL
  1073. /* Example for user io pool, shared build may need definitions in lib proper */
  1074. #include <stdlib.h>
  1075. #ifndef HAVE_THREAD_LS
  1076. #error "Oops, simple I/O pool example needs thread local storage"
  1077. #endif
  1078. /* allow simple per thread in and out pools */
  1079. /* use 17k size since max record size is 16k plus overhead */
  1080. static THREAD_LS_T byte pool_in[17*1024];
  1081. static THREAD_LS_T byte pool_out[17*1024];
  1082. void* XMALLOC(size_t n, void* heap, int type)
  1083. {
  1084. (void)heap;
  1085. if (type == DYNAMIC_TYPE_IN_BUFFER) {
  1086. if (n < sizeof(pool_in))
  1087. return pool_in;
  1088. else
  1089. return NULL;
  1090. }
  1091. if (type == DYNAMIC_TYPE_OUT_BUFFER) {
  1092. if (n < sizeof(pool_out))
  1093. return pool_out;
  1094. else
  1095. return NULL;
  1096. }
  1097. return malloc(n);
  1098. }
  1099. void* XREALLOC(void *p, size_t n, void* heap, int type)
  1100. {
  1101. (void)heap;
  1102. if (type == DYNAMIC_TYPE_IN_BUFFER) {
  1103. if (n < sizeof(pool_in))
  1104. return pool_in;
  1105. else
  1106. return NULL;
  1107. }
  1108. if (type == DYNAMIC_TYPE_OUT_BUFFER) {
  1109. if (n < sizeof(pool_out))
  1110. return pool_out;
  1111. else
  1112. return NULL;
  1113. }
  1114. return realloc(p, n);
  1115. }
  1116. void XFREE(void *p, void* heap, int type)
  1117. {
  1118. (void)heap;
  1119. if (type == DYNAMIC_TYPE_IN_BUFFER)
  1120. return; /* do nothing, static pool */
  1121. if (type == DYNAMIC_TYPE_OUT_BUFFER)
  1122. return; /* do nothing, static pool */
  1123. free(p);
  1124. }
  1125. #endif /* HAVE_IO_POOL */
  1126. #ifdef WOLFSSL_MEMORY_LOG
  1127. void *xmalloc(size_t n, void* heap, int type, const char* func,
  1128. const char* file, unsigned int line)
  1129. {
  1130. void* p = NULL;
  1131. word32* p32;
  1132. #ifdef WOLFSSL_MEM_FAIL_COUNT
  1133. if (!wc_MemFailCount_AllocMem()) {
  1134. WOLFSSL_MSG("MemFailCnt: Fail malloc");
  1135. return NULL;
  1136. }
  1137. #endif
  1138. if (malloc_function) {
  1139. #ifndef WOLFSSL_STATIC_MEMORY
  1140. p32 = malloc_function(n + sizeof(word32) * 4);
  1141. #else
  1142. p32 = malloc_function(n + sizeof(word32) * 4, heap, type);
  1143. #endif
  1144. }
  1145. else
  1146. p32 = malloc(n + sizeof(word32) * 4);
  1147. if (p32 != NULL) {
  1148. p32[0] = (word32)n;
  1149. p = (void*)(p32 + 4);
  1150. fprintf(stderr, "Alloc: %p -> %u (%d) at %s:%s:%u\n", p, (word32)n,
  1151. type, func, file, line);
  1152. }
  1153. (void)heap;
  1154. return p;
  1155. }
  1156. void *xrealloc(void *p, size_t n, void* heap, int type, const char* func,
  1157. const char* file, unsigned int line)
  1158. {
  1159. void* newp = NULL;
  1160. word32* p32;
  1161. word32* oldp32 = NULL;
  1162. word32 oldLen;
  1163. #ifdef WOLFSSL_MEM_FAIL_COUNT
  1164. if (!wc_MemFailCount_AllocMem()) {
  1165. WOLFSSL_MSG("MemFailCnt: Fail malloc");
  1166. return NULL;
  1167. }
  1168. #endif
  1169. if (p != NULL) {
  1170. oldp32 = (word32*)p;
  1171. oldp32 -= 4;
  1172. oldLen = oldp32[0];
  1173. }
  1174. if (realloc_function) {
  1175. #ifndef WOLFSSL_STATIC_MEMORY
  1176. p32 = realloc_function(oldp32, n + sizeof(word32) * 4);
  1177. #else
  1178. p32 = realloc_function(oldp32, n + sizeof(word32) * 4, heap, type);
  1179. #endif
  1180. }
  1181. else
  1182. p32 = realloc(oldp32, n + sizeof(word32) * 4);
  1183. if (p32 != NULL) {
  1184. p32[0] = (word32)n;
  1185. newp = (void*)(p32 + 4);
  1186. if (p != NULL) {
  1187. fprintf(stderr, "Free: %p -> %u (%d) at %s:%s:%u\n", p, oldLen,
  1188. type, func, file, line);
  1189. }
  1190. fprintf(stderr, "Alloc: %p -> %u (%d) at %s:%s:%u\n", newp, (word32)n,
  1191. type, func, file, line);
  1192. }
  1193. #ifdef WOLFSSL_MEM_FAIL_COUNT
  1194. if (p != NULL) {
  1195. wc_MemFailCount_FreeMem();
  1196. }
  1197. #endif
  1198. (void)heap;
  1199. return newp;
  1200. }
  1201. void xfree(void *p, void* heap, int type, const char* func, const char* file,
  1202. unsigned int line)
  1203. {
  1204. word32* p32 = (word32*)p;
  1205. if (p != NULL) {
  1206. #ifdef WOLFSSL_MEM_FAIL_COUNT
  1207. wc_MemFailCount_FreeMem();
  1208. #endif
  1209. p32 -= 4;
  1210. fprintf(stderr, "Free: %p -> %u (%d) at %s:%s:%u\n", p, p32[0], type,
  1211. func, file, line);
  1212. if (free_function) {
  1213. #ifndef WOLFSSL_STATIC_MEMORY
  1214. free_function(p32);
  1215. #else
  1216. free_function(p32, heap, type);
  1217. #endif
  1218. }
  1219. else
  1220. free(p32);
  1221. }
  1222. (void)heap;
  1223. }
  1224. #endif /* WOLFSSL_MEMORY_LOG */
  1225. #ifdef WOLFSSL_STACK_LOG
  1226. /* Note: this code only works with GCC using -finstrument-functions. */
  1227. void __attribute__((no_instrument_function))
  1228. __cyg_profile_func_enter(void *func, void *caller)
  1229. {
  1230. register void* sp asm("sp");
  1231. fprintf(stderr, "ENTER: %016lx %p\n", (unsigned long)(wc_ptr_t)func, sp);
  1232. (void)caller;
  1233. }
  1234. void __attribute__((no_instrument_function))
  1235. __cyg_profile_func_exit(void *func, void *caller)
  1236. {
  1237. register void* sp asm("sp");
  1238. fprintf(stderr, "EXIT: %016lx %p\n", (unsigned long)(wc_ptr_t)func, sp);
  1239. (void)caller;
  1240. }
  1241. #endif
  1242. #ifdef WC_DEBUG_CIPHER_LIFECYCLE
  1243. static const byte wc_debug_cipher_lifecycle_tag_value[] =
  1244. { 'W', 'o', 'l', 'f' };
  1245. WOLFSSL_LOCAL int wc_debug_CipherLifecycleInit(
  1246. void **CipherLifecycleTag,
  1247. void *heap)
  1248. {
  1249. if (CipherLifecycleTag == NULL)
  1250. return BAD_FUNC_ARG;
  1251. *CipherLifecycleTag = (void *)XMALLOC(
  1252. sizeof(wc_debug_cipher_lifecycle_tag_value),
  1253. heap,
  1254. DYNAMIC_TYPE_DEBUG_TAG);
  1255. if (*CipherLifecycleTag == NULL)
  1256. return MEMORY_E;
  1257. XMEMCPY(*CipherLifecycleTag,
  1258. wc_debug_cipher_lifecycle_tag_value,
  1259. sizeof(wc_debug_cipher_lifecycle_tag_value));
  1260. return 0;
  1261. }
  1262. WOLFSSL_LOCAL int wc_debug_CipherLifecycleCheck(
  1263. void *CipherLifecycleTag,
  1264. int abort_p)
  1265. {
  1266. int ret;
  1267. if (CipherLifecycleTag == NULL) {
  1268. ret = BAD_STATE_E;
  1269. goto out;
  1270. }
  1271. if (XMEMCMP(CipherLifecycleTag,
  1272. wc_debug_cipher_lifecycle_tag_value,
  1273. sizeof(wc_debug_cipher_lifecycle_tag_value)) != 0)
  1274. {
  1275. ret = BAD_STATE_E;
  1276. goto out;
  1277. }
  1278. ret = 0;
  1279. out:
  1280. if ((ret < 0) && abort_p)
  1281. abort();
  1282. return ret;
  1283. }
  1284. WOLFSSL_LOCAL int wc_debug_CipherLifecycleFree(
  1285. void **CipherLifecycleTag,
  1286. void *heap,
  1287. int abort_p)
  1288. {
  1289. int ret;
  1290. if (CipherLifecycleTag == NULL)
  1291. return BAD_FUNC_ARG;
  1292. ret = wc_debug_CipherLifecycleCheck(*CipherLifecycleTag, abort_p);
  1293. if (ret != 0)
  1294. return ret;
  1295. XFREE(*CipherLifecycleTag, heap, DYNAMIC_TYPE_DEBUG_TAG);
  1296. *CipherLifecycleTag = NULL;
  1297. return 0;
  1298. }
  1299. #endif /* WC_DEBUG_CIPHER_LIFECYCLE */
  1300. #ifdef DEBUG_VECTOR_REGISTER_ACCESS
  1301. THREAD_LS_T int wc_svr_count = 0;
  1302. THREAD_LS_T const char *wc_svr_last_file = NULL;
  1303. THREAD_LS_T int wc_svr_last_line = -1;
  1304. THREAD_LS_T int wc_debug_vector_registers_retval =
  1305. WC_DEBUG_VECTOR_REGISTERS_RETVAL_INITVAL;
  1306. #ifdef DEBUG_VECTOR_REGISTER_ACCESS_FUZZING
  1307. WOLFSSL_LOCAL int SAVE_VECTOR_REGISTERS2_fuzzer(void) {
  1308. static THREAD_LS_T struct drand48_data wc_svr_fuzzing_state;
  1309. static THREAD_LS_T int wc_svr_fuzzing_seeded = 0;
  1310. long result;
  1311. if (wc_debug_vector_registers_retval)
  1312. return wc_debug_vector_registers_retval;
  1313. if (wc_svr_fuzzing_seeded == 0) {
  1314. long seed = WC_DEBUG_VECTOR_REGISTERS_FUZZING_SEED;
  1315. char *seed_envstr = getenv("WC_DEBUG_VECTOR_REGISTERS_FUZZING_SEED");
  1316. if (seed_envstr)
  1317. seed = strtol(seed_envstr, NULL, 0);
  1318. (void)srand48_r(seed, &wc_svr_fuzzing_state);
  1319. wc_svr_fuzzing_seeded = 1;
  1320. }
  1321. (void)lrand48_r(&wc_svr_fuzzing_state, &result);
  1322. if (result & 1)
  1323. return IO_FAILED_E;
  1324. else
  1325. return 0;
  1326. }
  1327. #endif
  1328. #endif
  1329. #ifdef WOLFSSL_LINUXKM
  1330. #include "../../linuxkm/linuxkm_memory.c"
  1331. #endif