WriteBarrierValidation.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #if IL2CPP_ENABLE_WRITE_BARRIER_VALIDATION
  2. #include "gc_wrapper.h"
  3. #include "il2cpp-config.h"
  4. #include "il2cpp-api.h"
  5. #include "gc/WriteBarrierValidation.h"
  6. #include "gc/GarbageCollector.h"
  7. #include "os/Mutex.h"
  8. #include "vm/StackTrace.h"
  9. #include <algorithm>
  10. #include <functional>
  11. #include <map>
  12. #include <string>
  13. // On systems which have the posix backtrace API, you can turn on this define to get native stack traces.
  14. // This can make it easier to debug issues with missing barriers.
  15. #define HAS_POSIX_BACKTRACE IL2CPP_TARGET_OSX
  16. #define HAS_WINDOWS_BACKTRACE IL2CPP_TARGET_WINDOWS
  17. #if HAS_POSIX_BACKTRACE
  18. #include <execinfo.h>
  19. #endif
  20. #if HAS_WINDOWS_BACKTRACE
  21. #include <windows.h>
  22. #endif
  23. using namespace il2cpp::os;
  24. using namespace il2cpp::vm;
  25. #if !IL2CPP_GC_BOEHM
  26. #error "Write Barrier Validation is specific to Boehm GC"
  27. #endif
  28. #if IL2CPP_TINY && !IL2CPP_TINY_DEBUGGER
  29. #define IL2CPP_TINY_BACKEND 1
  30. uint8_t* Il2CppGetTinyTypeUniverse();
  31. typedef void* StackFrames;
  32. struct StackTrace
  33. {
  34. static StackFrames* GetStackFrames()
  35. {
  36. return NULL;
  37. }
  38. };
  39. #endif
  40. namespace il2cpp
  41. {
  42. namespace gc
  43. {
  44. enum AllocationKind
  45. {
  46. kPtrFree = 0,
  47. kNormal = 1,
  48. kUncollectable = 2,
  49. kObject = 3
  50. };
  51. struct AllocationInfo
  52. {
  53. size_t size;
  54. StackFrames stacktrace;
  55. #if HAS_POSIX_BACKTRACE || HAS_WINDOWS_BACKTRACE
  56. void *backtraceFrames[128];
  57. int frameCount;
  58. #endif
  59. AllocationKind kind;
  60. };
  61. static std::map<void*, AllocationInfo, std::greater<void*> > g_Allocations;
  62. static std::map<void**, void*> g_References;
  63. static void* g_MinHeap = (void*)0xffffffffffffffffULL;
  64. static void* g_MaxHeap = 0;
  65. static WriteBarrierValidation::ExternalAllocationTrackerFunction g_ExternalAllocationTrackerFunction = NULL;
  66. static WriteBarrierValidation::ExternalWriteBarrierTrackerFunction g_ExternalWriteBarrierTrackerFunction = NULL;
  67. static baselib::ReentrantLock s_AllocationMutex;
  68. static baselib::ReentrantLock s_WriteBarrierMutex;
  69. extern "C" void* GC_malloc_kind(size_t size, int k);
  70. #if HAS_POSIX_BACKTRACE
  71. std::string GetStackPosix(const AllocationInfo &info)
  72. {
  73. std::string result;
  74. char **frameStrings = backtrace_symbols(&info.backtraceFrames[0], info.frameCount);
  75. int frameCount = std::min(info.frameCount, 32);
  76. if (frameStrings != NULL)
  77. {
  78. for (int x = 0; x < frameCount; x++)
  79. {
  80. result += frameStrings[x];
  81. result += "\n";
  82. }
  83. free(frameStrings);
  84. }
  85. return result;
  86. }
  87. #endif
  88. void* GC_malloc_wrapper(size_t size, AllocationKind kind)
  89. {
  90. void* ptr = (char*)GC_malloc_kind(size, kind);
  91. memset(ptr, 0, size);
  92. if (g_ExternalAllocationTrackerFunction != NULL)
  93. g_ExternalAllocationTrackerFunction(ptr, size, kind);
  94. else
  95. {
  96. const StackFrames *trace = StackTrace::GetStackFrames();
  97. os::FastAutoLock lock(&s_AllocationMutex);
  98. AllocationInfo& allocation = g_Allocations[ptr];
  99. allocation.size = size;
  100. allocation.kind = kind;
  101. if (trace != NULL)
  102. allocation.stacktrace = *trace;
  103. #if HAS_POSIX_BACKTRACE
  104. allocation.frameCount = backtrace(&allocation.backtraceFrames[0], 128);
  105. #endif
  106. #if HAS_WINDOWS_BACKTRACE
  107. allocation.frameCount = CaptureStackBackTrace(0, 128, &allocation.backtraceFrames[0], NULL);
  108. #endif
  109. g_MinHeap = std::min(g_MinHeap, ptr);
  110. g_MaxHeap = std::max(g_MaxHeap, (void*)((char*)ptr + size));
  111. }
  112. return ptr;
  113. }
  114. extern "C" void GC_dirty_inner(void **ptr)
  115. {
  116. if (g_ExternalWriteBarrierTrackerFunction)
  117. g_ExternalWriteBarrierTrackerFunction(ptr);
  118. else
  119. {
  120. os::FastAutoLock lock(&s_WriteBarrierMutex);
  121. g_References[ptr] = *ptr;
  122. }
  123. }
  124. extern "C" void GC_free(void *ptr)
  125. {
  126. }
  127. extern "C" void* GC_malloc(size_t size)
  128. {
  129. return GC_malloc_wrapper(size, kNormal);
  130. }
  131. extern "C" void* GC_gcj_malloc(size_t size, void * ptr_to_struct_containing_descr)
  132. {
  133. void ** ptr = (void**)GC_malloc_wrapper(size, kObject);
  134. *ptr = ptr_to_struct_containing_descr;
  135. return ptr;
  136. }
  137. extern "C" void* GC_CALL GC_gcj_vector_malloc(size_t size, void * ptr_to_struct_containing_descr)
  138. {
  139. void ** ptr = (void**)GC_malloc_wrapper(size, kObject);
  140. *ptr = ptr_to_struct_containing_descr;
  141. return ptr;
  142. }
  143. extern "C" void* GC_malloc_uncollectable(size_t size)
  144. {
  145. return GC_malloc_wrapper(size, kUncollectable);
  146. }
  147. extern "C" void* GC_malloc_atomic(size_t size)
  148. {
  149. return GC_malloc_wrapper(size, kPtrFree);
  150. }
  151. static std::string ObjectName(void* object, AllocationKind kind)
  152. {
  153. if (kind != kObject)
  154. {
  155. switch (kind)
  156. {
  157. case kPtrFree: return "Kind: kPtrFree";
  158. case kNormal: return "Kind: kNormal";
  159. case kUncollectable: return "Kind: kUncollectable";
  160. default: return "?";
  161. }
  162. }
  163. #if IL2CPP_TINY_BACKEND
  164. ptrdiff_t typeOffset = reinterpret_cast<uint8_t*>(((Il2CppObject*)object)->klass) - Il2CppGetTinyTypeUniverse();
  165. return "Tiny Type Offset:" + std::to_string(typeOffset);
  166. #else
  167. Il2CppClass* klass = il2cpp_object_get_class((Il2CppObject*)(object));
  168. if (klass == NULL)
  169. return "";
  170. std::string name = il2cpp_class_get_name(klass);
  171. Il2CppClass* parent = il2cpp_class_get_declaring_type(klass);
  172. while (parent != NULL)
  173. {
  174. klass = parent;
  175. parent = il2cpp_class_get_declaring_type(klass);
  176. name = std::string(il2cpp_class_get_name(klass)) + "/" + name;
  177. }
  178. return std::string(il2cpp_class_get_namespace(klass)) + "::" + name;
  179. #endif
  180. }
  181. static std::string GetReadableStackTrace(const StackFrames &stackTrace)
  182. {
  183. #if IL2CPP_TINY_BACKEND
  184. return "No managed stack traces in Tiny";
  185. #else
  186. std::string str;
  187. for (StackFrames::const_iterator i = stackTrace.begin(); i != stackTrace.end(); i++)
  188. {
  189. Il2CppClass* parent = il2cpp_method_get_declaring_type(i->method);
  190. str += il2cpp_class_get_namespace(parent);
  191. str += '.';
  192. str += il2cpp_class_get_name(parent);
  193. str += ':';
  194. str += il2cpp_method_get_name(i->method);
  195. str += '\n';
  196. }
  197. return str;
  198. #endif
  199. }
  200. static std::string LogError(std::pair<void*, AllocationInfo> const & object, void** reference, void *refObject)
  201. {
  202. std::string msg;
  203. char chbuf[1024];
  204. snprintf(chbuf, 1024, "In object %p (%s) with size %zx at offset %zx, allocated at \n%s\n", object.first, ObjectName(object.first, object.second.kind).c_str(), object.second.size, (size_t)((char*)reference - (char*)object.first),
  205. #if HAS_POSIX_BACKTRACE
  206. GetStackPosix(object.second).c_str()
  207. #else
  208. GetReadableStackTrace(object.second.stacktrace).c_str()
  209. #endif
  210. );
  211. msg += chbuf;
  212. snprintf(chbuf, 1024, "Points to object %p of type (%s)\n", refObject, ObjectName(refObject, kPtrFree).c_str());
  213. msg += chbuf;
  214. return msg;
  215. }
  216. // Boehm internal constants
  217. #define GC_DS_TAG_BITS 2
  218. #define GC_DS_TAGS ((1 << GC_DS_TAG_BITS) - 1)
  219. #define GC_DS_LENGTH 0 /* The entire word is a length in bytes that */
  220. /* must be a multiple of 4. */
  221. #define GC_DS_BITMAP 1 /* 30 (62) bits are a bitmap describing pointer */
  222. #ifndef MARK_DESCR_OFFSET
  223. # define MARK_DESCR_OFFSET sizeof(void*)
  224. #endif
  225. void WriteBarrierValidation::SetExternalAllocationTracker(ExternalAllocationTrackerFunction func)
  226. {
  227. g_ExternalAllocationTrackerFunction = func;
  228. }
  229. void WriteBarrierValidation::SetExternalWriteBarrierTracker(ExternalWriteBarrierTrackerFunction func)
  230. {
  231. g_ExternalWriteBarrierTrackerFunction = func;
  232. }
  233. /* Taken from https://randomascii.wordpress.com/2012/02/14/64-bit-made-easy/
  234. Copyright 2012 Bruce Dawson. All Rights Reserved.
  235. Licensed under the Apache License, Version 2.0 (the "License");
  236. you may not use this file except in compliance with the License.
  237. You may obtain a copy of the License at
  238. http://www.apache.org/licenses/LICENSE-2.0
  239. Unless required by applicable law or agreed to in writing, software
  240. distributed under the License is distributed on an "AS IS" BASIS,
  241. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  242. See the License for the specific language governing permissions and
  243. limitations under the License.
  244. */
  245. void ReserveBottomMemory()
  246. {
  247. #if defined(_WIN64)
  248. static bool s_initialized = false;
  249. if (s_initialized)
  250. return;
  251. s_initialized = true;
  252. // Start by reserving large blocks of address space, and then
  253. // gradually reduce the size in order to capture all of the
  254. // fragments. Technically we should continue down to 64 KB but
  255. // stopping at 1 MB is sufficient to keep most allocators out.
  256. const size_t LOW_MEM_LINE = 0x1000000000LL; // Modified to reserve bottom 64 GB
  257. size_t totalReservation = 0;
  258. size_t numVAllocs = 0;
  259. size_t numHeapAllocs = 0;
  260. size_t oneMB = 1024 * 1024;
  261. size_t sixtyFourKB = 64 * 1024; // Modified to continue down to 64 KB as our GC allocates chunks in 256 KB
  262. for (size_t size = 256 * oneMB; size >= sixtyFourKB; size /= 2)
  263. {
  264. for (;;)
  265. {
  266. void* p = VirtualAlloc(0, size, MEM_RESERVE, PAGE_NOACCESS);
  267. if (!p)
  268. break;
  269. if ((size_t)p >= LOW_MEM_LINE)
  270. {
  271. // We don't need this memory, so release it completely.
  272. VirtualFree(p, 0, MEM_RELEASE);
  273. break;
  274. }
  275. totalReservation += size;
  276. ++numVAllocs;
  277. }
  278. }
  279. // Now repeat the same process but making heap allocations, to use up
  280. // the already reserved heap blocks that are below the 4 GB line.
  281. HANDLE heap = GetProcessHeap();
  282. for (size_t blockSize = 64 * 1024; blockSize >= 16; blockSize /= 2)
  283. {
  284. for (;;)
  285. {
  286. void* p = HeapAlloc(heap, 0, blockSize);
  287. if (!p)
  288. break;
  289. if ((size_t)p >= LOW_MEM_LINE)
  290. {
  291. // We don't need this memory, so release it completely.
  292. HeapFree(heap, 0, p);
  293. break;
  294. }
  295. totalReservation += blockSize;
  296. ++numHeapAllocs;
  297. }
  298. }
  299. // Perversely enough the CRT doesn't use the process heap. Consume up
  300. // the memory the CRT heap has already reserved.
  301. for (size_t blockSize = 64 * 1024; blockSize >= 16; blockSize /= 2)
  302. {
  303. for (;;)
  304. {
  305. void* p = malloc(blockSize);
  306. if (!p)
  307. break;
  308. if ((size_t)p >= LOW_MEM_LINE)
  309. {
  310. // We don't need this memory, so release it completely.
  311. free(p);
  312. break;
  313. }
  314. totalReservation += blockSize;
  315. ++numHeapAllocs;
  316. }
  317. }
  318. // Print diagnostics showing how many allocations we had to make in
  319. // order to reserve all of low memory, typically less than 200.
  320. char buffer[1000];
  321. sprintf_s(buffer, "Reserved %1.3f MB (%d vallocs,"
  322. "%d heap allocs) of low-memory.\n",
  323. totalReservation / (1024 * 1024.0),
  324. (int)numVAllocs, (int)numHeapAllocs);
  325. OutputDebugStringA(buffer);
  326. #endif
  327. }
  328. void WriteBarrierValidation::Setup()
  329. {
  330. // Reserve bottom 64 GB of memory to force GC into high addresses
  331. // This prevents hashes colliding with heap addresses and causing false detections.
  332. ReserveBottomMemory();
  333. GarbageCollector::Disable();
  334. }
  335. void WriteBarrierValidation::Run()
  336. {
  337. if (g_ExternalAllocationTrackerFunction != NULL)
  338. return;
  339. std::string msg;
  340. msg = "<TestResult Name='WriteBarrierValidation'>\n<![CDATA[\n";
  341. size_t errors = 0;
  342. for (std::map<void*, AllocationInfo>::iterator i = g_Allocations.begin(); i != g_Allocations.end(); i++)
  343. {
  344. if (i->second.kind == kPtrFree)
  345. continue;
  346. intptr_t desc = (intptr_t)GC_NO_DESCRIPTOR;
  347. if (i->second.kind == kObject)
  348. {
  349. desc = *(intptr_t*)(((char*)(*(void**)i->first)) + MARK_DESCR_OFFSET);
  350. if ((desc & GC_DS_TAGS) != GC_DS_BITMAP)
  351. desc = (intptr_t)GC_NO_DESCRIPTOR;
  352. }
  353. for (void** ptr = ((void**)i->first) + 2; ptr < (void**)((char*)i->first + i->second.size); ptr++)
  354. {
  355. if (desc != (intptr_t)GC_NO_DESCRIPTOR)
  356. {
  357. // if we have a GC descriptor bitmap, check if this address can be a pointer, skip otherwise.
  358. size_t ptr_index = ptr - (void**)i->first;
  359. if (((desc >> (sizeof(void*) * 8 - ptr_index - 1)) & 1) == 0)
  360. continue;
  361. }
  362. void* ref = *ptr;
  363. if (ref < g_MinHeap || ref >= g_MaxHeap)
  364. continue;
  365. std::map<void*, AllocationInfo>::iterator j = g_Allocations.lower_bound(ref);
  366. if (j != g_Allocations.end() && j != i && j->second.kind != kUncollectable)
  367. {
  368. if (j->first <= ref && (void*)((char*)j->first + j->second.size) > ref)
  369. {
  370. std::map<void**, void*>::iterator trackedRef = g_References.find(ptr);
  371. if (trackedRef == g_References.end())
  372. {
  373. char chbuf[1024];
  374. snprintf(chbuf, 1024, "\n%p looks like a reference to %p, but was not found in tracked references\n", ptr, ref);
  375. msg += chbuf;
  376. errors++;
  377. msg += LogError(*i, ptr, j->first);
  378. }
  379. else if (trackedRef->second != ref)
  380. {
  381. char chbuf[1024];
  382. snprintf(chbuf, 1024, "\n%p does not match tracked value (%p!=%p).\n", ptr, trackedRef->second, ref);
  383. msg += chbuf;
  384. errors++;
  385. msg += LogError(*i, ptr, j->first);
  386. }
  387. }
  388. }
  389. }
  390. }
  391. msg += "]]>\n</TestResult>\n";
  392. if (errors > 0)
  393. printf("%s", msg.c_str());
  394. }
  395. } /* gc */
  396. } /* il2cpp */
  397. #endif