virtualStack.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 "virtualStack.h"
  24. #include <thread>
  25. #include "../api/stringAPI.h"
  26. namespace dsr {
  27. // How many bytes that are allocated directly in thread local memory.
  28. static const uint64_t VIRTUAL_STACK_SIZE = 262144;
  29. static const int MAX_EXTRA_STACKS = 63;
  30. static const uintptr_t stackHeaderPaddedSize = memory_getPaddedSize<AllocationHeader>();
  31. static const uintptr_t stackHeaderAlignmentAndMask = memory_createAlignmentAndMask((uintptr_t)alignof(AllocationHeader));
  32. struct StackMemory {
  33. uint8_t *top = nullptr; // The stack pointer is here when completely full.
  34. uint8_t *stackPointer = nullptr; // The virtual stack pointer.
  35. uint8_t *bottom = nullptr; // The stack pointer is here when empty.
  36. };
  37. // The first block of stack memory in stread local memory.
  38. struct FixedStackMemory : public StackMemory {
  39. uint8_t data[VIRTUAL_STACK_SIZE];
  40. FixedStackMemory() {
  41. this->top = this->data;
  42. this->stackPointer = this->data + VIRTUAL_STACK_SIZE;
  43. this->bottom = this->data + VIRTUAL_STACK_SIZE;
  44. }
  45. };
  46. // Additional stacks in heap memory.
  47. struct DynamicStackMemory : public StackMemory {
  48. ~DynamicStackMemory() {
  49. if (this->top != nullptr) {
  50. free(this->top);
  51. }
  52. }
  53. };
  54. // Returns the size of the allocation including alignment.
  55. inline uint64_t increaseStackPointer(uint8_t *&pointer, uint64_t paddedSize, uintptr_t alignmentAndMask) {
  56. // Add the padded payload and align.
  57. uintptr_t oldAddress = (uintptr_t)pointer;
  58. uintptr_t newAddress = (oldAddress - paddedSize) & alignmentAndMask;
  59. pointer = (uint8_t*)newAddress;
  60. return oldAddress - newAddress;
  61. }
  62. inline void decreaseStackPointer(uint8_t *&pointer, uint64_t totalSize) {
  63. // Remove the data and alignment.
  64. pointer += totalSize;
  65. }
  66. static UnsafeAllocation stackAllocate(StackMemory& stack, uint64_t paddedSize, uintptr_t alignmentAndMask) {
  67. uint8_t *newStackPointer = stack.stackPointer;
  68. // Allocate memory for payload.
  69. uint64_t payloadTotalSize = increaseStackPointer(newStackPointer, paddedSize, alignmentAndMask);
  70. // Get a pointer to the payload.
  71. uint8_t *data = newStackPointer;
  72. // Allocate memory for header.
  73. uint64_t headerTotalSize = increaseStackPointer(newStackPointer, stackHeaderPaddedSize, stackHeaderAlignmentAndMask);
  74. // Check that we did not run out of memory.
  75. if (newStackPointer < stack.top) {
  76. // Not enough space.
  77. return UnsafeAllocation(nullptr, nullptr);
  78. } else {
  79. stack.stackPointer = newStackPointer;
  80. // Write the header to memory.
  81. AllocationHeader *header = (AllocationHeader*)(stack.stackPointer);
  82. *header = AllocationHeader(payloadTotalSize + headerTotalSize, true);
  83. // Clear the new allocation for determinism.
  84. std::memset((void*)data, 0, payloadTotalSize);
  85. // Return a pointer to the payload.
  86. return UnsafeAllocation(data, header);
  87. }
  88. }
  89. thread_local FixedStackMemory fixedMemory; // Index -1
  90. thread_local DynamicStackMemory dynamicMemory[MAX_EXTRA_STACKS]; // Index 0..MAX_EXTRA_STACKS-1
  91. thread_local int32_t stackIndex = -1;
  92. UnsafeAllocation virtualStack_push(uint64_t paddedSize, uintptr_t alignmentAndMask) {
  93. // 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.
  94. if (stackIndex < 0) {
  95. UnsafeAllocation result = stackAllocate(fixedMemory, paddedSize, alignmentAndMask);
  96. // Check that we did not run out of memory.
  97. if (result.data == nullptr) {
  98. // Not enough space in thread local memory. Moving to the first dynamic stack.
  99. stackIndex = 0;
  100. goto allocateDynamic;
  101. } else {
  102. // Return a pointer to the payload.
  103. return result;
  104. }
  105. }
  106. allocateDynamic:
  107. // We should only reach this place if allocating in dynamic stack memory.
  108. assert(stackIndex >= 0);
  109. // Never go above the maximum index.
  110. assert(stackIndex < MAX_EXTRA_STACKS);
  111. // Allocate memory in the dynamic stack if not yet allocated.
  112. if (dynamicMemory[stackIndex].top == nullptr) {
  113. uint64_t regionSize = 16777216 * (1 << stackIndex);
  114. if (paddedSize * 4 > regionSize) {
  115. regionSize = paddedSize * 4;
  116. }
  117. uint8_t *newMemory = (uint8_t*)malloc(regionSize);
  118. if (newMemory == nullptr) {
  119. throwError(U"Failed to allocate ", regionSize, U" bytes of heap memory for expanding the virtual stack when trying to allocate ", paddedSize, " bytes!\n");
  120. return UnsafeAllocation(nullptr, nullptr);
  121. } else {
  122. // Keep the new allocation.
  123. dynamicMemory[stackIndex].top = newMemory;
  124. // Start from the back of the new allocation.
  125. dynamicMemory[stackIndex].stackPointer = newMemory + regionSize;
  126. dynamicMemory[stackIndex].bottom = newMemory + regionSize;
  127. }
  128. }
  129. assert(dynamicMemory[stackIndex].stackPointer != nullptr);
  130. // Allocate memory.
  131. UnsafeAllocation result = stackAllocate(dynamicMemory[stackIndex], paddedSize, alignmentAndMask);
  132. if (result.data == nullptr) {
  133. if (stackIndex >= MAX_EXTRA_STACKS - 1) {
  134. throwError(U"Exceeded MAX_EXTRA_STACKS to allocate more heap memory for a thread local virtual stack!\n");
  135. return UnsafeAllocation(nullptr, nullptr);
  136. } else {
  137. stackIndex++;
  138. goto allocateDynamic;
  139. }
  140. } else {
  141. // Return a pointer to the payload.
  142. return result;
  143. }
  144. }
  145. // Deallocates the topmost allocation in the stack or returns false if it does not contain any more allocations.
  146. static bool stackDeallocate(StackMemory& stack) {
  147. if (stack.stackPointer + stackHeaderPaddedSize > stack.bottom) {
  148. // If the allocated memory does not fit a header, then it is empty.
  149. return false;
  150. } else {
  151. // Read the header.
  152. AllocationHeader header = *((AllocationHeader*)stack.stackPointer);
  153. // Overwrite the header.
  154. *((AllocationHeader*)stack.stackPointer) = AllocationHeader();
  155. // Deallocate both header and payload using the stored total size.
  156. decreaseStackPointer(stack.stackPointer, header.totalSize);
  157. return true;
  158. }
  159. }
  160. void virtualStack_pop() {
  161. if (stackIndex < 0) {
  162. if (!stackDeallocate(fixedMemory)) {
  163. throwError(U"No more stack memory to pop!\n");
  164. }
  165. } else {
  166. if (!stackDeallocate(dynamicMemory[stackIndex])) {
  167. throwError(U"The virtual stack has been corrupted!\n");
  168. } else {
  169. // If the bottom has been reached then go to the lower stack.
  170. if (dynamicMemory[stackIndex].stackPointer >= dynamicMemory[stackIndex].bottom) {
  171. stackIndex--;
  172. }
  173. }
  174. }
  175. }
  176. }