1 /*
   2  * Copyright (c) 1997, 2020, 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 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "logging/log.hpp"
  31 #include "logging/logTag.hpp"
  32 #include "memory/oopFactory.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "oops/instanceKlass.hpp"
  35 #include "oops/method.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "oops/symbol.hpp"
  38 #include "prims/jvm_misc.hpp"
  39 #include "prims/nativeLookup.hpp"
  40 #include "prims/unsafe.hpp"
  41 #include "runtime/arguments.hpp"
  42 #include "runtime/handles.inline.hpp"
  43 #include "runtime/interfaceSupport.inline.hpp"
  44 #include "runtime/javaCalls.hpp"
  45 #include "runtime/os.inline.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/signature.hpp"
  48 #include "utilities/macros.hpp"
  49 #include "utilities/utf8.hpp"
  50 #if INCLUDE_JFR
  51 #include "jfr/jfr.hpp"
  52 #endif
  53 
  54 static void mangle_name_on(outputStream* st, Symbol* name, int begin, int end) {
  55   char* bytes = (char*)name->bytes() + begin;
  56   char* end_bytes = (char*)name->bytes() + end;
  57   while (bytes < end_bytes) {
  58     jchar c;
  59     bytes = UTF8::next(bytes, &c);
  60     if (c <= 0x7f && isalnum(c)) {
  61       st->put((char) c);
  62     } else {
  63            if (c == '_') st->print("_1");
  64       else if (c == '/') st->print("_");
  65       else if (c == ';') st->print("_2");
  66       else if (c == '[') st->print("_3");
  67       else               st->print("_%.5x", c);
  68     }
  69   }
  70 }
  71 
  72 
  73 static void mangle_name_on(outputStream* st, Symbol* name) {
  74   mangle_name_on(st, name, 0, name->utf8_length());
  75 }
  76 
  77 
  78 char* NativeLookup::pure_jni_name(const methodHandle& method) {
  79   stringStream st;
  80   // Prefix
  81   st.print("Java_");
  82   // Klass name
  83   mangle_name_on(&st, method->klass_name());
  84   st.print("_");
  85   // Method name
  86   mangle_name_on(&st, method->name());
  87   return st.as_string();
  88 }
  89 
  90 
  91 char* NativeLookup::critical_jni_name(const methodHandle& method) {
  92   stringStream st;
  93   // Prefix
  94   st.print("JavaCritical_");
  95   // Klass name
  96   mangle_name_on(&st, method->klass_name());
  97   st.print("_");
  98   // Method name
  99   mangle_name_on(&st, method->name());
 100   return st.as_string();
 101 }
 102 
 103 
 104 char* NativeLookup::long_jni_name(const methodHandle& method) {
 105   // Signature ignore the wrapping parenteses and the trailing return type
 106   stringStream st;
 107   Symbol* signature = method->signature();
 108   st.print("__");
 109   // find ')'
 110   int end;
 111   for (end = 0; end < signature->utf8_length() && signature->char_at(end) != JVM_SIGNATURE_ENDFUNC; end++);
 112   // skip first '('
 113   mangle_name_on(&st, signature, 1, end);
 114   return st.as_string();
 115 }
 116 
 117 extern "C" {
 118   void JNICALL JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass unsafecls);
 119   void JNICALL JVM_RegisterPerfMethods(JNIEnv *env, jclass perfclass);
 120   void JNICALL JVM_RegisterWhiteBoxMethods(JNIEnv *env, jclass wbclass);
 121   void JNICALL JVM_RegisterVectorSupportMethods(JNIEnv *env, jclass vsclass);
 122 #if INCLUDE_JVMCI
 123   jobject  JNICALL JVM_GetJVMCIRuntime(JNIEnv *env, jclass c);
 124   void     JNICALL JVM_RegisterJVMCINatives(JNIEnv *env, jclass compilerToVMClass);
 125 #endif
 126 }
 127 
 128 #define CC (char*)  /* cast a literal from (const char*) */
 129 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
 130 
 131 static JNINativeMethod lookup_special_native_methods[] = {
 132   { CC"Java_jdk_internal_misc_Unsafe_registerNatives",             NULL, FN_PTR(JVM_RegisterJDKInternalMiscUnsafeMethods) },
 133   { CC"Java_java_lang_invoke_MethodHandleNatives_registerNatives", NULL, FN_PTR(JVM_RegisterMethodHandleMethods) },
 134   { CC"Java_jdk_internal_perf_Perf_registerNatives",               NULL, FN_PTR(JVM_RegisterPerfMethods)         },
 135   { CC"Java_sun_hotspot_WhiteBox_registerNatives",                 NULL, FN_PTR(JVM_RegisterWhiteBoxMethods)     },
 136   { CC"Java_jdk_internal_vm_vector_VectorSupport_registerNatives", NULL, FN_PTR(JVM_RegisterVectorSupportMethods)},
 137 #if INCLUDE_JVMCI
 138   { CC"Java_jdk_vm_ci_runtime_JVMCI_initializeRuntime",            NULL, FN_PTR(JVM_GetJVMCIRuntime)             },
 139   { CC"Java_jdk_vm_ci_hotspot_CompilerToVM_registerNatives",       NULL, FN_PTR(JVM_RegisterJVMCINatives)        },
 140 #endif
 141 #if INCLUDE_JFR
 142   { CC"Java_jdk_jfr_internal_JVM_registerNatives",                 NULL, FN_PTR(jfr_register_natives)            },
 143 #endif
 144 };
 145 
 146 static address lookup_special_native(const char* jni_name) {
 147   int count = sizeof(lookup_special_native_methods) / sizeof(JNINativeMethod);
 148   for (int i = 0; i < count; i++) {
 149     // NB: To ignore the jni prefix and jni postfix strstr is used matching.
 150     if (strstr(jni_name, lookup_special_native_methods[i].name) != NULL) {
 151       return CAST_FROM_FN_PTR(address, lookup_special_native_methods[i].fnPtr);
 152     }
 153   }
 154   return NULL;
 155 }
 156 
 157 address NativeLookup::lookup_style(const methodHandle& method, char* pure_name, const char* long_name, int args_size, bool os_style, bool& in_base_library, TRAPS) {
 158   address entry;
 159   const char* jni_name = compute_complete_jni_name(pure_name, long_name, args_size, os_style);
 160 
 161 
 162   // If the loader is null we have a system class, so we attempt a lookup in
 163   // the native Java library. This takes care of any bootstrapping problems.
 164   // Note: It is critical for bootstrapping that Java_java_lang_ClassLoader_findNative
 165   // gets found the first time around - otherwise an infinite loop can occure. This is
 166   // another VM/library dependency
 167   Handle loader(THREAD, method->method_holder()->class_loader());
 168   if (loader.is_null()) {
 169     entry = lookup_special_native(jni_name);
 170     if (entry == NULL) {
 171        entry = (address) os::dll_lookup(os::native_java_library(), jni_name);
 172     }
 173     if (entry != NULL) {
 174       in_base_library = true;
 175       return entry;
 176     }
 177   }
 178 
 179   // Otherwise call static method findNative in ClassLoader
 180   Klass*   klass = SystemDictionary::ClassLoader_klass();
 181   Handle name_arg = java_lang_String::create_from_str(jni_name, CHECK_NULL);
 182 
 183   JavaValue result(T_LONG);
 184   JavaCalls::call_static(&result,
 185                          klass,
 186                          vmSymbols::findNative_name(),
 187                          vmSymbols::classloader_string_long_signature(),
 188                          // Arguments
 189                          loader,
 190                          name_arg,
 191                          CHECK_NULL);
 192   entry = (address) (intptr_t) result.get_jlong();
 193 
 194   if (entry == NULL) {
 195     // findNative didn't find it, if there are any agent libraries look in them
 196     AgentLibrary* agent;
 197     for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
 198       entry = (address) os::dll_lookup(agent->os_lib(), jni_name);
 199       if (entry != NULL) {
 200         return entry;
 201       }
 202     }
 203   }
 204 
 205   return entry;
 206 }
 207 
 208 const char* NativeLookup::compute_complete_jni_name(const char* pure_name, const char* long_name, int args_size, bool os_style) {
 209   stringStream st;
 210   if (os_style) {
 211     os::print_jni_name_prefix_on(&st, args_size);
 212   }
 213 
 214   st.print_raw(pure_name);
 215   st.print_raw(long_name);
 216   if (os_style) {
 217     os::print_jni_name_suffix_on(&st, args_size);
 218   }
 219 
 220   return st.as_string();
 221 }
 222 
 223 address NativeLookup::lookup_critical_style(void* dll, const char* pure_name, const char* long_name, int args_size, bool os_style) {
 224   const char* jni_name = compute_complete_jni_name(pure_name, long_name, args_size, os_style);
 225   assert(dll != NULL, "dll must be loaded");
 226   return (address)os::dll_lookup(dll, jni_name);
 227 }
 228 
 229 // Check all the formats of native implementation name to see if there is one
 230 // for the specified method.
 231 address NativeLookup::lookup_entry(const methodHandle& method, bool& in_base_library, TRAPS) {
 232   address entry = NULL;
 233   in_base_library = false;
 234   // Compute pure name
 235   char* pure_name = pure_jni_name(method);
 236 
 237   // Compute argument size
 238   int args_size = 1                             // JNIEnv
 239                 + (method->is_static() ? 1 : 0) // class for static methods
 240                 + method->size_of_parameters(); // actual parameters
 241 
 242   // 1) Try JNI short style
 243   entry = lookup_style(method, pure_name, "",        args_size, true,  in_base_library, CHECK_NULL);
 244   if (entry != NULL) return entry;
 245 
 246   // Compute long name
 247   char* long_name = long_jni_name(method);
 248 
 249   // 2) Try JNI long style
 250   entry = lookup_style(method, pure_name, long_name, args_size, true,  in_base_library, CHECK_NULL);
 251   if (entry != NULL) return entry;
 252 
 253   // 3) Try JNI short style without os prefix/suffix
 254   entry = lookup_style(method, pure_name, "",        args_size, false, in_base_library, CHECK_NULL);
 255   if (entry != NULL) return entry;
 256 
 257   // 4) Try JNI long style without os prefix/suffix
 258   entry = lookup_style(method, pure_name, long_name, args_size, false, in_base_library, CHECK_NULL);
 259 
 260   return entry; // NULL indicates not found
 261 }
 262 
 263 // Check all the formats of native implementation name to see if there is one
 264 // for the specified method.
 265 address NativeLookup::lookup_critical_entry(const methodHandle& method) {
 266   assert(CriticalJNINatives, "or should not be here");
 267 
 268   if (method->is_synchronized() ||
 269       !method->is_static()) {
 270     // Only static non-synchronized methods are allowed
 271     return NULL;
 272   }
 273 
 274   ResourceMark rm;
 275 
 276   Symbol* signature = method->signature();
 277   for (int end = 0; end < signature->utf8_length(); end++) {
 278     if (signature->char_at(end) == 'L') {
 279       // Don't allow object types
 280       return NULL;
 281     }
 282   }
 283 
 284   // Compute argument size
 285   int args_size = method->size_of_parameters();
 286   for (SignatureStream ss(signature); !ss.at_return_type(); ss.next()) {
 287     if (ss.is_array()) {
 288       args_size += T_INT_size; // array length parameter
 289     }
 290   }
 291 
 292   // dll handling requires I/O. Don't do that while in _thread_in_vm (safepoint may get requested).
 293   ThreadToNativeFromVM thread_in_native(JavaThread::current());
 294 
 295   void* dll = dll_load(method);
 296   address entry = NULL;
 297 
 298   if (dll != NULL) {
 299     entry = lookup_critical_style(dll, method, args_size);
 300     // Close the handle to avoid keeping the library alive if the native method holder is unloaded.
 301     // This is fine because the library is still kept alive by JNI (see JVM_LoadLibrary). As soon
 302     // as the holder class and the library are unloaded (see JVM_UnloadLibrary), the native wrapper
 303     // that calls 'critical_entry' becomes unreachable and is unloaded as well.
 304     os::dll_unload(dll);
 305   }
 306 
 307   return entry; // NULL indicates not found
 308 }
 309 
 310 void* NativeLookup::dll_load(const methodHandle& method) {
 311   if (method->has_native_function()) {
 312 
 313     address current_entry = method->native_function();
 314 
 315     char dll_name[JVM_MAXPATHLEN];
 316     int offset;
 317     if (os::dll_address_to_library_name(current_entry, dll_name, sizeof(dll_name), &offset)) {
 318       char ebuf[32];
 319       return os::dll_load(dll_name, ebuf, sizeof(ebuf));
 320     }
 321   }
 322 
 323   return NULL;
 324 }
 325 
 326 address NativeLookup::lookup_critical_style(void* dll, const methodHandle& method, int args_size) {
 327   address entry = NULL;
 328   const char* critical_name = critical_jni_name(method);
 329 
 330   // 1) Try JNI short style
 331   entry = lookup_critical_style(dll, critical_name, "",        args_size, true);
 332   if (entry != NULL) {
 333     return entry;
 334   }
 335 
 336   const char* long_name = long_jni_name(method);
 337 
 338   // 2) Try JNI long style
 339   entry = lookup_critical_style(dll, critical_name, long_name, args_size, true);
 340   if (entry != NULL) {
 341     return entry;
 342   }
 343 
 344   // 3) Try JNI short style without os prefix/suffix
 345   entry = lookup_critical_style(dll, critical_name, "",        args_size, false);
 346   if (entry != NULL) {
 347     return entry;
 348   }
 349 
 350   // 4) Try JNI long style without os prefix/suffix
 351   return lookup_critical_style(dll, critical_name, long_name, args_size, false);
 352 }
 353 
 354 // Check if there are any JVM TI prefixes which have been applied to the native method name.
 355 // If any are found, remove them before attemping the look up of the
 356 // native implementation again.
 357 // See SetNativeMethodPrefix in the JVM TI Spec for more details.
 358 address NativeLookup::lookup_entry_prefixed(const methodHandle& method, bool& in_base_library, TRAPS) {
 359 #if INCLUDE_JVMTI
 360   ResourceMark rm(THREAD);
 361 
 362   int prefix_count;
 363   char** prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
 364   char* in_name = method->name()->as_C_string();
 365   char* wrapper_name = in_name;
 366   // last applied prefix will be first -- go backwards
 367   for (int i = prefix_count-1; i >= 0; i--) {
 368     char* prefix = prefixes[i];
 369     size_t prefix_len = strlen(prefix);
 370     if (strncmp(prefix, wrapper_name, prefix_len) == 0) {
 371       // has this prefix remove it
 372       wrapper_name += prefix_len;
 373     }
 374   }
 375   if (wrapper_name != in_name) {
 376     // we have a name for a wrapping method
 377     int wrapper_name_len = (int)strlen(wrapper_name);
 378     TempNewSymbol wrapper_symbol = SymbolTable::probe(wrapper_name, wrapper_name_len);
 379     if (wrapper_symbol != NULL) {
 380       Klass* k = method->method_holder();
 381       Method* wrapper_method = k->lookup_method(wrapper_symbol, method->signature());
 382       if (wrapper_method != NULL && !wrapper_method->is_native()) {
 383         // we found a wrapper method, use its native entry
 384         method->set_is_prefixed_native();
 385         return lookup_entry(methodHandle(THREAD, wrapper_method), in_base_library, THREAD);
 386       }
 387     }
 388   }
 389 #endif // INCLUDE_JVMTI
 390   return NULL;
 391 }
 392 
 393 address NativeLookup::lookup_base(const methodHandle& method, bool& in_base_library, TRAPS) {
 394   address entry = NULL;
 395   ResourceMark rm(THREAD);
 396 
 397   entry = lookup_entry(method, in_base_library, THREAD);
 398   if (entry != NULL) return entry;
 399 
 400   // standard native method resolution has failed.  Check if there are any
 401   // JVM TI prefixes which have been applied to the native method name.
 402   entry = lookup_entry_prefixed(method, in_base_library, THREAD);
 403   if (entry != NULL) return entry;
 404 
 405   // Native function not found, throw UnsatisfiedLinkError
 406   stringStream ss;
 407   ss.print("'");
 408   method->print_external_name(&ss);
 409   ss.print("'");
 410   THROW_MSG_0(vmSymbols::java_lang_UnsatisfiedLinkError(), ss.as_string());
 411 }
 412 
 413 
 414 address NativeLookup::lookup(const methodHandle& method, bool& in_base_library, TRAPS) {
 415   if (!method->has_native_function()) {
 416     address entry = lookup_base(method, in_base_library, CHECK_NULL);
 417     method->set_native_function(entry,
 418       Method::native_bind_event_is_interesting);
 419     // -verbose:jni printing
 420     if (log_is_enabled(Debug, jni, resolve)) {
 421       ResourceMark rm(THREAD);
 422       log_debug(jni, resolve)("[Dynamic-linking native method %s.%s ... JNI]",
 423                               method->method_holder()->external_name(),
 424                               method->name()->as_C_string());
 425     }
 426   }
 427   return method->native_function();
 428 }
 429 
 430 address NativeLookup::base_library_lookup(const char* class_name, const char* method_name, const char* signature) {
 431   EXCEPTION_MARK;
 432   bool in_base_library = true;  // SharedRuntime inits some math methods.
 433   TempNewSymbol c_name = SymbolTable::new_symbol(class_name);
 434   TempNewSymbol m_name = SymbolTable::new_symbol(method_name);
 435   TempNewSymbol s_name = SymbolTable::new_symbol(signature);
 436 
 437   // Find the class
 438   Klass* k = SystemDictionary::resolve_or_fail(c_name, true, CATCH);
 439   InstanceKlass* klass  = InstanceKlass::cast(k);
 440 
 441   // Find method and invoke standard lookup
 442   methodHandle method (THREAD,
 443                        klass->uncached_lookup_method(m_name, s_name, Klass::OverpassLookupMode::find));
 444   address result = lookup(method, in_base_library, CATCH);
 445   assert(in_base_library, "must be in basic library");
 446   guarantee(result != NULL, "must be non NULL");
 447   return result;
 448 }