Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' into v3.20-expose-simgrid-jni
[simgrid.git] / src / bindings / java / JavaContext.cpp
1 /* Context switching within the JVM.                                        */
2
3 /* Copyright (c) 2009-2018. The SimGrid Team. All rights reserved.          */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include "JavaContext.hpp"
9 #include "jxbt_utilities.hpp"
10 #include "simgrid/Exception.hpp"
11 #include "src/simix/smx_private.hpp"
12
13 #include <functional>
14 #include <utility>
15
16 extern JavaVM* __java_vm;
17
18 XBT_LOG_NEW_DEFAULT_CATEGORY(java, "MSG for Java(TM)");
19
20 namespace simgrid {
21 namespace kernel {
22 namespace context {
23
24 ContextFactory* java_factory()
25 {
26   XBT_INFO("Using regular java threads.");
27   return new JavaContextFactory();
28 }
29
30 JavaContextFactory::JavaContextFactory(): ContextFactory("JavaContextFactory")
31 {
32   xbt_binary_name = xbt_strdup("java"); // Used by the backtrace displayer
33 }
34
35 JavaContextFactory::~JavaContextFactory()=default;
36
37 JavaContext* JavaContextFactory::self()
38 {
39   return static_cast<JavaContext*>(xbt_os_thread_get_extra_data());
40 }
41
42 JavaContext* JavaContextFactory::create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup_fun,
43                                                 smx_actor_t actor)
44 {
45   return this->new_context<JavaContext>(std::move(code), cleanup_fun, actor);
46 }
47
48 void JavaContextFactory::run_all()
49 {
50   SerialThreadContext::run_all();
51 }
52
53 JavaContext::JavaContext(std::function<void()> code, void_pfn_smxprocess_t cleanup_func, smx_actor_t process)
54     : SerialThreadContext(std::move(code), cleanup_func, process, false /* not maestro */)
55 {
56   /* ThreadContext already does all we need */
57 }
58
59 void JavaContext::start_hook()
60 {
61   xbt_os_thread_set_extra_data(this); // We need to attach it also for maestro, in contrary to our ancestor
62
63   //Attach the thread to the JVM
64   JNIEnv *env;
65   XBT_ATTRIB_UNUSED jint error = __java_vm->AttachCurrentThread((void**)&env, nullptr);
66   xbt_assert((error == JNI_OK), "The thread could not be attached to the JVM");
67   this->jenv_ = env;
68 }
69
70 void JavaContext::stop()
71 {
72   /* I was asked to die (either with kill() or because of a failed element) */
73   if (this->iwannadie) {
74     this->iwannadie = 0;
75     JNIEnv* env     = this->jenv_;
76     XBT_DEBUG("Gonna launch Killed Error");
77     // When the process wants to stop before its regular end, we should cut its call stack quickly.
78     // The easiest way to do so is to raise an exception that will be catched in its top calling level.
79     //
80     // For that, we raise a ProcessKilledError that is catched in Process::run() (in msg/Process.java)
81     //
82     // Throwing a Java exception to stop the actor may be an issue for pure C actors
83     // (as the ones created for the VM migration). The Java exception will not be catched anywhere.
84     // Bad things happen currently if these actors get killed, unfortunately.
85     jxbt_throw_by_name(env, "org/simgrid/msg/ProcessKilledError",
86                        std::string("Process ") + this->process()->get_cname() + " killed from file JavaContext.cpp");
87
88     // (remember that throwing a java exception from C does not break the C execution path.
89     //  Instead, it marks the exception to be raised when returning to the Java world and
90     //  continues to execute the C function until it ends or returns).
91
92     // Once the Java stack is marked to be unrolled, a C cancel_error is raised to kill the simcall
93     //  on which the killed actor is blocked (if any).
94     // Not doing so would prevent the actor to notice that it's dead, leading to segfaults when it wakes up.
95     // This is dangerous: if the killed actor is not actually blocked, the cancel_error will not get catched.
96     // But it should be OK in most cases:
97     //  - If I kill myself, I must do so with Process.kill().
98     //    The binding of this function in jmsg_process.cpp adds a try/catch around the MSG_process_kill() leading to us
99     //  - If I kill someone else that is blocked, the cancel_error will unblock it.
100     //
101     // A problem remains probably if I kill a process that is ready_to_run in the same scheduling round.
102     // I guess that this will kill the whole simulation because the victim does not catch the exception.
103     // The only solution I see to that problem would be to completely rewrite the process killing sequence
104     // (also in C) so that it's based on regular C++ exceptions that would be catched anyway.
105     // In other words, we need to do in C++ what we do in Java for sake of uniformity.
106     //
107     // Plus, C++ RAII would work in that case, too.
108     XBT_DEBUG("Trigger a cancel error at the C level");
109     THROWF(cancel_error, 0, "process cancelled");
110   } else {
111     ThreadContext::stop();
112     JNIEnv* env = this->jenv_;
113     env->DeleteGlobalRef(this->jprocess_);
114     XBT_ATTRIB_UNUSED jint error = __java_vm->DetachCurrentThread();
115     xbt_assert((error == JNI_OK), "The thread couldn't be detached.");
116     xbt_os_thread_exit(nullptr);
117   }
118 }
119
120 }}} // namespace simgrid::kernel::context