Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
java: cosmetics
[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 }
33
34 JavaContextFactory::~JavaContextFactory()=default;
35
36 JavaContext* JavaContextFactory::self()
37 {
38   return static_cast<JavaContext*>(xbt_os_thread_get_extra_data());
39 }
40
41 JavaContext* JavaContextFactory::create_context(std::function<void()> code, void_pfn_smxprocess_t cleanup_fun,
42                                                 smx_actor_t actor)
43 {
44   return this->new_context<JavaContext>(std::move(code), cleanup_fun, actor);
45 }
46
47 void JavaContextFactory::run_all()
48 {
49   for (smx_actor_t const& process : simgrid::simix::process_get_runnable()) {
50     static_cast<JavaContext*>(process->context_)->resume();
51   }
52 }
53
54 JavaContext::JavaContext(std::function<void()> code,
55         void_pfn_smxprocess_t cleanup_func,
56         smx_actor_t process)
57   : Context(std::move(code), cleanup_func, process)
58 {
59   static int thread_amount=0;
60   thread_amount++;
61
62   /* If the user provided a function for the process then use it otherwise is the context for maestro */
63   if (has_code()) {
64     this->begin = xbt_os_sem_init(0);
65     this->end = xbt_os_sem_init(0);
66
67     try {
68        this->thread = xbt_os_thread_create(
69          nullptr, JavaContext::wrapper, this, nullptr);
70     }
71     catch (xbt_ex& ex) {
72       char* str = bprintf(
73         "Failed to create context #%d. You may want to switch to Java coroutines to increase your limits (error: %s)."
74         "See the Install section of simgrid-java documentation (in doc/install.html) for more on coroutines.",
75         thread_amount, ex.what());
76       xbt_ex new_exception(XBT_THROW_POINT, str);
77       new_exception.category = ex.category;
78       new_exception.value = ex.value;
79       std::throw_with_nested(std::move(new_exception));
80     }
81   } else {
82     xbt_os_thread_set_extra_data(this);
83   }
84 }
85
86 JavaContext::~JavaContext()
87 {
88   if (this->thread) {
89     // We are not in maestro context
90     xbt_os_thread_join(this->thread, nullptr);
91     xbt_os_sem_destroy(this->begin);
92     xbt_os_sem_destroy(this->end);
93   }
94 }
95
96 void* JavaContext::wrapper(void *data)
97 {
98   JavaContext* context = static_cast<JavaContext*>(data);
99   xbt_os_thread_set_extra_data(context);
100   //Attach the thread to the JVM
101
102   JNIEnv *env;
103   XBT_ATTRIB_UNUSED jint error = __java_vm->AttachCurrentThread((void**)&env, nullptr);
104   xbt_assert((error == JNI_OK), "The thread could not be attached to the JVM");
105   context->jenv = env;
106   //Wait for the first scheduling round to happen.
107   xbt_os_sem_acquire(context->begin);
108   //Create the "Process" object if needed.
109   (*context)();
110   context->stop();
111   return nullptr;
112 }
113
114 void JavaContext::stop()
115 {
116   /* I was asked to die (either with kill() or because of a failed element) */
117   if (this->iwannadie) {
118     this->iwannadie = 0;
119     JNIEnv *env = get_current_thread_env();
120     XBT_DEBUG("Gonna launch Killed Error");
121     // When the process wants to stop before its regular end, we should cut its call stack quickly.
122     // The easiest way to do so is to raise an exception that will be catched in its top calling level.
123     //
124     // For that, we raise a ProcessKilledError that is catched in Process::run() (in msg/Process.java)
125     //
126     // Throwing a Java exception to stop the actor may be an issue for pure C actors
127     // (as the ones created for the VM migration). The Java exception will not be catched anywhere.
128     // Bad things happen currently if these actors get killed, unfortunately.
129     jxbt_throw_by_name(env, "org/simgrid/msg/ProcessKilledError",
130                        std::string("Process ") + this->process()->get_cname() + " killed from file JavaContext.cpp");
131
132     // (remember that throwing a java exception from C does not break the C execution path.
133     //  Instead, it marks the exception to be raised when returning to the Java world and
134     //  continues to execute the C function until it ends or returns).
135
136     // Once the Java stack is marked to be unrolled, a C cancel_error is raised to kill the simcall
137     //  on which the killed actor is blocked (if any).
138     // Not doing so would prevent the actor to notice that it's dead, leading to segfaults when it wakes up.
139     // This is dangerous: if the killed actor is not actually blocked, the cancel_error will not get catched.
140     // But it should be OK in most cases:
141     //  - If I kill myself, I must do so with Process.kill().
142     //    The binding of this function in jmsg_process.cpp adds a try/catch around the MSG_process_kill() leading to us
143     //  - If I kill someone else that is blocked, the cancel_error will unblock it.
144     //
145     // A problem remains probably if I kill a process that is ready_to_run in the same scheduling round.
146     // I guess that this will kill the whole simulation because the victim does not catch the exception.
147     // The only solution I see to that problem would be to completely rewrite the process killing sequence
148     // (also in C) so that it's based on regular C++ exceptions that would be catched anyway.
149     // In other words, we need to do in C++ what we do in Java for sake of uniformity.
150     //
151     // Plus, C++ RAII would work in that case, too.
152
153     XBT_DEBUG("Trigger a cancel error at the C level");
154     THROWF(cancel_error, 0, "process cancelled");
155   } else {
156     Context::stop();
157     /* detach the thread and kills it */
158     JNIEnv *env = this->jenv;
159     env->DeleteGlobalRef(this->jprocess);
160     XBT_ATTRIB_UNUSED jint error = __java_vm->DetachCurrentThread();
161     xbt_assert((error == JNI_OK), "The thread couldn't be detached.");
162     xbt_os_sem_release(this->end);
163     xbt_os_thread_exit(nullptr);
164   }
165 }
166
167 void JavaContext::suspend()
168 {
169   xbt_os_sem_release(this->end);
170   xbt_os_sem_acquire(this->begin);
171 }
172
173 // FIXME: inline those functions
174 void JavaContext::resume()
175 {
176   xbt_os_sem_release(this->begin);
177   xbt_os_sem_acquire(this->end);
178 }
179
180 }}} // namespace simgrid::kernel::context