Skip to content
This repository has been archived by the owner on Aug 10, 2021. It is now read-only.

Commit

Permalink
Do not use counting logic
Browse files Browse the repository at this point in the history
  • Loading branch information
projedi committed Nov 3, 2020
1 parent 6c26926 commit ea26c4c
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions runtime/src/main/cpp/Runtime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,12 @@ RuntimeState* initRuntime() {
return result;
}

void deinitRuntime(RuntimeState* state) {
void deinitRuntime(RuntimeState* state, bool destroyRuntime) {
RuntimeAssert(state->status == RuntimeStatus::kRunning, "Runtime must be in the running state");
state->status = RuntimeStatus::kDestroying;
// This may be called after TLS is zeroed out, so ::memoryState in Memory cannot be trusted.
RestoreMemory(state->memoryState);
bool lastRuntime = atomicAdd(&aliveRuntimesCount, -1) == 0;
bool destroyRuntime = lastRuntime && atomicGet(&globalRuntimeStatus) == GLOBAL_RUNTIME_DESTROYED;
atomicAdd(&aliveRuntimesCount, -1);
InitOrDeinitGlobalVariables(DEINIT_THREAD_LOCAL_GLOBALS, state->memoryState);
if (destroyRuntime)
InitOrDeinitGlobalVariables(DEINIT_GLOBALS, state->memoryState);
Expand All @@ -128,7 +127,7 @@ void deinitRuntime(RuntimeState* state) {

void Kotlin_deinitRuntimeCallback(void* argument) {
auto* state = reinterpret_cast<RuntimeState*>(argument);
deinitRuntime(state);
deinitRuntime(state, false);
}

} // namespace
Expand Down Expand Up @@ -159,7 +158,7 @@ void Kotlin_initRuntimeIfNeeded() {

void Kotlin_deinitRuntimeIfNeeded() {
if (isValidRuntime()) {
deinitRuntime(::runtimeState);
deinitRuntime(::runtimeState, false);
::runtimeState = kInvalidRuntime;
}
}
Expand All @@ -184,7 +183,21 @@ void Kotlin_destroyRuntime() {

atomicSet(&globalRuntimeStatus, GLOBAL_RUNTIME_DESTROYED);

Kotlin_deinitRuntimeIfNeeded();
// At this point `aliveRuntimesCount` can only go down as no new runtime can be created.
bool otherRuntimesCount = atomicGet(&aliveRuntimesCount) - 1;
RuntimeAssert(otherRuntimesCount >= 0, "Cannot be negative");

if (Kotlin_cleanersLeakCheckerEnabled() || Kotlin_memoryLeakCheckerEnabled()) {
// Checkers can only work if this is the last runtime.
if (otherRuntimesCount > 0) {
konan::consoleErrorf(
"Cannot destroy runtime while there're %d alive threads with Kotlin runtime on them.\n", otherRuntimesCount);
konan::abort();
}
}

deinitRuntime(::runtimeState, otherRuntimesCount == 0);
::runtimeState = kInvalidRuntime;
}

KInt Konan_Platform_canAccessUnaligned() {
Expand Down

0 comments on commit ea26c4c

Please sign in to comment.