memory.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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. #include <wolfssl/wolfcrypt/settings.h>
  25. /* check old macros @wc_fips */
  26. #if defined(USE_CYASSL_MEMORY) && !defined(USE_WOLFSSL_MEMORY)
  27. #define USE_WOLFSSL_MEMORY
  28. #endif
  29. #if defined(CYASSL_MALLOC_CHECK) && !defined(WOLFSSL_MALLOC_CHECK)
  30. #define WOLFSSL_MALLOC_CHECK
  31. #endif
  32. /*
  33. Possible memory options:
  34. * NO_WOLFSSL_MEMORY: Disables wolf memory callback support. When not defined settings.h defines USE_WOLFSSL_MEMORY.
  35. * WOLFSSL_STATIC_MEMORY: Turns on the use of static memory buffers and functions.
  36. This allows for using static memory instead of dynamic.
  37. * WOLFSSL_STATIC_ALIGN: Define defaults to 16 to indicate static memory alignment.
  38. * HAVE_IO_POOL: Enables use of static thread safe memory pool for input/output buffers.
  39. * XMALLOC_OVERRIDE: Allows override of the XMALLOC, XFREE and XREALLOC macros.
  40. * XMALLOC_USER: Allows custom XMALLOC, XFREE and XREALLOC functions to be defined.
  41. * WOLFSSL_NO_MALLOC: Disables the fall-back case to use STDIO malloc/free when no callbacks are set.
  42. * WOLFSSL_TRACK_MEMORY: Enables memory tracking for total stats and list of allocated memory.
  43. * WOLFSSL_DEBUG_MEMORY: Enables extra function and line number args for memory callbacks.
  44. * WOLFSSL_DEBUG_MEMORY_PRINT: Enables printing of each malloc/free.
  45. * WOLFSSL_MALLOC_CHECK: Reports malloc or alignment failure using WOLFSSL_STATIC_ALIGN
  46. * WOLFSSL_FORCE_MALLOC_FAIL_TEST: Used for internal testing to induce random malloc failures.
  47. * WOLFSSL_HEAP_TEST: Used for internal testing of heap hint
  48. * WOLFSSL_MEM_FAIL_COUNT: Fail memory allocation at a count from
  49. * environment variable: MEM_FAIL_CNT.
  50. */
  51. #ifdef WOLFSSL_ZEPHYR
  52. #undef realloc
  53. void *z_realloc(void *ptr, size_t size)
  54. {
  55. if (ptr == NULL)
  56. ptr = malloc(size);
  57. else
  58. ptr = realloc(ptr, size);
  59. return ptr;
  60. }
  61. #define realloc z_realloc
  62. #endif
  63. #ifdef USE_WOLFSSL_MEMORY
  64. #include <wolfssl/wolfcrypt/memory.h>
  65. #include <wolfssl/wolfcrypt/error-crypt.h>
  66. #include <wolfssl/wolfcrypt/logging.h>
  67. #if defined(WOLFSSL_DEBUG_MEMORY) && defined(WOLFSSL_DEBUG_MEMORY_PRINT)
  68. #include <stdio.h>
  69. #endif
  70. #ifdef WOLFSSL_FORCE_MALLOC_FAIL_TEST
  71. static int gMemFailCountSeed;
  72. static int gMemFailCount;
  73. void wolfSSL_SetMemFailCount(int memFailCount)
  74. {
  75. if (gMemFailCountSeed == 0) {
  76. gMemFailCountSeed = memFailCount;
  77. gMemFailCount = memFailCount;
  78. }
  79. }
  80. #endif
  81. #if defined(WOLFSSL_MALLOC_CHECK) || defined(WOLFSSL_TRACK_MEMORY_FULL) || \
  82. defined(WOLFSSL_MEMORY_LOG)
  83. #include <stdio.h>
  84. #endif
  85. /* Set these to default values initially. */
  86. static wolfSSL_Malloc_cb malloc_function = NULL;
  87. static wolfSSL_Free_cb free_function = NULL;
  88. static wolfSSL_Realloc_cb realloc_function = NULL;
  89. int wolfSSL_SetAllocators(wolfSSL_Malloc_cb mf,
  90. wolfSSL_Free_cb ff,
  91. wolfSSL_Realloc_cb rf)
  92. {
  93. malloc_function = mf;
  94. free_function = ff;
  95. realloc_function = rf;
  96. return 0;
  97. }
  98. int wolfSSL_GetAllocators(wolfSSL_Malloc_cb* mf,
  99. wolfSSL_Free_cb* ff,
  100. wolfSSL_Realloc_cb* rf)
  101. {
  102. if (mf) *mf = malloc_function;
  103. if (ff) *ff = free_function;
  104. if (rf) *rf = realloc_function;
  105. return 0;
  106. }
  107. #ifndef WOLFSSL_STATIC_MEMORY
  108. #ifdef WOLFSSL_CHECK_MEM_ZERO
  109. #ifndef WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN
  110. /* Number of entries in table of addresses to check. */
  111. #define WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN 256
  112. #endif
  113. /* Alignment to maintain when adding length to allocated pointer.
  114. * Intel x64 wants to use aligned loads of XMM registers.
  115. */
  116. #define MEM_ALIGN 16
  117. /* An address that is meant to be all zeros for its length. */
  118. typedef struct MemZero {
  119. /* Name of address to check. */
  120. const char* name;
  121. /* Address to check. */
  122. const void* addr;
  123. /* Length of data that must be zero. */
  124. size_t len;
  125. } MemZero;
  126. /* List of addresses to check. */
  127. static MemZero memZero[WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN];
  128. /* Next index to place address at.
  129. * -1 indicates uninitialized.
  130. * If nextIdx is equal to WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN then all entries
  131. * have been used.
  132. */
  133. static int nextIdx = -1;
  134. /* Mutex to protect modifying list of addresses to check. */
  135. static wolfSSL_Mutex zeroMutex;
  136. /* Initialize the table of addresses and the mutex.
  137. */
  138. void wc_MemZero_Init()
  139. {
  140. /* Clear the table to more easily see what is valid. */
  141. XMEMSET(memZero, 0, sizeof(memZero));
  142. /* Initialize mutex. */
  143. wc_InitMutex(&zeroMutex);
  144. /* Next index is first entry. */
  145. nextIdx = 0;
  146. }
  147. /* Free the mutex and check we have not any uncheck addresses.
  148. */
  149. void wc_MemZero_Free()
  150. {
  151. /* Free mutex. */
  152. wc_FreeMutex(&zeroMutex);
  153. /* Make sure we checked all addresses. */
  154. if (nextIdx > 0) {
  155. int i;
  156. fprintf(stderr, "[MEM_ZERO] Unseen: %d\n", nextIdx);
  157. for (i = 0; i < nextIdx; i++) {
  158. fprintf(stderr, " %s - %p:%ld\n", memZero[i].name, memZero[i].addr,
  159. memZero[i].len);
  160. }
  161. }
  162. /* Uninitialized value in next index. */
  163. nextIdx = -1;
  164. }
  165. /* Add an address to check.
  166. *
  167. * @param [in] name Name of address to check.
  168. * @param [in] addr Address that needs to be checked.
  169. * @param [in] len Length of data that must be zero.
  170. */
  171. void wc_MemZero_Add(const char* name, const void* addr, size_t len)
  172. {
  173. /* Initialize if not done. */
  174. if (nextIdx == -1) {
  175. wc_MemZero_Init();
  176. }
  177. /* Add an entry to the table while locked. */
  178. wc_LockMutex(&zeroMutex);
  179. if (nextIdx < WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN) {
  180. /* Fill in the next entry and update next index. */
  181. memZero[nextIdx].name = name;
  182. memZero[nextIdx].addr = addr;
  183. memZero[nextIdx].len = len;
  184. nextIdx++;
  185. }
  186. else {
  187. /* Abort when too many entries. */
  188. fprintf(stderr, "\n[MEM_ZERO] Too many addresses to check\n");
  189. fprintf(stderr, "[MEM_ZERO] WOLFSSL_MEM_CHECK_ZERO_CACHE_LEN\n");
  190. abort();
  191. }
  192. wc_UnLockMutex(&zeroMutex);
  193. }
  194. /* Check the memory in the range of the address for memory that must be zero.
  195. *
  196. * @param [in] addr Start address of memory that is to be checked.
  197. * @param [in] len Length of data associated with address.
  198. */
  199. void wc_MemZero_Check(void* addr, size_t len)
  200. {
  201. int i;
  202. size_t j;
  203. wc_LockMutex(&zeroMutex);
  204. /* Look at each address for overlap with address passes in. */
  205. for (i = 0; i < nextIdx; i++) {
  206. if ((memZero[i].addr < addr) ||
  207. ((size_t)memZero[i].addr >= (size_t)addr + len)) {
  208. /* Check address not part of memory to check. */
  209. continue;
  210. }
  211. /* Address is in range of memory being freed - check each byte zero. */
  212. for (j = 0; j < memZero[i].len; j++) {
  213. if (((unsigned char*)memZero[i].addr)[j] != 0) {
  214. /* Byte not zero - abort! */
  215. fprintf(stderr, "\n[MEM_ZERO] %s:%p + %ld is not zero\n",
  216. memZero[i].name, memZero[i].addr, j);
  217. fprintf(stderr, "[MEM_ZERO] Checking %p:%ld\n", addr, len);
  218. abort();
  219. }
  220. }
  221. /* Update next index to write to. */
  222. nextIdx--;
  223. if (nextIdx > 0) {
  224. /* Remove entry. */
  225. XMEMCPY(memZero + i, memZero + i + 1,
  226. sizeof(MemZero) * (nextIdx - i));
  227. /* Clear out top to make it easier to see what is to be checked. */
  228. XMEMSET(&memZero[nextIdx], 0, sizeof(MemZero));
  229. }
  230. /* Need to check this index again with new data. */
  231. i--;
  232. }
  233. wc_UnLockMutex(&zeroMutex);
  234. }
  235. #endif /* WOLFSSL_CHECK_MEM_ZERO */
  236. #ifdef WOLFSSL_MEM_FAIL_COUNT
  237. static wolfSSL_Mutex memFailMutex;
  238. int mem_fail_allocs = 0;
  239. int mem_fail_frees = 0;
  240. int mem_fail_cnt = 0;
  241. void wc_MemFailCount_Init()
  242. {
  243. wc_InitMutex(&memFailMutex);
  244. char* cnt = getenv("MEM_FAIL_CNT");
  245. if (cnt != NULL) {
  246. fprintf(stderr, "MemFailCount At: %d\n", mem_fail_cnt);
  247. mem_fail_cnt = atoi(cnt);
  248. }
  249. }
  250. static int wc_MemFailCount_AllocMem(void)
  251. {
  252. int ret = 1;
  253. wc_LockMutex(&memFailMutex);
  254. if ((mem_fail_cnt > 0) && (mem_fail_cnt <= mem_fail_allocs + 1)) {
  255. ret = 0;
  256. }
  257. else {
  258. mem_fail_allocs++;
  259. }
  260. wc_UnLockMutex(&memFailMutex);
  261. return ret;
  262. }
  263. static void wc_MemFailCount_FreeMem(void)
  264. {
  265. wc_LockMutex(&memFailMutex);
  266. mem_fail_frees++;
  267. wc_UnLockMutex(&memFailMutex);
  268. }
  269. void wc_MemFailCount_Free()
  270. {
  271. wc_FreeMutex(&memFailMutex);
  272. fprintf(stderr, "MemFailCount Total: %d\n", mem_fail_allocs);
  273. fprintf(stderr, "MemFailCount Frees: %d\n", mem_fail_frees);
  274. }
  275. #endif
  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 <wolfssl/wolfcrypt/types.h>
  1075. #include <stdlib.h>
  1076. #ifndef HAVE_THREAD_LS
  1077. #error "Oops, simple I/O pool example needs thread local storage"
  1078. #endif
  1079. /* allow simple per thread in and out pools */
  1080. /* use 17k size since max record size is 16k plus overhead */
  1081. static THREAD_LS_T byte pool_in[17*1024];
  1082. static THREAD_LS_T byte pool_out[17*1024];
  1083. void* XMALLOC(size_t n, void* heap, int type)
  1084. {
  1085. (void)heap;
  1086. if (type == DYNAMIC_TYPE_IN_BUFFER) {
  1087. if (n < sizeof(pool_in))
  1088. return pool_in;
  1089. else
  1090. return NULL;
  1091. }
  1092. if (type == DYNAMIC_TYPE_OUT_BUFFER) {
  1093. if (n < sizeof(pool_out))
  1094. return pool_out;
  1095. else
  1096. return NULL;
  1097. }
  1098. return malloc(n);
  1099. }
  1100. void* XREALLOC(void *p, size_t n, void* heap, int type)
  1101. {
  1102. (void)heap;
  1103. if (type == DYNAMIC_TYPE_IN_BUFFER) {
  1104. if (n < sizeof(pool_in))
  1105. return pool_in;
  1106. else
  1107. return NULL;
  1108. }
  1109. if (type == DYNAMIC_TYPE_OUT_BUFFER) {
  1110. if (n < sizeof(pool_out))
  1111. return pool_out;
  1112. else
  1113. return NULL;
  1114. }
  1115. return realloc(p, n);
  1116. }
  1117. void XFREE(void *p, void* heap, int type)
  1118. {
  1119. (void)heap;
  1120. if (type == DYNAMIC_TYPE_IN_BUFFER)
  1121. return; /* do nothing, static pool */
  1122. if (type == DYNAMIC_TYPE_OUT_BUFFER)
  1123. return; /* do nothing, static pool */
  1124. free(p);
  1125. }
  1126. #endif /* HAVE_IO_POOL */
  1127. #ifdef WOLFSSL_MEMORY_LOG
  1128. void *xmalloc(size_t n, void* heap, int type, const char* func,
  1129. const char* file, unsigned int line)
  1130. {
  1131. void* p = NULL;
  1132. word32* p32;
  1133. #ifdef WOLFSSL_MEM_FAIL_COUNT
  1134. if (!wc_MemFailCount_AllocMem()) {
  1135. WOLFSSL_MSG("MemFailCnt: Fail malloc");
  1136. return NULL;
  1137. }
  1138. #endif
  1139. if (malloc_function)
  1140. p32 = malloc_function(n + sizeof(word32) * 4);
  1141. else
  1142. p32 = malloc(n + sizeof(word32) * 4);
  1143. if (p32 != NULL) {
  1144. p32[0] = (word32)n;
  1145. p = (void*)(p32 + 4);
  1146. fprintf(stderr, "Alloc: %p -> %u (%d) at %s:%s:%u\n", p, (word32)n,
  1147. type, func, file, line);
  1148. }
  1149. (void)heap;
  1150. return p;
  1151. }
  1152. void *xrealloc(void *p, size_t n, void* heap, int type, const char* func,
  1153. const char* file, unsigned int line)
  1154. {
  1155. void* newp = NULL;
  1156. word32* p32;
  1157. word32* oldp32 = NULL;
  1158. word32 oldLen;
  1159. #ifdef WOLFSSL_MEM_FAIL_COUNT
  1160. if (!wc_MemFailCount_AllocMem()) {
  1161. WOLFSSL_MSG("MemFailCnt: Fail malloc");
  1162. return NULL;
  1163. }
  1164. #endif
  1165. if (p != NULL) {
  1166. oldp32 = (word32*)p;
  1167. oldp32 -= 4;
  1168. oldLen = oldp32[0];
  1169. }
  1170. if (realloc_function)
  1171. p32 = realloc_function(oldp32, n + sizeof(word32) * 4);
  1172. else
  1173. p32 = realloc(oldp32, n + sizeof(word32) * 4);
  1174. if (p32 != NULL) {
  1175. p32[0] = (word32)n;
  1176. newp = (void*)(p32 + 4);
  1177. if (p != NULL) {
  1178. fprintf(stderr, "Free: %p -> %u (%d) at %s:%s:%u\n", p, oldLen,
  1179. type, func, file, line);
  1180. }
  1181. fprintf(stderr, "Alloc: %p -> %u (%d) at %s:%s:%u\n", newp, (word32)n,
  1182. type, func, file, line);
  1183. }
  1184. #ifdef WOLFSSL_MEM_FAIL_COUNT
  1185. if (p != NULL) {
  1186. wc_MemFailCount_FreeMem();
  1187. }
  1188. #endif
  1189. (void)heap;
  1190. return newp;
  1191. }
  1192. void xfree(void *p, void* heap, int type, const char* func, const char* file,
  1193. unsigned int line)
  1194. {
  1195. word32* p32 = (word32*)p;
  1196. if (p != NULL) {
  1197. #ifdef WOLFSSL_MEM_FAIL_COUNT
  1198. wc_MemFailCount_FreeMem();
  1199. #endif
  1200. p32 -= 4;
  1201. fprintf(stderr, "Free: %p -> %u (%d) at %s:%s:%u\n", p, p32[0], type,
  1202. func, file, line);
  1203. if (free_function)
  1204. free_function(p32);
  1205. else
  1206. free(p32);
  1207. }
  1208. (void)heap;
  1209. }
  1210. #endif /* WOLFSSL_MEMORY_LOG */
  1211. #ifdef WOLFSSL_STACK_LOG
  1212. /* Note: this code only works with GCC using -finstrument-functions. */
  1213. void __attribute__((no_instrument_function))
  1214. __cyg_profile_func_enter(void *func, void *caller)
  1215. {
  1216. register void* sp asm("sp");
  1217. fprintf(stderr, "ENTER: %016lx %p\n", (unsigned long)(wc_ptr_t)func, sp);
  1218. (void)caller;
  1219. }
  1220. void __attribute__((no_instrument_function))
  1221. __cyg_profile_func_exit(void *func, void *caller)
  1222. {
  1223. register void* sp asm("sp");
  1224. fprintf(stderr, "EXIT: %016lx %p\n", (unsigned long)(wc_ptr_t)func, sp);
  1225. (void)caller;
  1226. }
  1227. #endif
  1228. #ifdef WOLFSSL_LINUXKM
  1229. #include "../../linuxkm/linuxkm_memory.c"
  1230. #endif