natsu.gc.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //
  2. // Chino Memory
  3. //
  4. #include "Chino.Kernel.h"
  5. #include <cstring>
  6. #define traceMALLOC(p, size)
  7. #define traceFREE(p, size)
  8. #define portBYTE_ALIGNMENT 8
  9. #if portBYTE_ALIGNMENT == 32
  10. #define portBYTE_ALIGNMENT_MASK (0x001f)
  11. #endif
  12. #if portBYTE_ALIGNMENT == 16
  13. #define portBYTE_ALIGNMENT_MASK (0x000f)
  14. #endif
  15. #if portBYTE_ALIGNMENT == 8
  16. #define portBYTE_ALIGNMENT_MASK (0x0007)
  17. #endif
  18. #if portBYTE_ALIGNMENT == 4
  19. #define portBYTE_ALIGNMENT_MASK (0x0003)
  20. #endif
  21. #if portBYTE_ALIGNMENT == 2
  22. #define portBYTE_ALIGNMENT_MASK (0x0001)
  23. #endif
  24. #if portBYTE_ALIGNMENT == 1
  25. #define portBYTE_ALIGNMENT_MASK (0x0000)
  26. #endif
  27. #ifndef portBYTE_ALIGNMENT_MASK
  28. #error "Invalid portBYTE_ALIGNMENT definition"
  29. #endif
  30. /* Block sizes must not get too small. */
  31. #define heapMINIMUM_BLOCK_SIZE ((size_t)(heapStructSize_ << 1))
  32. /* Assumes 8bit bytes! */
  33. #define heapBITS_PER_BYTE ((size_t)8)
  34. typedef struct A_BLOCK_LINK
  35. {
  36. A_BLOCK_LINK *pNextFreeBlock; /*<< The next free block in the list. */
  37. size_t BlockSize; /*<< The size of the free block. */
  38. } BlockLink_t;
  39. /*
  40. * Inserts a block of memory that is being freed into the correct position in
  41. * the list of free memory blocks. The block being freed will be merged with
  42. * the block in front it and/or the block behind it if the memory blocks are
  43. * adjacent to each other.
  44. */
  45. static void prvInsertBlockIntoFreeList(BlockLink_t *pBlockToInsert);
  46. /*-----------------------------------------------------------*/
  47. BlockLink_t heapStart_, *pHeapEnd_ = nullptr;
  48. size_t freeBytesRemaining_ = 0;
  49. size_t minimumEverFreeBytesRemaining_ = 0;
  50. size_t blockAllocatedBit_ = 0;
  51. /* The size of the structure placed at the beginning of each allocated memory
  52. block must by correctly byte aligned. */
  53. static constexpr size_t heapStructSize_ = (sizeof(BlockLink_t) + ((size_t)(portBYTE_ALIGNMENT - 1))) & ~((size_t)portBYTE_ALIGNMENT_MASK);
  54. struct HeapRegionDesc
  55. {
  56. uintptr_t StartAddress;
  57. size_t SizeInBytes;
  58. };
  59. #ifdef WIN32
  60. static char _sram[6 * 1024 * 1024];
  61. #else
  62. extern "C"
  63. {
  64. extern char _heap_start[];
  65. extern char _heap_end[];
  66. }
  67. #endif
  68. #define kassert(exp) \
  69. if (!(exp)) \
  70. { \
  71. while (1) \
  72. ; \
  73. }
  74. void InitializeHeap() noexcept
  75. {
  76. if (pHeapEnd_)
  77. return;
  78. BlockLink_t *pFirstFreeBlockInRegion = nullptr, *pPreviousFreeBlock;
  79. uintptr_t alignedHeap;
  80. size_t totalRegionSize, totalHeapSize = 0;
  81. size_t definedRegions = 0;
  82. uintptr_t address;
  83. HeapRegionDesc regionDesc;
  84. #ifdef WIN32
  85. regionDesc.StartAddress = uintptr_t(&_sram[0]);
  86. regionDesc.SizeInBytes = size_t(std::size(_sram));
  87. #else
  88. regionDesc.StartAddress = uintptr_t(&_heap_start[0]);
  89. regionDesc.SizeInBytes = size_t(&_heap_end[0] - &_heap_start[0]);
  90. #endif
  91. do
  92. {
  93. totalRegionSize = regionDesc.SizeInBytes;
  94. address = regionDesc.StartAddress;
  95. /* Ensure the heap region starts on a correctly aligned boundary. */
  96. if ((address & portBYTE_ALIGNMENT_MASK) != 0)
  97. {
  98. address += (portBYTE_ALIGNMENT - 1);
  99. address &= ~portBYTE_ALIGNMENT_MASK;
  100. /* Adjust the size for the bytes lost to alignment. */
  101. totalRegionSize -= address - (size_t)regionDesc.StartAddress;
  102. }
  103. alignedHeap = address;
  104. /* Set xStart if it has not already been set. */
  105. if (definedRegions == 0)
  106. {
  107. /* xStart is used to hold a pointer to the first item in the list of
  108. free blocks. The void cast is used to prevent compiler warnings. */
  109. heapStart_.pNextFreeBlock = reinterpret_cast<BlockLink_t *>(alignedHeap);
  110. heapStart_.BlockSize = 0;
  111. }
  112. else
  113. {
  114. /* Should only get here if one region has already been added to the
  115. heap. */
  116. kassert(pHeapEnd_);
  117. /* Check blocks are passed in with increasing start addresses. */
  118. kassert(address > uintptr_t(pHeapEnd_));
  119. }
  120. /* Remember the location of the end marker in the previous region, if
  121. any. */
  122. pPreviousFreeBlock = pHeapEnd_;
  123. /* pxEnd is used to mark the end of the list of free blocks and is
  124. inserted at the end of the region space. */
  125. address = alignedHeap + totalRegionSize;
  126. address -= heapStructSize_;
  127. address &= ~portBYTE_ALIGNMENT_MASK;
  128. pHeapEnd_ = reinterpret_cast<BlockLink_t *>(address);
  129. pHeapEnd_->BlockSize = 0;
  130. pHeapEnd_->pNextFreeBlock = nullptr;
  131. /* To start with there is a single free block in this region that is
  132. sized to take up the entire heap region minus the space taken by the
  133. free block structure. */
  134. pFirstFreeBlockInRegion = reinterpret_cast<BlockLink_t *>(alignedHeap);
  135. pFirstFreeBlockInRegion->BlockSize = address - uintptr_t(pFirstFreeBlockInRegion);
  136. pFirstFreeBlockInRegion->pNextFreeBlock = pHeapEnd_;
  137. /* If this is not the first region that makes up the entire heap space
  138. then link the previous region to this region. */
  139. if (pPreviousFreeBlock)
  140. pPreviousFreeBlock->pNextFreeBlock = pFirstFreeBlockInRegion;
  141. totalHeapSize += pFirstFreeBlockInRegion->BlockSize;
  142. /* Move onto the next HeapRegion_t structure. */
  143. definedRegions++;
  144. } while (false);
  145. minimumEverFreeBytesRemaining_ = totalHeapSize;
  146. freeBytesRemaining_ = totalHeapSize;
  147. /* Check something was actually defined before it is accessed. */
  148. kassert(totalHeapSize);
  149. /* Work out the position of the top bit in a size_t variable. */
  150. blockAllocatedBit_ = ((size_t)1) << ((sizeof(size_t) * heapBITS_PER_BYTE) - 1);
  151. }
  152. void *HeapAlloc(size_t wantedSize) noexcept
  153. {
  154. #ifdef WIN32
  155. InitializeHeap();
  156. #endif
  157. BlockLink_t *pBlock, *pPreviousBlock, *pNewBlockLink;
  158. void *pReturn = nullptr;
  159. uintptr_t alignOffset = 0;
  160. /* The heap must be initialised before the first call to
  161. prvPortMalloc(). */
  162. kassert(pHeapEnd_);
  163. //vTaskSuspendAll();
  164. {
  165. /* Check the requested block size is not so large that the top bit is
  166. set. The top bit of the block size member of the BlockLink_t structure
  167. is used to determine who owns the block - the application or the
  168. kernel, so it must be free. */
  169. if ((wantedSize & blockAllocatedBit_) == 0)
  170. {
  171. /* The wanted size is increased so it can contain a BlockLink_t
  172. structure in addition to the requested amount of bytes. */
  173. if (wantedSize > 0)
  174. {
  175. wantedSize += heapStructSize_;
  176. /* Ensure that blocks are always aligned to the required number
  177. of bytes. */
  178. if ((wantedSize & portBYTE_ALIGNMENT_MASK) != 0x00)
  179. {
  180. /* Byte alignment required. */
  181. wantedSize += (portBYTE_ALIGNMENT - (wantedSize & portBYTE_ALIGNMENT_MASK));
  182. }
  183. }
  184. if ((wantedSize > 0) && (wantedSize <= freeBytesRemaining_))
  185. {
  186. /* Traverse the list from the start (lowest address) block until
  187. one of adequate size is found. */
  188. pPreviousBlock = &heapStart_;
  189. pBlock = heapStart_.pNextFreeBlock;
  190. while ((pBlock->BlockSize < wantedSize) && pBlock->pNextFreeBlock)
  191. {
  192. pPreviousBlock = pBlock;
  193. pBlock = pBlock->pNextFreeBlock;
  194. }
  195. /* If the end marker was reached then a block of adequate size
  196. was not found. */
  197. if (pBlock != pHeapEnd_)
  198. {
  199. /* Return the memory space pointed to - jumping over the
  200. BlockLink_t structure at its start. */
  201. pReturn = reinterpret_cast<void *>(uintptr_t(pPreviousBlock->pNextFreeBlock) + heapStructSize_);
  202. /* This block is being returned for use so must be taken out
  203. of the list of free blocks. */
  204. pPreviousBlock->pNextFreeBlock = pBlock->pNextFreeBlock;
  205. /* If the block is larger than required it can be split into
  206. two. */
  207. if ((pBlock->BlockSize - wantedSize) > heapMINIMUM_BLOCK_SIZE)
  208. {
  209. /* This block is to be split into two. Create a new
  210. block following the number of bytes requested. The void
  211. cast is used to prevent byte alignment warnings from the
  212. compiler. */
  213. pNewBlockLink = reinterpret_cast<BlockLink_t *>(uintptr_t(pBlock) + wantedSize);
  214. /* Calculate the sizes of two blocks split from the
  215. single block. */
  216. pNewBlockLink->BlockSize = pBlock->BlockSize - wantedSize;
  217. pBlock->BlockSize = wantedSize;
  218. /* Insert the new block into the list of free blocks. */
  219. prvInsertBlockIntoFreeList(pNewBlockLink);
  220. }
  221. freeBytesRemaining_ -= pBlock->BlockSize;
  222. if (freeBytesRemaining_ < minimumEverFreeBytesRemaining_)
  223. minimumEverFreeBytesRemaining_ = freeBytesRemaining_;
  224. /* The block is being returned - it is allocated and owned
  225. by the application and has no "next" block. */
  226. pBlock->BlockSize |= blockAllocatedBit_;
  227. pBlock->pNextFreeBlock = nullptr;
  228. }
  229. }
  230. }
  231. traceMALLOC(pvReturn, xWantedSize);
  232. }
  233. //(void)xTaskResumeAll();
  234. #if (configUSE_MALLOC_FAILED_HOOK == 1)
  235. {
  236. if (pvReturn == NULL)
  237. {
  238. extern void vApplicationMallocFailedHook(void);
  239. vApplicationMallocFailedHook();
  240. }
  241. else
  242. {
  243. mtCOVERAGE_TEST_MARKER();
  244. }
  245. }
  246. #endif
  247. return pReturn;
  248. }
  249. void HeapFree(void *ptr) noexcept
  250. {
  251. auto puc = uintptr_t(ptr);
  252. BlockLink_t *pLink;
  253. if (ptr)
  254. {
  255. /* The memory being freed will have an BlockLink_t structure immediately
  256. before it. */
  257. puc -= heapStructSize_;
  258. /* This casting is to keep the compiler from issuing warnings. */
  259. pLink = reinterpret_cast<BlockLink_t *>(puc);
  260. /* Check the block is actually allocated. */
  261. kassert(pLink->BlockSize & blockAllocatedBit_);
  262. kassert(pLink->pNextFreeBlock == nullptr);
  263. if (pLink->BlockSize & blockAllocatedBit_)
  264. {
  265. if (pLink->pNextFreeBlock == nullptr)
  266. {
  267. /* The block is being returned to the heap - it is no longer
  268. allocated. */
  269. pLink->BlockSize &= ~blockAllocatedBit_;
  270. //vTaskSuspendAll();
  271. {
  272. /* Add this block to the list of free blocks. */
  273. freeBytesRemaining_ += pLink->BlockSize;
  274. traceFREE(pv, pxLink->xBlockSize);
  275. prvInsertBlockIntoFreeList(pLink);
  276. }
  277. //(void)xTaskResumeAll();
  278. }
  279. }
  280. }
  281. }
  282. static void prvInsertBlockIntoFreeList(BlockLink_t *pBlockToInsert)
  283. {
  284. BlockLink_t *pIterator;
  285. uintptr_t puc;
  286. /* Iterate through the list until a block is found that has a higher address
  287. than the block being inserted. */
  288. for (pIterator = &heapStart_; pIterator->pNextFreeBlock < pBlockToInsert; pIterator = pIterator->pNextFreeBlock)
  289. {
  290. /* Nothing to do here, just iterate to the right position. */
  291. }
  292. /* Do the block being inserted, and the block it is being inserted after
  293. make a contiguous block of memory? */
  294. puc = uintptr_t(pIterator);
  295. if ((puc + pIterator->BlockSize) == uintptr_t(pBlockToInsert))
  296. {
  297. pIterator->BlockSize += pBlockToInsert->BlockSize;
  298. pBlockToInsert = pIterator;
  299. }
  300. /* Do the block being inserted, and the block it is being inserted before
  301. make a contiguous block of memory? */
  302. puc = uintptr_t(pBlockToInsert);
  303. if ((puc + pBlockToInsert->BlockSize) == uintptr_t(pIterator->pNextFreeBlock))
  304. {
  305. if (pIterator->pNextFreeBlock != pHeapEnd_)
  306. {
  307. /* Form one big block from the two blocks. */
  308. pBlockToInsert->BlockSize += pIterator->pNextFreeBlock->BlockSize;
  309. pBlockToInsert->pNextFreeBlock = pIterator->pNextFreeBlock->pNextFreeBlock;
  310. }
  311. else
  312. {
  313. pBlockToInsert->pNextFreeBlock = pHeapEnd_;
  314. }
  315. }
  316. else
  317. {
  318. pBlockToInsert->pNextFreeBlock = pIterator->pNextFreeBlock;
  319. }
  320. /* If the block being inserted plugged a gab, so was merged with the block
  321. before and the block after, then it's pxNextFreeBlock pointer will have
  322. already been set, and should not be set here as that would make it point
  323. to itself. */
  324. if (pIterator != pBlockToInsert)
  325. {
  326. pIterator->pNextFreeBlock = pBlockToInsert;
  327. }
  328. }
  329. using namespace System_Private_CoreLib::System;
  330. using namespace Chino_Kernel::Chino::Memory;
  331. using namespace natsu;
  332. gc_obj_ref<Object> natsu::gc_alloc(const vtable_t &vtable, size_t size)
  333. {
  334. auto mem_ptr = reinterpret_cast<uint8_t *>(HeapAlloc(size + sizeof(object_header)));
  335. if (!mem_ptr)
  336. throw make_exception(make_object<OutOfMemoryException>());
  337. gc_obj_ref<Object> ptr(reinterpret_cast<Object *>(mem_ptr + sizeof(object_header)));
  338. ptr.header().vtable_ = &vtable;
  339. return ptr;
  340. }
  341. int32_t MemoryManager::_s_GetUsedMemorySize()
  342. {
  343. #if _WIN32
  344. return 6 * 1024 * 1024 - freeBytesRemaining_;
  345. #else
  346. return size_t(&_heap_end[0] - &_heap_start[0]) - freeBytesRemaining_;
  347. #endif
  348. }
  349. int32_t MemoryManager::_s_GetFreeMemorySize()
  350. {
  351. return freeBytesRemaining_;
  352. }