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