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