1 /*
  2  * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 #ifndef SHARE_JVMCI_JVMCIRUNTIME_HPP
 25 #define SHARE_JVMCI_JVMCIRUNTIME_HPP
 26 
 27 #include "jvm_io.h"
 28 #include "code/nmethod.hpp"
 29 #include "gc/shared/collectedHeap.hpp"
 30 #include "jvmci/jvmci.hpp"
 31 #include "jvmci/jvmciExceptions.hpp"
 32 #include "jvmci/jvmciObject.hpp"
 33 #include "utilities/linkedlist.hpp"
 34 #if INCLUDE_G1GC
 35 #include "gc/g1/g1CardTable.hpp"
 36 #endif // INCLUDE_G1GC
 37 
 38 class JVMCIEnv;
 39 class JVMCICompiler;
 40 class JVMCICompileState;
 41 class MetadataHandles;
 42 
 43 // Encapsulates the JVMCI metadata for an nmethod.
 44 // JVMCINMethodData objects are inlined into nmethods
 45 // at nmethod::_jvmci_data_offset.
 46 class JVMCINMethodData {
 47   friend class JVMCIVMStructs;
 48   // Index for the HotSpotNmethod mirror in the nmethod's oops table.
 49   // This is -1 if there is no mirror in the oops table.
 50   int _nmethod_mirror_index;
 51 
 52   // Is HotSpotNmethod.name non-null? If so, the value is
 53   // embedded in the end of this object.
 54   bool _has_name;
 55 
 56   // Address of the failed speculations list to which a speculation
 57   // is appended when it causes a deoptimization.
 58   FailedSpeculation** _failed_speculations;
 59 
 60   // A speculation id is a length (low 5 bits) and an index into
 61   // a jbyte array (i.e. 31 bits for a positive Java int).
 62   enum {
 63     // Keep in sync with HotSpotSpeculationEncoding.
 64     SPECULATION_LENGTH_BITS = 5,
 65     SPECULATION_LENGTH_MASK = (1 << SPECULATION_LENGTH_BITS) - 1
 66   };
 67 
 68 public:
 69   // Computes the size of a JVMCINMethodData object
 70   static int compute_size(const char* nmethod_mirror_name) {
 71     int size = sizeof(JVMCINMethodData);
 72     if (nmethod_mirror_name != NULL) {
 73       size += (int) strlen(nmethod_mirror_name) + 1;
 74     }
 75     return size;
 76   }
 77 
 78   void initialize(int nmethod_mirror_index,
 79              const char* name,
 80              FailedSpeculation** failed_speculations);
 81 
 82   // Adds `speculation` to the failed speculations list.
 83   void add_failed_speculation(nmethod* nm, jlong speculation);
 84 
 85   // Gets the JVMCI name of the nmethod (which may be NULL).
 86   const char* name() { return _has_name ? (char*)(((address) this) + sizeof(JVMCINMethodData)) : NULL; }
 87 
 88   // Clears the HotSpotNmethod.address field in the  mirror. If nm
 89   // is dead, the HotSpotNmethod.entryPoint field is also cleared.
 90   void invalidate_nmethod_mirror(nmethod* nm);
 91 
 92   // Gets the mirror from nm's oops table.
 93   oop get_nmethod_mirror(nmethod* nm, bool phantom_ref);
 94 
 95   // Sets the mirror in nm's oops table.
 96   void set_nmethod_mirror(nmethod* nm, oop mirror);
 97 
 98   // Clears the mirror in nm's oops table.
 99   void clear_nmethod_mirror(nmethod* nm);
100 };
101 
102 // A top level class that represents an initialized JVMCI runtime.
103 // There is one instance of this class per HotSpotJVMCIRuntime object.
104 class JVMCIRuntime: public CHeapObj<mtJVMCI> {
105   friend class JVMCI;
106  public:
107   // Constants describing whether JVMCI wants to be able to adjust the compilation
108   // level selected for a method by the VM compilation policy and if so, based on
109   // what information about the method being schedule for compilation.
110   enum CompLevelAdjustment {
111      none = 0,             // no adjustment
112      by_holder = 1,        // adjust based on declaring class of method
113      by_full_signature = 2 // adjust based on declaring class, name and signature of method
114   };
115 
116  private:
117 
118   enum InitState {
119     uninitialized,
120     being_initialized,
121     fully_initialized
122   };
123 
124   // Initialization state of this JVMCIRuntime.
125   InitState _init_state;
126 
127   // A wrapper for a VM scoped JNI global handle (i.e. JVMCIEnv::make_global)
128   // to a HotSpotJVMCIRuntime instance. This JNI global handle must never
129   // be explicitly destroyed as it can be accessed in a racy way during
130   // JVMCI shutdown. Furthermore, it will be reclaimed when
131   // the VM or shared library JavaVM managing the handle dies.
132   JVMCIObject _HotSpotJVMCIRuntime_instance;
133 
134   // Result of calling JNI_CreateJavaVM in the JVMCI shared library.
135   // Must only be modified under JVMCI_lock.
136   volatile JavaVM* _shared_library_javavm;
137 
138   // The HotSpot heap based runtime will have an id of -1 and the
139   // JVMCI shared library runtime will have an id of 0.
140   int _id;
141 
142   // Handles to Metadata objects.
143   MetadataHandles* _metadata_handles;
144 
145   JVMCIObject create_jvmci_primitive_type(BasicType type, JVMCI_TRAPS);
146 
147   // Implementation methods for loading and constant pool access.
148   static Klass* get_klass_by_name_impl(Klass*& accessing_klass,
149                                        const constantPoolHandle& cpool,
150                                        Symbol* klass_name,
151                                        bool require_local);
152   static Klass*   get_klass_by_index_impl(const constantPoolHandle& cpool,
153                                           int klass_index,
154                                           bool& is_accessible,
155                                           Klass* loading_klass);
156   static void   get_field_by_index_impl(InstanceKlass* loading_klass, fieldDescriptor& fd,
157                                         int field_index);
158   static Method*  get_method_by_index_impl(const constantPoolHandle& cpool,
159                                            int method_index, Bytecodes::Code bc,
160                                            InstanceKlass* loading_klass);
161 
162   // Helper methods
163   static bool       check_klass_accessibility(Klass* accessing_klass, Klass* resolved_klass);
164   static Method*    lookup_method(InstanceKlass*  accessor,
165                                   Klass*  holder,
166                                   Symbol*         name,
167                                   Symbol*         sig,
168                                   Bytecodes::Code bc,
169                                   constantTag     tag);
170 
171  public:
172   JVMCIRuntime(int id);
173 
174   int id() const        { return _id;   }
175 
176   // Ensures that a JVMCI shared library JavaVM exists for this runtime.
177   // If the JavaVM was created by this call, then the thread-local JNI
178   // interface pointer for the JavaVM is returned otherwise NULL is returned.
179   JNIEnv* init_shared_library_javavm();
180 
181   // Determines if the JVMCI shared library JavaVM exists for this runtime.
182   bool has_shared_library_javavm() { return _shared_library_javavm != NULL; }
183 
184   // Copies info about the JVMCI shared library JavaVM associated with this
185   // runtime into `info` as follows:
186   // {
187   //     javaVM, // the {@code JavaVM*} value
188   //     javaVM->functions->reserved0,
189   //     javaVM->functions->reserved1,
190   //     javaVM->functions->reserved2
191   // }
192   void init_JavaVM_info(jlongArray info, JVMCI_TRAPS);
193 
194   // Wrappers for calling Invocation Interface functions on the
195   // JVMCI shared library JavaVM associated with this runtime.
196   // These wrappers ensure all required thread state transitions are performed.
197   jint AttachCurrentThread(JavaThread* thread, void **penv, void *args);
198   jint AttachCurrentThreadAsDaemon(JavaThread* thread, void **penv, void *args);
199   jint DetachCurrentThread(JavaThread* thread);
200   jint GetEnv(JavaThread* thread, void **penv, jint version);
201 
202   // Compute offsets and construct any state required before executing JVMCI code.
203   void initialize(JVMCIEnv* jvmciEnv);
204 
205   // Allocation and management of JNI global object handles
206   // whose lifetime is scoped by this JVMCIRuntime. The lifetime
207   // of these handles is the same as the JVMCI shared library JavaVM
208   // associated with this JVMCIRuntime. These JNI handles are
209   // used when creating a IndirectHotSpotObjectConstantImpl in the
210   // shared library JavaVM.
211   jobject make_global(const Handle& obj);
212   void destroy_global(jobject handle);
213   bool is_global_handle(jobject handle);
214 
215   // Allocation and management of metadata handles.
216   jmetadata allocate_handle(const methodHandle& handle);
217   jmetadata allocate_handle(const constantPoolHandle& handle);
218   void release_handle(jmetadata handle);
219 
220   // Gets the HotSpotJVMCIRuntime instance for this runtime,
221   // initializing it first if necessary.
222   JVMCIObject get_HotSpotJVMCIRuntime(JVMCI_TRAPS);
223 
224   bool is_HotSpotJVMCIRuntime_initialized() {
225     return _HotSpotJVMCIRuntime_instance.is_non_null();
226   }
227 
228   // Gets the current HotSpotJVMCIRuntime instance for this runtime which
229   // may be a "null" JVMCIObject value.
230   JVMCIObject probe_HotSpotJVMCIRuntime() {
231     return _HotSpotJVMCIRuntime_instance;
232   }
233 
234   // Trigger initialization of HotSpotJVMCIRuntime through JVMCI.getRuntime()
235   void initialize_JVMCI(JVMCI_TRAPS);
236 
237   // Explicitly initialize HotSpotJVMCIRuntime itself
238   void initialize_HotSpotJVMCIRuntime(JVMCI_TRAPS);
239 
240   void call_getCompiler(TRAPS);
241 
242   // Shuts down this runtime by calling HotSpotJVMCIRuntime.shutdown().
243   void shutdown();
244 
245   void bootstrap_finished(TRAPS);
246 
247   // Look up a klass by name from a particular class loader (the accessor's).
248   // If require_local, result must be defined in that class loader, or NULL.
249   // If !require_local, a result from remote class loader may be reported,
250   // if sufficient class loader constraints exist such that initiating
251   // a class loading request from the given loader is bound to return
252   // the class defined in the remote loader (or throw an error).
253   //
254   // Return an unloaded klass if !require_local and no class at all is found.
255   //
256   // The CI treats a klass as loaded if it is consistently defined in
257   // another loader, even if it hasn't yet been loaded in all loaders
258   // that could potentially see it via delegation.
259   static Klass* get_klass_by_name(Klass* accessing_klass,
260                                   Symbol* klass_name,
261                                   bool require_local);
262 
263   // Constant pool access.
264   static Klass*   get_klass_by_index(const constantPoolHandle& cpool,
265                                      int klass_index,
266                                      bool& is_accessible,
267                                      Klass* loading_klass);
268   static void   get_field_by_index(InstanceKlass* loading_klass, fieldDescriptor& fd,
269                                    int field_index);
270   static Method*  get_method_by_index(const constantPoolHandle& cpool,
271                                       int method_index, Bytecodes::Code bc,
272                                       InstanceKlass* loading_klass);
273 
274   // converts the Klass* representing the holder of a method into a
275   // InstanceKlass*.  This is needed since the holder of a method in
276   // the bytecodes could be an array type.  Basically this converts
277   // array types into java/lang/Object and other types stay as they are.
278   static InstanceKlass* get_instance_klass_for_declared_method_holder(Klass* klass);
279 
280   // Helper routine for determining the validity of a compilation
281   // with respect to concurrent class loading.
282   static JVMCI::CodeInstallResult validate_compile_task_dependencies(Dependencies* target, JVMCICompileState* task, char** failure_detail);
283 
284   // Compiles `target` with the JVMCI compiler.
285   void compile_method(JVMCIEnv* JVMCIENV, JVMCICompiler* compiler, const methodHandle& target, int entry_bci);
286 
287   // Determines if the GC identified by `name` is supported by the JVMCI compiler.
288   bool is_gc_supported(JVMCIEnv* JVMCIENV, CollectedHeap::Name name);
289 
290   // Register the result of a compilation.
291   JVMCI::CodeInstallResult register_method(JVMCIEnv* JVMCIENV,
292                        const methodHandle&       target,
293                        nmethodLocker&            code_handle,
294                        int                       entry_bci,
295                        CodeOffsets*              offsets,
296                        int                       orig_pc_offset,
297                        CodeBuffer*               code_buffer,
298                        int                       frame_words,
299                        OopMapSet*                oop_map_set,
300                        ExceptionHandlerTable*    handler_table,
301                        ImplicitExceptionTable*   implicit_exception_table,
302                        AbstractCompiler*         compiler,
303                        DebugInformationRecorder* debug_info,
304                        Dependencies*             dependencies,
305                        int                       compile_id,
306                        bool                      has_monitors,
307                        bool                      has_unsafe_access,
308                        bool                      has_wide_vector,
309                        JVMCIObject               compiled_code,
310                        JVMCIObject               nmethod_mirror,
311                        FailedSpeculation**       failed_speculations,
312                        char*                     speculations,
313                        int                       speculations_len);
314 
315   // Reports an unexpected exception and exits the VM with a fatal error.
316   static void fatal_exception(JVMCIEnv* JVMCIENV, const char* message);
317 
318   static void describe_pending_hotspot_exception(JavaThread* THREAD, bool clear);
319 
320 #define CHECK_EXIT THREAD); \
321   if (HAS_PENDING_EXCEPTION) { \
322     char buf[256]; \
323     jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
324     JVMCIRuntime::fatal_exception(NULL, buf); \
325     return; \
326   } \
327   (void)(0
328 
329 #define CHECK_EXIT_(v) THREAD);                 \
330   if (HAS_PENDING_EXCEPTION) { \
331     char buf[256]; \
332     jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
333     JVMCIRuntime::fatal_exception(NULL, buf); \
334     return v; \
335   } \
336   (void)(0
337 
338 #define JVMCI_CHECK_EXIT JVMCIENV); \
339   if (JVMCIENV->has_pending_exception()) {      \
340     char buf[256]; \
341     jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
342     JVMCIRuntime::fatal_exception(JVMCIENV, buf); \
343     return; \
344   } \
345   (void)(0
346 
347 #define JVMCI_CHECK_EXIT_(result) JVMCIENV); \
348   if (JVMCIENV->has_pending_exception()) {      \
349     char buf[256]; \
350     jio_snprintf(buf, 256, "Uncaught exception at %s:%d", __FILE__, __LINE__); \
351     JVMCIRuntime::fatal_exception(JVMCIENV, buf); \
352     return result; \
353   } \
354   (void)(0
355 
356   static BasicType kindToBasicType(const Handle& kind, TRAPS);
357 
358   static void new_instance_common(JavaThread* current, Klass* klass, bool null_on_fail);
359   static void new_array_common(JavaThread* current, Klass* klass, jint length, bool null_on_fail);
360   static void new_multi_array_common(JavaThread* current, Klass* klass, int rank, jint* dims, bool null_on_fail);
361   static void dynamic_new_array_common(JavaThread* current, oopDesc* element_mirror, jint length, bool null_on_fail);
362   static void dynamic_new_instance_common(JavaThread* current, oopDesc* type_mirror, bool null_on_fail);
363 
364   // The following routines are called from compiled JVMCI code
365 
366   // When allocation fails, these stubs:
367   // 1. Exercise -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError handling and also
368   //    post a JVMTI_EVENT_RESOURCE_EXHAUSTED event if the failure is an OutOfMemroyError
369   // 2. Return NULL with a pending exception.
370   // Compiled code must ensure these stubs are not called twice for the same allocation
371   // site due to the non-repeatable side effects in the case of OOME.
372   static void new_instance(JavaThread* current, Klass* klass) { new_instance_common(current, klass, false); }
373   static void new_array(JavaThread* current, Klass* klass, jint length) { new_array_common(current, klass, length, false); }
374   static void new_multi_array(JavaThread* current, Klass* klass, int rank, jint* dims) { new_multi_array_common(current, klass, rank, dims, false); }
375   static void dynamic_new_array(JavaThread* current, oopDesc* element_mirror, jint length) { dynamic_new_array_common(current, element_mirror, length, false); }
376   static void dynamic_new_instance(JavaThread* current, oopDesc* type_mirror) { dynamic_new_instance_common(current, type_mirror, false); }
377 
378   // When allocation fails, these stubs return NULL and have no pending exception. Compiled code
379   // can use these stubs if a failed allocation will be retried (e.g., by deoptimizing and
380   // re-executing in the interpreter).
381   static void new_instance_or_null(JavaThread* thread, Klass* klass) { new_instance_common(thread, klass, true); }
382   static void new_array_or_null(JavaThread* thread, Klass* klass, jint length) { new_array_common(thread, klass, length, true); }
383   static void new_multi_array_or_null(JavaThread* thread, Klass* klass, int rank, jint* dims) { new_multi_array_common(thread, klass, rank, dims, true); }
384   static void dynamic_new_array_or_null(JavaThread* thread, oopDesc* element_mirror, jint length) { dynamic_new_array_common(thread, element_mirror, length, true); }
385   static void dynamic_new_instance_or_null(JavaThread* thread, oopDesc* type_mirror) { dynamic_new_instance_common(thread, type_mirror, true); }
386 
387   static void vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3);
388   static jint identity_hash_code(JavaThread* current, oopDesc* obj);
389   static address exception_handler_for_pc(JavaThread* current);
390   static void monitorenter(JavaThread* current, oopDesc* obj, BasicLock* lock);
391   static void monitorexit (JavaThread* current, oopDesc* obj, BasicLock* lock);
392   static jboolean object_notify(JavaThread* current, oopDesc* obj);
393   static jboolean object_notifyAll(JavaThread* current, oopDesc* obj);
394   static void vm_error(JavaThread* current, jlong where, jlong format, jlong value);
395   static oopDesc* load_and_clear_exception(JavaThread* thread);
396   static void log_printf(JavaThread* thread, const char* format, jlong v1, jlong v2, jlong v3);
397   static void log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline);
398   // Print the passed in object, optionally followed by a newline.  If
399   // as_string is true and the object is a java.lang.String then it
400   // printed as a string, otherwise the type of the object is printed
401   // followed by its address.
402   static void log_object(JavaThread* thread, oopDesc* object, bool as_string, bool newline);
403 #if INCLUDE_G1GC
404   using CardValue = G1CardTable::CardValue;
405   static void write_barrier_pre(JavaThread* thread, oopDesc* obj);
406   static void write_barrier_post(JavaThread* thread, volatile CardValue* card);
407 #endif
408   static jboolean validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child);
409 
410   // used to throw exceptions from compiled JVMCI code
411   static int throw_and_post_jvmti_exception(JavaThread* current, const char* exception, const char* message);
412   // helper methods to throw exception with complex messages
413   static int throw_klass_external_name_exception(JavaThread* current, const char* exception, Klass* klass);
414   static int throw_class_cast_exception(JavaThread* current, const char* exception, Klass* caster_klass, Klass* target_klass);
415 
416   // A helper to allow invocation of an arbitrary Java method.  For simplicity the method is
417   // restricted to a static method that takes at most one argument.  For calling convention
418   // simplicty all types are passed by being converted into a jlong
419   static jlong invoke_static_method_one_arg(JavaThread* current, Method* method, jlong argument);
420 
421   // Test only function
422   static jint test_deoptimize_call_int(JavaThread* current, int value);
423 };
424 #endif // SHARE_JVMCI_JVMCIRUNTIME_HPP