Logo AND Algorithmique Numérique Distribuée

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