1 /*
   2  * Copyright (c) 1997, 2011, 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/methodOop.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 #ifdef TARGET_OS_FAMILY_linux
  44 # include "os_linux.inline.hpp"
  45 #endif
  46 #ifdef TARGET_OS_FAMILY_solaris
  47 # include "os_solaris.inline.hpp"
  48 #endif
  49 #ifdef TARGET_OS_FAMILY_windows
  50 # include "os_windows.inline.hpp"
  51 #endif
  52 
  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(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::long_jni_name(methodHandle method) {
  92   // Signature ignore the wrapping parenteses and the trailing return type
  93   stringStream st;
  94   Symbol* signature = method->signature();
  95   st.print("__");
  96   // find ')'
  97   int end;
  98   for (end = 0; end < signature->utf8_length() && signature->byte_at(end) != ')'; end++);
  99   // skip first '('
 100   mangle_name_on(&st, signature, 1, end);
 101   return st.as_string();
 102 }
 103 
 104 extern "C" {
 105   void JNICALL JVM_RegisterUnsafeMethods(JNIEnv *env, jclass unsafecls);
 106   void JNICALL JVM_RegisterMethodHandleMethods(JNIEnv *env, jclass unsafecls);
 107   void JNICALL JVM_RegisterPerfMethods(JNIEnv *env, jclass perfclass);
 108 }
 109 
 110 #define CC (char*)  /* cast a literal from (const char*) */
 111 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
 112 
 113 static JNINativeMethod lookup_special_native_methods[] = {
 114   // Next two functions only exist for compatibility with 1.3.1 and earlier.
 115   { CC"Java_java_io_ObjectOutputStream_getPrimitiveFieldValues",   NULL, FN_PTR(JVM_GetPrimitiveFieldValues)     },  // intercept ObjectOutputStream getPrimitiveFieldValues for faster serialization
 116   { CC"Java_java_io_ObjectInputStream_setPrimitiveFieldValues",    NULL, FN_PTR(JVM_SetPrimitiveFieldValues)     },  // intercept ObjectInputStream setPrimitiveFieldValues for faster serialization
 117 
 118   { CC"Java_sun_misc_Unsafe_registerNatives",                      NULL, FN_PTR(JVM_RegisterUnsafeMethods)       },
 119   { CC"Java_sun_dyn_MethodHandleNatives_registerNatives",          NULL, FN_PTR(JVM_RegisterMethodHandleMethods) },  // AllowTransitionalJSR292
 120   { CC"Java_java_dyn_MethodHandleNatives_registerNatives",         NULL, FN_PTR(JVM_RegisterMethodHandleMethods) },  // AllowTransitionalJSR292
 121   { CC"Java_sun_misc_Perf_registerNatives",                        NULL, FN_PTR(JVM_RegisterPerfMethods)         }
 122 };
 123 
 124 static address lookup_special_native(char* jni_name) {
 125   int i = !JDK_Version::is_gte_jdk14x_version() ? 0 : 2;  // see comment in lookup_special_native_methods
 126   int count = sizeof(lookup_special_native_methods) / sizeof(JNINativeMethod);
 127   for (; i < count; i++) {
 128     // NB: To ignore the jni prefix and jni postfix strstr is used matching.
 129     if (strstr(jni_name, lookup_special_native_methods[i].name) != NULL) {
 130       return CAST_FROM_FN_PTR(address, lookup_special_native_methods[i].fnPtr);
 131     }
 132   }
 133   return NULL;
 134 }
 135 
 136 address NativeLookup::lookup_style(methodHandle method, char* pure_name, const char* long_name, int args_size, bool os_style, bool& in_base_library, TRAPS) {
 137   address entry;
 138   // Compute complete JNI name for style
 139   stringStream st;
 140   if (os_style) os::print_jni_name_prefix_on(&st, args_size);
 141   st.print_raw(pure_name);
 142   st.print_raw(long_name);
 143   if (os_style) os::print_jni_name_suffix_on(&st, args_size);
 144   char* jni_name = st.as_string();
 145 
 146   // If the loader is null we have a system class, so we attempt a lookup in
 147   // the native Java library. This takes care of any bootstrapping problems.
 148   // Note: It is critical for bootstrapping that Java_java_lang_ClassLoader_00024NativeLibrary_find
 149   // gets found the first time around - otherwise an infinite loop can occure. This is
 150   // another VM/library dependency
 151   Handle loader(THREAD,
 152                 instanceKlass::cast(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 // Check all the formats of native implementation name to see if there is one
 195 // for the specified method.
 196 address NativeLookup::lookup_entry(methodHandle method, bool& in_base_library, TRAPS) {
 197   address entry = NULL;
 198   in_base_library = false;
 199   // Compute pure name
 200   char* pure_name = pure_jni_name(method);
 201 
 202   // Compute argument size
 203   int args_size = 1                             // JNIEnv
 204                 + (method->is_static() ? 1 : 0) // class for static methods
 205                 + method->size_of_parameters(); // actual parameters
 206 
 207 
 208   // 1) Try JNI short style
 209   entry = lookup_style(method, pure_name, "",        args_size, true,  in_base_library, CHECK_NULL);
 210   if (entry != NULL) return entry;
 211 
 212   // Compute long name
 213   char* long_name = long_jni_name(method);
 214 
 215   // 2) Try JNI long style
 216   entry = lookup_style(method, pure_name, long_name, args_size, true,  in_base_library, CHECK_NULL);
 217   if (entry != NULL) return entry;
 218 
 219   // 3) Try JNI short style without os prefix/suffix
 220   entry = lookup_style(method, pure_name, "",        args_size, false, in_base_library, CHECK_NULL);
 221   if (entry != NULL) return entry;
 222 
 223   // 4) Try JNI long style without os prefix/suffix
 224   entry = lookup_style(method, pure_name, long_name, args_size, false, in_base_library, CHECK_NULL);
 225 
 226   return entry; // NULL indicates not found
 227 }
 228 
 229 // Check if there are any JVM TI prefixes which have been applied to the native method name.
 230 // If any are found, remove them before attemping the look up of the
 231 // native implementation again.
 232 // See SetNativeMethodPrefix in the JVM TI Spec for more details.
 233 address NativeLookup::lookup_entry_prefixed(methodHandle method, bool& in_base_library, TRAPS) {
 234   ResourceMark rm(THREAD);
 235 
 236   int prefix_count;
 237   char** prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
 238   char* in_name = method->name()->as_C_string();
 239   char* wrapper_name = in_name;
 240   // last applied prefix will be first -- go backwards
 241   for (int i = prefix_count-1; i >= 0; i--) {
 242     char* prefix = prefixes[i];
 243     size_t prefix_len = strlen(prefix);
 244     if (strncmp(prefix, wrapper_name, prefix_len) == 0) {
 245       // has this prefix remove it
 246       wrapper_name += prefix_len;
 247     }
 248   }
 249   if (wrapper_name != in_name) {
 250     // we have a name for a wrapping method
 251     int wrapper_name_len = (int)strlen(wrapper_name);
 252     TempNewSymbol wrapper_symbol = SymbolTable::probe(wrapper_name, wrapper_name_len);
 253     if (wrapper_symbol != NULL) {
 254       KlassHandle kh(method->method_holder());
 255       methodOop wrapper_method = Klass::cast(kh())->lookup_method(wrapper_symbol,
 256                                                                   method->signature());
 257       if (wrapper_method != NULL && !wrapper_method->is_native()) {
 258         // we found a wrapper method, use its native entry
 259         method->set_is_prefixed_native();
 260         return lookup_entry(wrapper_method, in_base_library, THREAD);
 261       }
 262     }
 263   }
 264   return NULL;
 265 }
 266 
 267 address NativeLookup::lookup_base(methodHandle method, bool& in_base_library, TRAPS) {
 268   address entry = NULL;
 269   ResourceMark rm(THREAD);
 270 
 271   entry = lookup_entry(method, in_base_library, THREAD);
 272   if (entry != NULL) return entry;
 273 
 274   // standard native method resolution has failed.  Check if there are any
 275   // JVM TI prefixes which have been applied to the native method name.
 276   entry = lookup_entry_prefixed(method, in_base_library, THREAD);
 277   if (entry != NULL) return entry;
 278 
 279   // Native function not found, throw UnsatisfiedLinkError
 280   THROW_MSG_0(vmSymbols::java_lang_UnsatisfiedLinkError(),
 281               method->name_and_sig_as_C_string());
 282 }
 283 
 284 
 285 address NativeLookup::lookup(methodHandle method, bool& in_base_library, TRAPS) {
 286   if (!method->has_native_function()) {
 287     address entry = lookup_base(method, in_base_library, CHECK_NULL);
 288     method->set_native_function(entry,
 289       methodOopDesc::native_bind_event_is_interesting);
 290     // -verbose:jni printing
 291     if (PrintJNIResolving) {
 292       ResourceMark rm(THREAD);
 293       tty->print_cr("[Dynamic-linking native method %s.%s ... JNI]",
 294         Klass::cast(method->method_holder())->external_name(),
 295         method->name()->as_C_string());
 296     }
 297   }
 298   return method->native_function();
 299 }
 300 
 301 address NativeLookup::base_library_lookup(const char* class_name, const char* method_name, const char* signature) {
 302   EXCEPTION_MARK;
 303   bool in_base_library = true;  // SharedRuntime inits some math methods.
 304   TempNewSymbol c_name = SymbolTable::new_symbol(class_name,  CATCH);
 305   TempNewSymbol m_name = SymbolTable::new_symbol(method_name, CATCH);
 306   TempNewSymbol s_name = SymbolTable::new_symbol(signature,   CATCH);
 307 
 308   // Find the class
 309   klassOop k = SystemDictionary::resolve_or_fail(c_name, true, CATCH);
 310   instanceKlassHandle klass (THREAD, k);
 311 
 312   // Find method and invoke standard lookup
 313   methodHandle method (THREAD,
 314                        klass->uncached_lookup_method(m_name, s_name));
 315   address result = lookup(method, in_base_library, CATCH);
 316   assert(in_base_library, "must be in basic library");
 317   guarantee(result != NULL, "must be non NULL");
 318   return result;
 319 }