From dc8681cebf37c422ad218e3640475f8212677d06 Mon Sep 17 00:00:00 2001 From: Svyatoslav Scherbina Date: Wed, 15 Apr 2020 17:49:50 +0300 Subject: [PATCH] Fix race in cyclic collector Prevent cyclic collector from observing newly allocated atomic root with RC = 0. --- runtime/src/main/cpp/Memory.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/runtime/src/main/cpp/Memory.cpp b/runtime/src/main/cpp/Memory.cpp index 1319c1315a8..c415889dec2 100644 --- a/runtime/src/main/cpp/Memory.cpp +++ b/runtime/src/main/cpp/Memory.cpp @@ -1940,11 +1940,6 @@ OBJ_GETTER(allocInstance, const TypeInfo* type_info) { #endif // USE_GC auto container = ObjectContainer(state, type_info); ObjHeader* obj = container.GetPlace(); -#if USE_CYCLIC_GC - if ((obj->type_info()->flags_ & TF_LEAK_DETECTOR_CANDIDATE) != 0) { - cyclicAddAtomicRoot(obj); - } -#endif // USE_CYCLIC_GC #if USE_GC if (Strict) { rememberNewContainer(container.header()); @@ -1952,6 +1947,14 @@ OBJ_GETTER(allocInstance, const TypeInfo* type_info) { makeShareable(container.header()); } #endif // USE_GC +#if USE_CYCLIC_GC + if ((obj->type_info()->flags_ & TF_LEAK_DETECTOR_CANDIDATE) != 0) { + // Note: this should be performed after [rememberNewContainer] (above). + // Otherwise cyclic collector can observe this atomic root with RC = 0, + // thus consider it garbage and then zero it after initialization. + cyclicAddAtomicRoot(obj); + } +#endif // USE_CYCLIC_GC RETURN_OBJ(obj); }