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