暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

WriteBarrierValidation.cpp 14KB

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