SafePointer.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2023 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 "SafePointer.h"
  24. #include "../api/stringAPI.h"
  25. #ifdef SAFE_POINTER_CHECKS
  26. #include <thread>
  27. #include <mutex>
  28. #endif
  29. using namespace dsr;
  30. // Thread hash of memory without any specific owner.
  31. static uint64_t ANY_THREAD_HASH = 0xF986BA1496E872A5;
  32. #ifdef SAFE_POINTER_CHECKS
  33. // Hashed thread identity.
  34. // TODO: Create a function for geterating a better thread hash with better entropy.
  35. std::hash<std::thread::id> hasher;
  36. thread_local const uint64_t currentThreadHash = hasher(std::this_thread::get_id());
  37. // Globally unique identifiers for memory allocations.
  38. // Different allocations can have the same address at different times when allocations are recycled,
  39. // so a globally unique identifier is needed to make sure that we access the same allocation.
  40. static std::mutex idLock;
  41. static uint64_t idCounter = 0xD13A98271E08BF57;
  42. static uint64_t createIdentity() {
  43. uint64_t result;
  44. idLock.lock();
  45. result = idCounter;
  46. idCounter++;
  47. idLock.unlock();
  48. return result;
  49. }
  50. AllocationHeader::AllocationHeader()
  51. : totalSize(0), threadHash(0), allocationIdentity(0) {}
  52. AllocationHeader::AllocationHeader(uintptr_t totalSize, bool threadLocal)
  53. : totalSize(totalSize), threadHash(threadLocal ? currentThreadHash : ANY_THREAD_HASH), allocationIdentity(createIdentity()) {}
  54. #else
  55. AllocationHeader::AllocationHeader()
  56. : totalSize(0) {}
  57. AllocationHeader::AllocationHeader(uintptr_t totalSize, bool threadLocal)
  58. : totalSize(totalSize) {}
  59. #endif
  60. #ifdef SAFE_POINTER_CHECKS
  61. void dsr::assertNonNegativeSize(intptr_t size) {
  62. if (size < 0) {
  63. throwError(U"Negative size of SafePointer!\n");
  64. }
  65. }
  66. void dsr::assertInsideSafePointer(const char* method, const char* name, const uint8_t* pointer, const uint8_t* data, const uint8_t* regionStart, const uint8_t* regionEnd, const AllocationHeader *header, uint64_t allocationIdentity, intptr_t claimedSize, intptr_t elementSize) {
  67. if (regionStart == nullptr) {
  68. throwError(U"SafePointer exception! Tried to use a null pointer!\n");
  69. return;
  70. }
  71. // If the pointer has an allocation header, check that the identity matches the one stored in the pointer.
  72. if (header != nullptr) {
  73. uint64_t headerIdentity, headerHash;
  74. try {
  75. // Both allocation identity and thread hash may match by mistake, but in most of the cases this will give more information about why it happened.
  76. headerIdentity = header->allocationIdentity;
  77. headerHash = header->threadHash;
  78. } catch(...) {
  79. throwError(U"SafePointer exception! Tried to access memory not available to the application!\n");
  80. return;
  81. }
  82. if (headerIdentity != allocationIdentity) {
  83. throwError(U"SafePointer exception! Accessing freed memory or corrupted allocation header!\n headerIdentity = ", headerIdentity, U"\n allocationIdentity = ", allocationIdentity, U"");
  84. return;
  85. } else if (headerHash != ANY_THREAD_HASH && headerHash != currentThreadHash) {
  86. throwError(U"SafePointer exception! Accessing another thread's private memory!\n headerHash = ", headerHash, U"\n currentThreadHash = ", currentThreadHash, U"\n");
  87. return;
  88. }
  89. }
  90. if (pointer < regionStart || pointer + claimedSize > regionEnd) {
  91. String message;
  92. string_append(message, U"\n _________________ SafePointer out of bound exception! _________________\n");
  93. string_append(message, U"/\n");
  94. string_append(message, U"| Name: ", name, U"\n");
  95. string_append(message, U"| Method: ", method, U"\n");
  96. string_append(message, U"| Region: ", (uintptr_t)regionStart, U" to ", (uintptr_t)regionEnd, U"\n");
  97. string_append(message, U"| Region size: ", (intptr_t)(regionEnd - regionStart), U" bytes\n");
  98. string_append(message, U"| Base pointer: ", (uintptr_t)data, U"\n");
  99. string_append(message, U"| Requested pointer: ", (uintptr_t)pointer, U"\n");
  100. string_append(message, U"| Requested size: ", claimedSize, U" bytes\n");
  101. intptr_t startOffset = (intptr_t)pointer - (intptr_t)regionStart;
  102. intptr_t baseOffset = (intptr_t)pointer - (intptr_t)data;
  103. // Index relative to allocation start
  104. // regionStart is the start of the accessible memory region
  105. if (startOffset != baseOffset) {
  106. string_append(message, U"| Start offset: ", startOffset, U" bytes\n");
  107. if (startOffset % elementSize == 0) {
  108. intptr_t index = startOffset / elementSize;
  109. intptr_t elementCount = ((intptr_t)regionEnd - (intptr_t)regionStart) / elementSize;
  110. string_append(message, U"| Start index: ", index, U" [0..", (elementCount - 1), U"]\n");
  111. }
  112. }
  113. // Base index relative to the stored pointer within the region
  114. // data is the base of the allocation at index zero
  115. string_append(message, U"| Base offset: ", baseOffset, U" bytes\n");
  116. if (baseOffset % elementSize == 0) {
  117. intptr_t index = baseOffset / elementSize;
  118. intptr_t elementCount = ((intptr_t)regionEnd - (intptr_t)data) / elementSize;
  119. string_append(message, U"| Base index: ", index, U" [0..", (elementCount - 1), U"]\n");
  120. }
  121. string_append(message, U"\\_______________________________________________________________________\n\n");
  122. throwError(message);
  123. return;
  124. }
  125. }
  126. #endif