virtualStack.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2024 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #include <thread>
  24. #include "virtualStack.h"
  25. #include "heap.h"
  26. #include "../api/stringAPI.h"
  27. namespace dsr {
  28. // How many bytes that are allocated directly in thread local memory.
  29. static const uint64_t VIRTUAL_STACK_SIZE = 262144;
  30. static const int MAX_EXTRA_STACKS = 63;
  31. static const uintptr_t stackHeaderPaddedSize = memory_getPaddedSize<AllocationHeader>();
  32. static const uintptr_t stackHeaderAlignmentAndMask = memory_createAlignmentAndMask((uintptr_t)alignof(AllocationHeader));
  33. struct StackMemory {
  34. uint8_t *top = nullptr; // The stack pointer is here when completely full.
  35. uint8_t *stackPointer = nullptr; // The virtual stack pointer.
  36. uint8_t *bottom = nullptr; // The stack pointer is here when empty.
  37. };
  38. // The first block of stack memory in stread local memory.
  39. struct FixedStackMemory : public StackMemory {
  40. uint8_t data[VIRTUAL_STACK_SIZE];
  41. FixedStackMemory() {
  42. this->top = this->data;
  43. this->stackPointer = this->data + VIRTUAL_STACK_SIZE;
  44. this->bottom = this->data + VIRTUAL_STACK_SIZE;
  45. }
  46. };
  47. // Additional stacks in heap memory.
  48. struct DynamicStackMemory : public StackMemory {
  49. ~DynamicStackMemory() {
  50. if (this->top != nullptr) {
  51. heap_decreaseUseCount(this->top);
  52. }
  53. }
  54. };
  55. // Returns the size of the allocation including alignment.
  56. inline uint64_t increaseStackPointer(uint8_t *&pointer, uint64_t paddedSize, uintptr_t alignmentAndMask) {
  57. // Add the padded payload and align.
  58. uintptr_t oldAddress = (uintptr_t)pointer;
  59. uintptr_t newAddress = (oldAddress - paddedSize) & alignmentAndMask;
  60. pointer = (uint8_t*)newAddress;
  61. return oldAddress - newAddress;
  62. }
  63. inline void decreaseStackPointer(uint8_t *&pointer, uint64_t totalSize) {
  64. // Remove the data and alignment.
  65. pointer += totalSize;
  66. }
  67. static UnsafeAllocation stackAllocate(StackMemory& stack, uint64_t paddedSize, uintptr_t alignmentAndMask, const char *name) {
  68. uint8_t *newStackPointer = stack.stackPointer;
  69. // Allocate memory for payload.
  70. uint64_t payloadTotalSize = increaseStackPointer(newStackPointer, paddedSize, alignmentAndMask);
  71. // Get a pointer to the payload.
  72. uint8_t *data = newStackPointer;
  73. // Allocate memory for header.
  74. uint64_t headerTotalSize = increaseStackPointer(newStackPointer, stackHeaderPaddedSize, stackHeaderAlignmentAndMask);
  75. // Check that we did not run out of memory.
  76. if (newStackPointer < stack.top) {
  77. // Not enough space.
  78. return UnsafeAllocation(nullptr, nullptr);
  79. } else {
  80. stack.stackPointer = newStackPointer;
  81. // Write the header to memory.
  82. AllocationHeader *header = (AllocationHeader*)(stack.stackPointer);
  83. *header = AllocationHeader(payloadTotalSize + headerTotalSize, true, name);
  84. // Clear the new allocation for determinism.
  85. std::memset((void*)data, 0, payloadTotalSize);
  86. // Return a pointer to the payload.
  87. return UnsafeAllocation(data, header);
  88. }
  89. }
  90. thread_local FixedStackMemory fixedMemory; // Index -1
  91. thread_local DynamicStackMemory dynamicMemory[MAX_EXTRA_STACKS]; // Index 0..MAX_EXTRA_STACKS-1
  92. thread_local int32_t stackIndex = -1;
  93. UnsafeAllocation virtualStack_push(uint64_t paddedSize, uintptr_t alignmentAndMask, const char *name) {
  94. // TODO: Assert that the alignment mask begins with ones and ends with zeroes, in case that the caller accidentally truncated the beginning of the mask.
  95. if (stackIndex < 0) {
  96. UnsafeAllocation result = stackAllocate(fixedMemory, paddedSize, alignmentAndMask, name);
  97. // Check that we did not run out of memory.
  98. if (result.data == nullptr) {
  99. // Not enough space in thread local memory. Moving to the first dynamic stack.
  100. stackIndex = 0;
  101. goto allocateDynamic;
  102. } else {
  103. // Return a pointer to the payload.
  104. return result;
  105. }
  106. }
  107. allocateDynamic:
  108. // We should only reach this place if allocating in dynamic stack memory.
  109. assert(stackIndex >= 0);
  110. // Never go above the maximum index.
  111. assert(stackIndex < MAX_EXTRA_STACKS);
  112. // Allocate memory in the dynamic stack if not yet allocated.
  113. if (dynamicMemory[stackIndex].top == nullptr) {
  114. // Decide a minimum size to allocate.
  115. uint64_t regionSize = 16777216 * (1 << stackIndex);
  116. if (paddedSize * 4 > regionSize) {
  117. regionSize = paddedSize * 4;
  118. }
  119. // Allocate the memory.
  120. UnsafeAllocation newAllocation = heap_allocate(regionSize, true);
  121. // Ask how large the allocation actually is.
  122. regionSize = heap_getAllocationSize(newAllocation.data);
  123. // Use the whole allocation.
  124. heap_setUsedSize(newAllocation.data, regionSize);
  125. // Tell the allocation that we are using it.
  126. heap_increaseUseCount(newAllocation.data);
  127. if (newAllocation.data == nullptr) {
  128. throwError(U"Failed to allocate ", regionSize, U" bytes of heap memory for expanding the virtual stack when trying to allocate ", paddedSize, " bytes!\n");
  129. return UnsafeAllocation(nullptr, nullptr);
  130. } else {
  131. // Keep the new allocation.
  132. dynamicMemory[stackIndex].top = newAllocation.data;
  133. // Start from the back of the new allocation.
  134. dynamicMemory[stackIndex].stackPointer = newAllocation.data + regionSize;
  135. dynamicMemory[stackIndex].bottom = newAllocation.data + regionSize;
  136. }
  137. }
  138. assert(dynamicMemory[stackIndex].stackPointer != nullptr);
  139. // Allocate memory.
  140. UnsafeAllocation result = stackAllocate(dynamicMemory[stackIndex], paddedSize, alignmentAndMask, name);
  141. if (result.data == nullptr) {
  142. if (stackIndex >= MAX_EXTRA_STACKS - 1) {
  143. throwError(U"Exceeded MAX_EXTRA_STACKS to allocate more heap memory for a thread local virtual stack!\n");
  144. return UnsafeAllocation(nullptr, nullptr);
  145. } else {
  146. stackIndex++;
  147. goto allocateDynamic;
  148. }
  149. } else {
  150. // Return a pointer to the payload.
  151. return result;
  152. }
  153. }
  154. // Deallocates the topmost allocation in the stack or returns false if it does not contain any more allocations.
  155. static bool stackDeallocate(StackMemory& stack) {
  156. if (stack.stackPointer + stackHeaderPaddedSize > stack.bottom) {
  157. // If the allocated memory does not fit a header, then it is empty.
  158. return false;
  159. } else {
  160. // Read the header.
  161. AllocationHeader header = *((AllocationHeader*)stack.stackPointer);
  162. // Overwrite the header.
  163. *((AllocationHeader*)stack.stackPointer) = AllocationHeader();
  164. // Deallocate both header and payload using the stored total size.
  165. decreaseStackPointer(stack.stackPointer, header.totalSize);
  166. return true;
  167. }
  168. }
  169. void virtualStack_pop() {
  170. if (stackIndex < 0) {
  171. if (!stackDeallocate(fixedMemory)) {
  172. throwError(U"No more stack memory to pop!\n");
  173. }
  174. } else {
  175. if (!stackDeallocate(dynamicMemory[stackIndex])) {
  176. throwError(U"The virtual stack has been corrupted!\n");
  177. } else {
  178. // If the bottom has been reached then go to the lower stack.
  179. if (dynamicMemory[stackIndex].stackPointer >= dynamicMemory[stackIndex].bottom) {
  180. stackIndex--;
  181. }
  182. }
  183. }
  184. }
  185. }