Logo AND Algorithmique Numérique Distribuée

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