Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid jacop-related crashes due to destructor execution order #133

Merged
merged 1 commit into from
May 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions solvers/jacop/java.cc
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ std::string RegKey::GetStrValue(fmt::CStringRef name) const {

namespace mp {

JVM JVM::instance_;
JVM *JVM::instance_;

void Env::Throw(jthrowable exception, const char *method_name) {
env_->ExceptionClear();
Expand Down Expand Up @@ -190,8 +190,16 @@ JVM::~JVM() {
jvm_->DestroyJavaVM();
}

void JVM::cleanup_jvm()
{
if (instance_) {
delete instance_;
instance_ = nullptr;
}
}

Env JVM::env(const char *const *options) {
if (!instance_.jvm_) {
if (!instance_) {
#ifdef _WIN32
std::string runtime_lib_path;
bool exists = false;
Expand Down Expand Up @@ -251,15 +259,19 @@ Env JVM::env(const char *const *options) {
}
vm_args.nOptions = static_cast<jint>(jvm_options.size());
vm_args.options = &jvm_options[0];
instance_ = new JVM();
void *envp = 0;
jint result = JNI_CreateJavaVM(&instance_.jvm_, &envp, &vm_args);
jint result = JNI_CreateJavaVM(&instance_->jvm_, &envp, &vm_args);
if (result != JNI_OK) {
delete instance_;
instance_ = nullptr;
throw JavaError(fmt::format(
"Java VM initialization failed, error code = {}", result));
}
instance_.env_ = Env(static_cast<JNIEnv*>(envp));
instance_->env_ = Env(static_cast<JNIEnv*>(envp));
std::atexit(cleanup_jvm);
}
return instance_.env_;
return instance_->env_;
}

ClassBase::~ClassBase() {}
Expand Down
3 changes: 2 additions & 1 deletion solvers/jacop/java.h
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ class JVM {
private:
JavaVM *jvm_;
Env env_;
static JVM instance_;
static JVM *instance_;
static void cleanup_jvm();

JVM() : jvm_() {}
~JVM();
Expand Down