#ifndef MRT_SCOPED_SAFEREGION_H
#define MRT_SCOPED_SAFEREGION_H
#include "Mutator/Mutator.inline.h"
namespace MapleRuntime {
class ScopedEnterSaferegion {
public:
ScopedEnterSaferegion() = delete;
explicit ScopedEnterSaferegion(bool onlyForMutator = false)
{
Mutator* mutator = Mutator::GetMutator();
ThreadType threadType = ThreadLocal::GetThreadType();
if (onlyForMutator &&
(threadType == ThreadType::FP_THREAD || threadType == ThreadType::GC_THREAD)) {
stateChanged = false;
} else {
stateChanged = (mutator != nullptr) ? mutator->EnterSaferegion(true) : false;
}
}
~ScopedEnterSaferegion()
{
if (LIKELY(stateChanged)) {
Mutator* mutator = Mutator::GetMutator();
(void)mutator->LeaveSaferegion();
}
}
private:
bool stateChanged;
};
class ScopedObjectAccess {
public:
ScopedObjectAccess() : mutator(Mutator::GetMutator()),
leavedSafeRegion(mutator == nullptr ? false : mutator->LeaveSaferegion()) {}
~ScopedObjectAccess()
{
if (LIKELY(leavedSafeRegion)) {
(void)mutator->EnterSaferegion(false);
}
}
private:
Mutator* mutator{ nullptr };
bool leavedSafeRegion;
};
}
#endif