1 /*
   2  * Copyright (c) 1997, 2016, 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/stringTable.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/verifier.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "interpreter/linkResolver.hpp"
  32 #include "memory/oopFactory.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.inline.hpp"
  35 #include "oops/instanceKlass.hpp"
  36 #include "oops/objArrayKlass.hpp"
  37 #include "oops/objArrayOop.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "prims/jvm.h"
  40 #include "prims/jvmtiExport.hpp"
  41 #include "runtime/arguments.hpp"
  42 #include "runtime/handles.inline.hpp"
  43 #include "runtime/javaCalls.hpp"
  44 #include "runtime/reflection.hpp"
  45 #include "runtime/reflectionUtils.hpp"
  46 #include "runtime/signature.hpp"
  47 #include "runtime/vframe.hpp"
  48 
  49 static void trace_class_resolution(const Klass* to_class) {
  50   ResourceMark rm;
  51   int line_number = -1;
  52   const char * source_file = NULL;
  53   Klass* caller = NULL;
  54   JavaThread* jthread = JavaThread::current();
  55   if (jthread->has_last_Java_frame()) {
  56     vframeStream vfst(jthread);
  57     // skip over any frames belonging to java.lang.Class
  58     while (!vfst.at_end() &&
  59            vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class()) {
  60       vfst.next();
  61     }
  62     if (!vfst.at_end()) {
  63       // this frame is a likely suspect
  64       caller = vfst.method()->method_holder();
  65       line_number = vfst.method()->line_number_from_bci(vfst.bci());
  66       Symbol* s = vfst.method()->method_holder()->source_file_name();
  67       if (s != NULL) {
  68         source_file = s->as_C_string();
  69       }
  70     }
  71   }
  72   if (caller != NULL) {
  73     const char * from = caller->external_name();
  74     const char * to = to_class->external_name();
  75     // print in a single call to reduce interleaving between threads
  76     if (source_file != NULL) {
  77       log_info(classresolve)("%s %s %s:%d (reflection)", from, to, source_file, line_number);
  78     } else {
  79       log_info(classresolve)("%s %s (reflection)", from, to);
  80     }
  81   }
  82 }
  83 
  84 
  85 oop Reflection::box(jvalue* value, BasicType type, TRAPS) {
  86   if (type == T_VOID) {
  87     return NULL;
  88   }
  89   if (type == T_OBJECT || type == T_ARRAY) {
  90     // regular objects are not boxed
  91     return (oop) value->l;
  92   }
  93   oop result = java_lang_boxing_object::create(type, value, CHECK_NULL);
  94   if (result == NULL) {
  95     THROW_(vmSymbols::java_lang_IllegalArgumentException(), result);
  96   }
  97   return result;
  98 }
  99 
 100 
 101 BasicType Reflection::unbox_for_primitive(oop box, jvalue* value, TRAPS) {
 102   if (box == NULL) {
 103     THROW_(vmSymbols::java_lang_IllegalArgumentException(), T_ILLEGAL);
 104   }
 105   return java_lang_boxing_object::get_value(box, value);
 106 }
 107 
 108 BasicType Reflection::unbox_for_regular_object(oop box, jvalue* value) {
 109   // Note:  box is really the unboxed oop.  It might even be a Short, etc.!
 110   value->l = (jobject) box;
 111   return T_OBJECT;
 112 }
 113 
 114 
 115 void Reflection::widen(jvalue* value, BasicType current_type, BasicType wide_type, TRAPS) {
 116   assert(wide_type != current_type, "widen should not be called with identical types");
 117   switch (wide_type) {
 118     case T_BOOLEAN:
 119     case T_BYTE:
 120     case T_CHAR:
 121       break;  // fail
 122     case T_SHORT:
 123       switch (current_type) {
 124         case T_BYTE:
 125           value->s = (jshort) value->b;
 126           return;
 127       }
 128       break;  // fail
 129     case T_INT:
 130       switch (current_type) {
 131         case T_BYTE:
 132           value->i = (jint) value->b;
 133           return;
 134         case T_CHAR:
 135           value->i = (jint) value->c;
 136           return;
 137         case T_SHORT:
 138           value->i = (jint) value->s;
 139           return;
 140       }
 141       break;  // fail
 142     case T_LONG:
 143       switch (current_type) {
 144         case T_BYTE:
 145           value->j = (jlong) value->b;
 146           return;
 147         case T_CHAR:
 148           value->j = (jlong) value->c;
 149           return;
 150         case T_SHORT:
 151           value->j = (jlong) value->s;
 152           return;
 153         case T_INT:
 154           value->j = (jlong) value->i;
 155           return;
 156       }
 157       break;  // fail
 158     case T_FLOAT:
 159       switch (current_type) {
 160         case T_BYTE:
 161           value->f = (jfloat) value->b;
 162           return;
 163         case T_CHAR:
 164           value->f = (jfloat) value->c;
 165           return;
 166         case T_SHORT:
 167           value->f = (jfloat) value->s;
 168           return;
 169         case T_INT:
 170           value->f = (jfloat) value->i;
 171           return;
 172         case T_LONG:
 173           value->f = (jfloat) value->j;
 174           return;
 175       }
 176       break;  // fail
 177     case T_DOUBLE:
 178       switch (current_type) {
 179         case T_BYTE:
 180           value->d = (jdouble) value->b;
 181           return;
 182         case T_CHAR:
 183           value->d = (jdouble) value->c;
 184           return;
 185         case T_SHORT:
 186           value->d = (jdouble) value->s;
 187           return;
 188         case T_INT:
 189           value->d = (jdouble) value->i;
 190           return;
 191         case T_FLOAT:
 192           value->d = (jdouble) value->f;
 193           return;
 194         case T_LONG:
 195           value->d = (jdouble) value->j;
 196           return;
 197       }
 198       break;  // fail
 199     default:
 200       break;  // fail
 201   }
 202   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "argument type mismatch");
 203 }
 204 
 205 
 206 BasicType Reflection::array_get(jvalue* value, arrayOop a, int index, TRAPS) {
 207   if (!a->is_within_bounds(index)) {
 208     THROW_(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), T_ILLEGAL);
 209   }
 210   if (a->is_objArray()) {
 211     value->l = (jobject) objArrayOop(a)->obj_at(index);
 212     return T_OBJECT;
 213   } else {
 214     assert(a->is_typeArray(), "just checking");
 215     BasicType type = TypeArrayKlass::cast(a->klass())->element_type();
 216     switch (type) {
 217       case T_BOOLEAN:
 218         value->z = typeArrayOop(a)->bool_at(index);
 219         break;
 220       case T_CHAR:
 221         value->c = typeArrayOop(a)->char_at(index);
 222         break;
 223       case T_FLOAT:
 224         value->f = typeArrayOop(a)->float_at(index);
 225         break;
 226       case T_DOUBLE:
 227         value->d = typeArrayOop(a)->double_at(index);
 228         break;
 229       case T_BYTE:
 230         value->b = typeArrayOop(a)->byte_at(index);
 231         break;
 232       case T_SHORT:
 233         value->s = typeArrayOop(a)->short_at(index);
 234         break;
 235       case T_INT:
 236         value->i = typeArrayOop(a)->int_at(index);
 237         break;
 238       case T_LONG:
 239         value->j = typeArrayOop(a)->long_at(index);
 240         break;
 241       default:
 242         return T_ILLEGAL;
 243     }
 244     return type;
 245   }
 246 }
 247 
 248 
 249 void Reflection::array_set(jvalue* value, arrayOop a, int index, BasicType value_type, TRAPS) {
 250   if (!a->is_within_bounds(index)) {
 251     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
 252   }
 253   if (a->is_objArray()) {
 254     if (value_type == T_OBJECT) {
 255       oop obj = (oop) value->l;
 256       if (obj != NULL) {
 257         Klass* element_klass = ObjArrayKlass::cast(a->klass())->element_klass();
 258         if (!obj->is_a(element_klass)) {
 259           THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "array element type mismatch");
 260         }
 261       }
 262       objArrayOop(a)->obj_at_put(index, obj);
 263     }
 264   } else {
 265     assert(a->is_typeArray(), "just checking");
 266     BasicType array_type = TypeArrayKlass::cast(a->klass())->element_type();
 267     if (array_type != value_type) {
 268       // The widen operation can potentially throw an exception, but cannot block,
 269       // so typeArrayOop a is safe if the call succeeds.
 270       widen(value, value_type, array_type, CHECK);
 271     }
 272     switch (array_type) {
 273       case T_BOOLEAN:
 274         typeArrayOop(a)->bool_at_put(index, value->z);
 275         break;
 276       case T_CHAR:
 277         typeArrayOop(a)->char_at_put(index, value->c);
 278         break;
 279       case T_FLOAT:
 280         typeArrayOop(a)->float_at_put(index, value->f);
 281         break;
 282       case T_DOUBLE:
 283         typeArrayOop(a)->double_at_put(index, value->d);
 284         break;
 285       case T_BYTE:
 286         typeArrayOop(a)->byte_at_put(index, value->b);
 287         break;
 288       case T_SHORT:
 289         typeArrayOop(a)->short_at_put(index, value->s);
 290         break;
 291       case T_INT:
 292         typeArrayOop(a)->int_at_put(index, value->i);
 293         break;
 294       case T_LONG:
 295         typeArrayOop(a)->long_at_put(index, value->j);
 296         break;
 297       default:
 298         THROW(vmSymbols::java_lang_IllegalArgumentException());
 299     }
 300   }
 301 }
 302 
 303 static Klass* basic_type_mirror_to_arrayklass(oop basic_type_mirror, TRAPS) {
 304   assert(java_lang_Class::is_primitive(basic_type_mirror), "just checking");
 305   BasicType type = java_lang_Class::primitive_type(basic_type_mirror);
 306   if (type == T_VOID) {
 307     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 308   }
 309   else {
 310     return Universe::typeArrayKlassObj(type);
 311   }
 312 }
 313 
 314 #ifdef ASSERT
 315 static oop basic_type_arrayklass_to_mirror(Klass* basic_type_arrayklass, TRAPS) {
 316   BasicType type = TypeArrayKlass::cast(basic_type_arrayklass)->element_type();
 317   return Universe::java_mirror(type);
 318 }
 319 #endif
 320 
 321 arrayOop Reflection::reflect_new_array(oop element_mirror, jint length, TRAPS) {
 322   if (element_mirror == NULL) {
 323     THROW_0(vmSymbols::java_lang_NullPointerException());
 324   }
 325   if (length < 0) {
 326     THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
 327   }
 328   if (java_lang_Class::is_primitive(element_mirror)) {
 329     Klass* tak = basic_type_mirror_to_arrayklass(element_mirror, CHECK_NULL);
 330     return TypeArrayKlass::cast(tak)->allocate(length, THREAD);
 331   } else {
 332     Klass* k = java_lang_Class::as_Klass(element_mirror);
 333     if (k->is_array_klass() && ArrayKlass::cast(k)->dimension() >= MAX_DIM) {
 334       THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 335     }
 336     return oopFactory::new_objArray(k, length, THREAD);
 337   }
 338 }
 339 
 340 
 341 arrayOop Reflection::reflect_new_multi_array(oop element_mirror, typeArrayOop dim_array, TRAPS) {
 342   assert(dim_array->is_typeArray(), "just checking");
 343   assert(TypeArrayKlass::cast(dim_array->klass())->element_type() == T_INT, "just checking");
 344 
 345   if (element_mirror == NULL) {
 346     THROW_0(vmSymbols::java_lang_NullPointerException());
 347   }
 348 
 349   int len = dim_array->length();
 350   if (len <= 0 || len > MAX_DIM) {
 351     THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 352   }
 353 
 354   jint dimensions[MAX_DIM];   // C array copy of intArrayOop
 355   for (int i = 0; i < len; i++) {
 356     int d = dim_array->int_at(i);
 357     if (d < 0) {
 358       THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
 359     }
 360     dimensions[i] = d;
 361   }
 362 
 363   Klass* klass;
 364   int dim = len;
 365   if (java_lang_Class::is_primitive(element_mirror)) {
 366     klass = basic_type_mirror_to_arrayklass(element_mirror, CHECK_NULL);
 367   } else {
 368     klass = java_lang_Class::as_Klass(element_mirror);
 369     if (klass->is_array_klass()) {
 370       int k_dim = ArrayKlass::cast(klass)->dimension();
 371       if (k_dim + len > MAX_DIM) {
 372         THROW_0(vmSymbols::java_lang_IllegalArgumentException());
 373       }
 374       dim += k_dim;
 375     }
 376   }
 377   klass = klass->array_klass(dim, CHECK_NULL);
 378   oop obj = ArrayKlass::cast(klass)->multi_allocate(len, dimensions, CHECK_NULL);
 379   assert(obj->is_array(), "just checking");
 380   return arrayOop(obj);
 381 }
 382 
 383 
 384 oop Reflection::array_component_type(oop mirror, TRAPS) {
 385   if (java_lang_Class::is_primitive(mirror)) {
 386     return NULL;
 387   }
 388 
 389   Klass* klass = java_lang_Class::as_Klass(mirror);
 390   if (!klass->is_array_klass()) {
 391     return NULL;
 392   }
 393 
 394   oop result = java_lang_Class::component_mirror(mirror);
 395 #ifdef ASSERT
 396   oop result2 = NULL;
 397   if (ArrayKlass::cast(klass)->dimension() == 1) {
 398     if (klass->is_typeArray_klass()) {
 399       result2 = basic_type_arrayklass_to_mirror(klass, CHECK_NULL);
 400     } else {
 401       result2 = ObjArrayKlass::cast(klass)->element_klass()->java_mirror();
 402     }
 403   } else {
 404     Klass* lower_dim = ArrayKlass::cast(klass)->lower_dimension();
 405     assert(lower_dim->is_array_klass(), "just checking");
 406     result2 = lower_dim->java_mirror();
 407   }
 408   assert(result == result2, "results must be consistent");
 409 #endif //ASSERT
 410   return result;
 411 }
 412 
 413 static bool under_host_klass(const InstanceKlass* ik, const Klass* host_klass) {
 414   DEBUG_ONLY(int inf_loop_check = 1000 * 1000 * 1000);
 415   for (;;) {
 416     const Klass* hc = (const Klass*)ik->host_klass();
 417     if (hc == NULL)        return false;
 418     if (hc == host_klass)  return true;
 419     ik = InstanceKlass::cast(hc);
 420 
 421     // There's no way to make a host class loop short of patching memory.
 422     // Therefore there cannot be a loop here unless there's another bug.
 423     // Still, let's check for it.
 424     assert(--inf_loop_check > 0, "no host_klass loop");
 425   }
 426 }
 427 
 428 static bool can_relax_access_check_for(const Klass* accessor,
 429                                        const Klass* accessee,
 430                                        bool classloader_only) {
 431 
 432   const InstanceKlass* accessor_ik = InstanceKlass::cast(accessor);
 433   const InstanceKlass* accessee_ik = InstanceKlass::cast(accessee);
 434 
 435   // If either is on the other's host_klass chain, access is OK,
 436   // because one is inside the other.
 437   if (under_host_klass(accessor_ik, accessee) ||
 438     under_host_klass(accessee_ik, accessor))
 439     return true;
 440 
 441   if ((RelaxAccessControlCheck &&
 442     accessor_ik->major_version() < Verifier::NO_RELAX_ACCESS_CTRL_CHECK_VERSION &&
 443     accessee_ik->major_version() < Verifier::NO_RELAX_ACCESS_CTRL_CHECK_VERSION) ||
 444     (accessor_ik->major_version() < Verifier::STRICTER_ACCESS_CTRL_CHECK_VERSION &&
 445     accessee_ik->major_version() < Verifier::STRICTER_ACCESS_CTRL_CHECK_VERSION)) {
 446     return classloader_only &&
 447       Verifier::relax_verify_for(accessor_ik->class_loader()) &&
 448       accessor_ik->protection_domain() == accessee_ik->protection_domain() &&
 449       accessor_ik->class_loader() == accessee_ik->class_loader();
 450   }
 451 
 452   return false;
 453 }
 454 
 455 bool Reflection::verify_class_access(const Klass* current_class,
 456                                      const Klass* new_class,
 457                                      bool classloader_only) {
 458   // Verify that current_class can access new_class.  If the classloader_only
 459   // flag is set, we automatically allow any accesses in which current_class
 460   // doesn't have a classloader.
 461   if ((current_class == NULL) ||
 462       (current_class == new_class) ||
 463       (new_class->is_public()) ||
 464       is_same_class_package(current_class, new_class)) {
 465     return true;
 466   }
 467   // Allow all accesses from sun/reflect/MagicAccessorImpl subclasses to
 468   // succeed trivially.
 469   if (current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) {
 470     return true;
 471   }
 472 
 473   return can_relax_access_check_for(current_class, new_class, classloader_only);
 474 }
 475 
 476 bool Reflection::verify_field_access(const Klass* current_class,
 477                                      const Klass* resolved_class,
 478                                      const Klass* field_class,
 479                                      AccessFlags access,
 480                                      bool classloader_only,
 481                                      bool protected_restriction) {
 482   // Verify that current_class can access a field of field_class, where that
 483   // field's access bits are "access".  We assume that we've already verified
 484   // that current_class can access field_class.
 485   //
 486   // If the classloader_only flag is set, we automatically allow any accesses
 487   // in which current_class doesn't have a classloader.
 488   //
 489   // "resolved_class" is the runtime type of "field_class". Sometimes we don't
 490   // need this distinction (e.g. if all we have is the runtime type, or during
 491   // class file parsing when we only care about the static type); in that case
 492   // callers should ensure that resolved_class == field_class.
 493   //
 494   if ((current_class == NULL) ||
 495       (current_class == field_class) ||
 496       access.is_public()) {
 497     return true;
 498   }
 499 
 500   const Klass* host_class = current_class;
 501   while (host_class->is_instance_klass() &&
 502          InstanceKlass::cast(host_class)->is_anonymous()) {
 503     const Klass* next_host_class = InstanceKlass::cast(host_class)->host_klass();
 504     if (next_host_class == NULL)  break;
 505     host_class = next_host_class;
 506   }
 507   if (host_class == field_class) {
 508     return true;
 509   }
 510 
 511   if (access.is_protected()) {
 512     if (!protected_restriction) {
 513       // See if current_class (or outermost host class) is a subclass of field_class
 514       // An interface may not access protected members of j.l.Object
 515       if (!host_class->is_interface() && host_class->is_subclass_of(field_class)) {
 516         if (access.is_static() || // static fields are ok, see 6622385
 517             current_class == resolved_class ||
 518             field_class == resolved_class ||
 519             host_class->is_subclass_of(resolved_class) ||
 520             resolved_class->is_subclass_of(host_class)) {
 521           return true;
 522         }
 523       }
 524     }
 525   }
 526 
 527   if (!access.is_private() && is_same_class_package(current_class, field_class)) {
 528     return true;
 529   }
 530 
 531   // Allow all accesses from sun/reflect/MagicAccessorImpl subclasses to
 532   // succeed trivially.
 533   if (current_class->is_subclass_of(SystemDictionary::reflect_MagicAccessorImpl_klass())) {
 534     return true;
 535   }
 536 
 537   return can_relax_access_check_for(
 538     current_class, field_class, classloader_only);
 539 }
 540 
 541 bool Reflection::is_same_class_package(const Klass* class1, const Klass* class2) {
 542   return InstanceKlass::cast(class1)->is_same_class_package(class2);
 543 }
 544 
 545 // Checks that the 'outer' klass has declared 'inner' as being an inner klass. If not,
 546 // throw an incompatible class change exception
 547 // If inner_is_member, require the inner to be a member of the outer.
 548 // If !inner_is_member, require the inner to be anonymous (a non-member).
 549 // Caller is responsible for figuring out in advance which case must be true.
 550 void Reflection::check_for_inner_class(instanceKlassHandle outer, instanceKlassHandle inner,
 551                                        bool inner_is_member, TRAPS) {
 552   InnerClassesIterator iter(outer);
 553   constantPoolHandle cp   (THREAD, outer->constants());
 554   for (; !iter.done(); iter.next()) {
 555      int ioff = iter.inner_class_info_index();
 556      int ooff = iter.outer_class_info_index();
 557 
 558      if (inner_is_member && ioff != 0 && ooff != 0) {
 559         Klass* o = cp->klass_at(ooff, CHECK);
 560         if (o == outer()) {
 561           Klass* i = cp->klass_at(ioff, CHECK);
 562           if (i == inner()) {
 563             return;
 564           }
 565         }
 566      }
 567      if (!inner_is_member && ioff != 0 && ooff == 0 &&
 568          cp->klass_name_at_matches(inner, ioff)) {
 569         Klass* i = cp->klass_at(ioff, CHECK);
 570         if (i == inner()) {
 571           return;
 572         }
 573      }
 574   }
 575 
 576   // 'inner' not declared as an inner klass in outer
 577   ResourceMark rm(THREAD);
 578   Exceptions::fthrow(
 579     THREAD_AND_LOCATION,
 580     vmSymbols::java_lang_IncompatibleClassChangeError(),
 581     "%s and %s disagree on InnerClasses attribute",
 582     outer->external_name(),
 583     inner->external_name()
 584   );
 585 }
 586 
 587 // Utility method converting a single SignatureStream element into java.lang.Class instance
 588 static oop get_mirror_from_signature(methodHandle method,
 589                                      SignatureStream* ss,
 590                                      TRAPS) {
 591 
 592 
 593   if (T_OBJECT == ss->type() || T_ARRAY == ss->type()) {
 594     Symbol* name = ss->as_symbol(CHECK_NULL);
 595     oop loader = method->method_holder()->class_loader();
 596     oop protection_domain = method->method_holder()->protection_domain();
 597     const Klass* k = SystemDictionary::resolve_or_fail(name,
 598                                                        Handle(THREAD, loader),
 599                                                        Handle(THREAD, protection_domain),
 600                                                        true,
 601                                                        CHECK_NULL);
 602     if (log_is_enabled(Info, classresolve)) {
 603       trace_class_resolution(k);
 604     }
 605     return k->java_mirror();
 606   }
 607 
 608   assert(ss->type() != T_VOID || ss->at_return_type(),
 609     "T_VOID should only appear as return type");
 610 
 611   return java_lang_Class::primitive_mirror(ss->type());
 612 }
 613 
 614 static objArrayHandle get_parameter_types(methodHandle method,
 615                                           int parameter_count,
 616                                           oop* return_type,
 617                                           TRAPS) {
 618   // Allocate array holding parameter types (java.lang.Class instances)
 619   objArrayOop m = oopFactory::new_objArray(SystemDictionary::Class_klass(), parameter_count, CHECK_(objArrayHandle()));
 620   objArrayHandle mirrors(THREAD, m);
 621   int index = 0;
 622   // Collect parameter types
 623   ResourceMark rm(THREAD);
 624   Symbol*  signature = method->signature();
 625   SignatureStream ss(signature);
 626   while (!ss.at_return_type()) {
 627     oop mirror = get_mirror_from_signature(method, &ss, CHECK_(objArrayHandle()));
 628     mirrors->obj_at_put(index++, mirror);
 629     ss.next();
 630   }
 631   assert(index == parameter_count, "invalid parameter count");
 632   if (return_type != NULL) {
 633     // Collect return type as well
 634     assert(ss.at_return_type(), "return type should be present");
 635     *return_type = get_mirror_from_signature(method, &ss, CHECK_(objArrayHandle()));
 636   }
 637   return mirrors;
 638 }
 639 
 640 static objArrayHandle get_exception_types(methodHandle method, TRAPS) {
 641   return method->resolved_checked_exceptions(THREAD);
 642 }
 643 
 644 static Handle new_type(Symbol* signature, KlassHandle k, TRAPS) {
 645   // Basic types
 646   BasicType type = vmSymbols::signature_type(signature);
 647   if (type != T_OBJECT) {
 648     return Handle(THREAD, Universe::java_mirror(type));
 649   }
 650 
 651   Klass* result =
 652     SystemDictionary::resolve_or_fail(signature,
 653                                       Handle(THREAD, k->class_loader()),
 654                                       Handle(THREAD, k->protection_domain()),
 655                                       true, CHECK_(Handle()));
 656 
 657   if (log_is_enabled(Info, classresolve)) {
 658     trace_class_resolution(result);
 659   }
 660 
 661   oop nt = result->java_mirror();
 662   return Handle(THREAD, nt);
 663 }
 664 
 665 
 666 oop Reflection::new_method(const methodHandle& method, bool for_constant_pool_access, TRAPS) {
 667   // Allow sun.reflect.ConstantPool to refer to <clinit> methods as java.lang.reflect.Methods.
 668   assert(!method()->is_initializer() ||
 669          (for_constant_pool_access && method()->is_static()),
 670          "should call new_constructor instead");
 671   instanceKlassHandle holder (THREAD, method->method_holder());
 672   int slot = method->method_idnum();
 673 
 674   Symbol*  signature  = method->signature();
 675   int parameter_count = ArgumentCount(signature).size();
 676   oop return_type_oop = NULL;
 677   objArrayHandle parameter_types = get_parameter_types(method, parameter_count, &return_type_oop, CHECK_NULL);
 678   if (parameter_types.is_null() || return_type_oop == NULL) return NULL;
 679 
 680   Handle return_type(THREAD, return_type_oop);
 681 
 682   objArrayHandle exception_types = get_exception_types(method, CHECK_NULL);
 683 
 684   if (exception_types.is_null()) return NULL;
 685 
 686   Symbol*  method_name = method->name();
 687   oop name_oop = StringTable::intern(method_name, CHECK_NULL);
 688   Handle name = Handle(THREAD, name_oop);
 689   if (name == NULL) return NULL;
 690 
 691   const int modifiers = method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
 692 
 693   Handle mh = java_lang_reflect_Method::create(CHECK_NULL);
 694 
 695   java_lang_reflect_Method::set_clazz(mh(), holder->java_mirror());
 696   java_lang_reflect_Method::set_slot(mh(), slot);
 697   java_lang_reflect_Method::set_name(mh(), name());
 698   java_lang_reflect_Method::set_return_type(mh(), return_type());
 699   java_lang_reflect_Method::set_parameter_types(mh(), parameter_types());
 700   java_lang_reflect_Method::set_exception_types(mh(), exception_types());
 701   java_lang_reflect_Method::set_modifiers(mh(), modifiers);
 702   java_lang_reflect_Method::set_override(mh(), false);
 703   if (java_lang_reflect_Method::has_signature_field() &&
 704       method->generic_signature() != NULL) {
 705     Symbol*  gs = method->generic_signature();
 706     Handle sig = java_lang_String::create_from_symbol(gs, CHECK_NULL);
 707     java_lang_reflect_Method::set_signature(mh(), sig());
 708   }
 709   if (java_lang_reflect_Method::has_annotations_field()) {
 710     typeArrayOop an_oop = Annotations::make_java_array(method->annotations(), CHECK_NULL);
 711     java_lang_reflect_Method::set_annotations(mh(), an_oop);
 712   }
 713   if (java_lang_reflect_Method::has_parameter_annotations_field()) {
 714     typeArrayOop an_oop = Annotations::make_java_array(method->parameter_annotations(), CHECK_NULL);
 715     java_lang_reflect_Method::set_parameter_annotations(mh(), an_oop);
 716   }
 717   if (java_lang_reflect_Method::has_annotation_default_field()) {
 718     typeArrayOop an_oop = Annotations::make_java_array(method->annotation_default(), CHECK_NULL);
 719     java_lang_reflect_Method::set_annotation_default(mh(), an_oop);
 720   }
 721   if (java_lang_reflect_Method::has_type_annotations_field()) {
 722     typeArrayOop an_oop = Annotations::make_java_array(method->type_annotations(), CHECK_NULL);
 723     java_lang_reflect_Method::set_type_annotations(mh(), an_oop);
 724   }
 725   return mh();
 726 }
 727 
 728 
 729 oop Reflection::new_constructor(const methodHandle& method, TRAPS) {
 730   assert(method()->is_initializer(), "should call new_method instead");
 731 
 732   instanceKlassHandle  holder (THREAD, method->method_holder());
 733   int slot = method->method_idnum();
 734 
 735   Symbol*  signature  = method->signature();
 736   int parameter_count = ArgumentCount(signature).size();
 737   objArrayHandle parameter_types = get_parameter_types(method, parameter_count, NULL, CHECK_NULL);
 738   if (parameter_types.is_null()) return NULL;
 739 
 740   objArrayHandle exception_types = get_exception_types(method, CHECK_NULL);
 741   if (exception_types.is_null()) return NULL;
 742 
 743   const int modifiers = method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
 744 
 745   Handle ch = java_lang_reflect_Constructor::create(CHECK_NULL);
 746 
 747   java_lang_reflect_Constructor::set_clazz(ch(), holder->java_mirror());
 748   java_lang_reflect_Constructor::set_slot(ch(), slot);
 749   java_lang_reflect_Constructor::set_parameter_types(ch(), parameter_types());
 750   java_lang_reflect_Constructor::set_exception_types(ch(), exception_types());
 751   java_lang_reflect_Constructor::set_modifiers(ch(), modifiers);
 752   java_lang_reflect_Constructor::set_override(ch(), false);
 753   if (java_lang_reflect_Constructor::has_signature_field() &&
 754       method->generic_signature() != NULL) {
 755     Symbol*  gs = method->generic_signature();
 756     Handle sig = java_lang_String::create_from_symbol(gs, CHECK_NULL);
 757     java_lang_reflect_Constructor::set_signature(ch(), sig());
 758   }
 759   if (java_lang_reflect_Constructor::has_annotations_field()) {
 760     typeArrayOop an_oop = Annotations::make_java_array(method->annotations(), CHECK_NULL);
 761     java_lang_reflect_Constructor::set_annotations(ch(), an_oop);
 762   }
 763   if (java_lang_reflect_Constructor::has_parameter_annotations_field()) {
 764     typeArrayOop an_oop = Annotations::make_java_array(method->parameter_annotations(), CHECK_NULL);
 765     java_lang_reflect_Constructor::set_parameter_annotations(ch(), an_oop);
 766   }
 767   if (java_lang_reflect_Constructor::has_type_annotations_field()) {
 768     typeArrayOop an_oop = Annotations::make_java_array(method->type_annotations(), CHECK_NULL);
 769     java_lang_reflect_Constructor::set_type_annotations(ch(), an_oop);
 770   }
 771   return ch();
 772 }
 773 
 774 
 775 oop Reflection::new_field(fieldDescriptor* fd, TRAPS) {
 776   Symbol*  field_name = fd->name();
 777   oop name_oop = StringTable::intern(field_name, CHECK_NULL);
 778   Handle name = Handle(THREAD, name_oop);
 779   Symbol*  signature  = fd->signature();
 780   instanceKlassHandle  holder    (THREAD, fd->field_holder());
 781   Handle type = new_type(signature, holder, CHECK_NULL);
 782   Handle rh  = java_lang_reflect_Field::create(CHECK_NULL);
 783 
 784   java_lang_reflect_Field::set_clazz(rh(), fd->field_holder()->java_mirror());
 785   java_lang_reflect_Field::set_slot(rh(), fd->index());
 786   java_lang_reflect_Field::set_name(rh(), name());
 787   java_lang_reflect_Field::set_type(rh(), type());
 788   // Note the ACC_ANNOTATION bit, which is a per-class access flag, is never set here.
 789   java_lang_reflect_Field::set_modifiers(rh(), fd->access_flags().as_int() & JVM_RECOGNIZED_FIELD_MODIFIERS);
 790   java_lang_reflect_Field::set_override(rh(), false);
 791   if (java_lang_reflect_Field::has_signature_field() &&
 792       fd->has_generic_signature()) {
 793     Symbol*  gs = fd->generic_signature();
 794     Handle sig = java_lang_String::create_from_symbol(gs, CHECK_NULL);
 795     java_lang_reflect_Field::set_signature(rh(), sig());
 796   }
 797   if (java_lang_reflect_Field::has_annotations_field()) {
 798     typeArrayOop an_oop = Annotations::make_java_array(fd->annotations(), CHECK_NULL);
 799     java_lang_reflect_Field::set_annotations(rh(), an_oop);
 800   }
 801   if (java_lang_reflect_Field::has_type_annotations_field()) {
 802     typeArrayOop an_oop = Annotations::make_java_array(fd->type_annotations(), CHECK_NULL);
 803     java_lang_reflect_Field::set_type_annotations(rh(), an_oop);
 804   }
 805   return rh();
 806 }
 807 
 808 oop Reflection::new_parameter(Handle method, int index, Symbol* sym,
 809                               int flags, TRAPS) {
 810 
 811   Handle rh = java_lang_reflect_Parameter::create(CHECK_NULL);
 812 
 813   if(NULL != sym) {
 814     Handle name = java_lang_String::create_from_symbol(sym, CHECK_NULL);
 815     java_lang_reflect_Parameter::set_name(rh(), name());
 816   } else {
 817     java_lang_reflect_Parameter::set_name(rh(), NULL);
 818   }
 819 
 820   java_lang_reflect_Parameter::set_modifiers(rh(), flags);
 821   java_lang_reflect_Parameter::set_executable(rh(), method());
 822   java_lang_reflect_Parameter::set_index(rh(), index);
 823   return rh();
 824 }
 825 
 826 
 827 static methodHandle resolve_interface_call(instanceKlassHandle klass,
 828                                            const methodHandle& method,
 829                                            KlassHandle recv_klass,
 830                                            Handle receiver,
 831                                            TRAPS) {
 832 
 833   assert(!method.is_null() , "method should not be null");
 834 
 835   CallInfo info;
 836   Symbol*  signature  = method->signature();
 837   Symbol*  name       = method->name();
 838   LinkResolver::resolve_interface_call(info, receiver, recv_klass,
 839                                        LinkInfo(klass, name, signature),
 840                                        true,
 841                                        CHECK_(methodHandle()));
 842   return info.selected_method();
 843 }
 844 
 845 // Conversion
 846 static BasicType basic_type_mirror_to_basic_type(oop basic_type_mirror, TRAPS) {
 847   assert(java_lang_Class::is_primitive(basic_type_mirror),
 848     "just checking");
 849   return java_lang_Class::primitive_type(basic_type_mirror);
 850 }
 851 
 852 // Narrowing of basic types. Used to create correct jvalues for
 853 // boolean, byte, char and short return return values from interpreter
 854 // which are returned as ints. Throws IllegalArgumentException.
 855 static void narrow(jvalue* value, BasicType narrow_type, TRAPS) {
 856   switch (narrow_type) {
 857   case T_BOOLEAN:
 858     value->z = (jboolean)value->i;
 859     return;
 860   case T_BYTE:
 861     value->b = (jbyte)value->i;
 862     return;
 863   case T_CHAR:
 864     value->c = (jchar)value->i;
 865     return;
 866   case T_SHORT:
 867     value->s = (jshort)value->i;
 868     return;
 869   default:
 870     break; // fail
 871   }
 872   THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "argument type mismatch");
 873 }
 874 
 875 
 876 // Method call (shared by invoke_method and invoke_constructor)
 877 static oop invoke(instanceKlassHandle klass,
 878                   methodHandle reflected_method,
 879                   Handle receiver,
 880                   bool override,
 881                   objArrayHandle ptypes,
 882                   BasicType rtype,
 883                   objArrayHandle args,
 884                   bool is_method_invoke,
 885                   TRAPS) {
 886 
 887   ResourceMark rm(THREAD);
 888 
 889   methodHandle method;      // actual method to invoke
 890   KlassHandle target_klass; // target klass, receiver's klass for non-static
 891 
 892   // Ensure klass is initialized
 893   klass->initialize(CHECK_NULL);
 894 
 895   bool is_static = reflected_method->is_static();
 896   if (is_static) {
 897     // ignore receiver argument
 898     method = reflected_method;
 899     target_klass = klass;
 900   } else {
 901     // check for null receiver
 902     if (receiver.is_null()) {
 903       THROW_0(vmSymbols::java_lang_NullPointerException());
 904     }
 905     // Check class of receiver against class declaring method
 906     if (!receiver->is_a(klass())) {
 907       THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "object is not an instance of declaring class");
 908     }
 909     // target klass is receiver's klass
 910     target_klass = KlassHandle(THREAD, receiver->klass());
 911     // no need to resolve if method is private or <init>
 912     if (reflected_method->is_private() || reflected_method->name() == vmSymbols::object_initializer_name()) {
 913       method = reflected_method;
 914     } else {
 915       // resolve based on the receiver
 916       if (reflected_method->method_holder()->is_interface()) {
 917         // resolve interface call
 918         //
 919         // Match resolution errors with those thrown due to reflection inlining
 920         // Linktime resolution & IllegalAccessCheck already done by Class.getMethod()
 921         method = resolve_interface_call(klass, reflected_method, target_klass, receiver, THREAD);
 922         if (HAS_PENDING_EXCEPTION) {
 923           // Method resolution threw an exception; wrap it in an InvocationTargetException
 924           oop resolution_exception = PENDING_EXCEPTION;
 925           CLEAR_PENDING_EXCEPTION;
 926           // JVMTI has already reported the pending exception
 927           // JVMTI internal flag reset is needed in order to report InvocationTargetException
 928           if (THREAD->is_Java_thread()) {
 929             JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
 930           }
 931           JavaCallArguments args(Handle(THREAD, resolution_exception));
 932           THROW_ARG_0(vmSymbols::java_lang_reflect_InvocationTargetException(),
 933                       vmSymbols::throwable_void_signature(),
 934                       &args);
 935         }
 936       }  else {
 937         // if the method can be overridden, we resolve using the vtable index.
 938         assert(!reflected_method->has_itable_index(), "");
 939         int index = reflected_method->vtable_index();
 940         method = reflected_method;
 941         if (index != Method::nonvirtual_vtable_index) {
 942           // target_klass might be an arrayKlassOop but all vtables start at
 943           // the same place. The cast is to avoid virtual call and assertion.
 944           InstanceKlass* inst = (InstanceKlass*)target_klass();
 945           method = methodHandle(THREAD, inst->method_at_vtable(index));
 946         }
 947         if (!method.is_null()) {
 948           // Check for abstract methods as well
 949           if (method->is_abstract()) {
 950             // new default: 6531596
 951             ResourceMark rm(THREAD);
 952             Handle h_origexception = Exceptions::new_exception(THREAD,
 953               vmSymbols::java_lang_AbstractMethodError(),
 954               Method::name_and_sig_as_C_string(target_klass(),
 955               method->name(),
 956               method->signature()));
 957             JavaCallArguments args(h_origexception);
 958             THROW_ARG_0(vmSymbols::java_lang_reflect_InvocationTargetException(),
 959               vmSymbols::throwable_void_signature(),
 960               &args);
 961           }
 962         }
 963       }
 964     }
 965   }
 966 
 967   // I believe this is a ShouldNotGetHere case which requires
 968   // an internal vtable bug. If you ever get this please let Karen know.
 969   if (method.is_null()) {
 970     ResourceMark rm(THREAD);
 971     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(),
 972                 Method::name_and_sig_as_C_string(klass(),
 973                 reflected_method->name(),
 974                 reflected_method->signature()));
 975   }
 976 
 977   assert(ptypes->is_objArray(), "just checking");
 978   int args_len = args.is_null() ? 0 : args->length();
 979   // Check number of arguments
 980   if (ptypes->length() != args_len) {
 981     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
 982                 "wrong number of arguments");
 983   }
 984 
 985   // Create object to contain parameters for the JavaCall
 986   JavaCallArguments java_args(method->size_of_parameters());
 987 
 988   if (!is_static) {
 989     java_args.push_oop(receiver);
 990   }
 991 
 992   for (int i = 0; i < args_len; i++) {
 993     oop type_mirror = ptypes->obj_at(i);
 994     oop arg = args->obj_at(i);
 995     if (java_lang_Class::is_primitive(type_mirror)) {
 996       jvalue value;
 997       BasicType ptype = basic_type_mirror_to_basic_type(type_mirror, CHECK_NULL);
 998       BasicType atype = Reflection::unbox_for_primitive(arg, &value, CHECK_NULL);
 999       if (ptype != atype) {
1000         Reflection::widen(&value, atype, ptype, CHECK_NULL);
1001       }
1002       switch (ptype) {
1003         case T_BOOLEAN:     java_args.push_int(value.z);    break;
1004         case T_CHAR:        java_args.push_int(value.c);    break;
1005         case T_BYTE:        java_args.push_int(value.b);    break;
1006         case T_SHORT:       java_args.push_int(value.s);    break;
1007         case T_INT:         java_args.push_int(value.i);    break;
1008         case T_LONG:        java_args.push_long(value.j);   break;
1009         case T_FLOAT:       java_args.push_float(value.f);  break;
1010         case T_DOUBLE:      java_args.push_double(value.d); break;
1011         default:
1012           THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "argument type mismatch");
1013       }
1014     } else {
1015       if (arg != NULL) {
1016         Klass* k = java_lang_Class::as_Klass(type_mirror);
1017         if (!arg->is_a(k)) {
1018           THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1019                       "argument type mismatch");
1020         }
1021       }
1022       Handle arg_handle(THREAD, arg);         // Create handle for argument
1023       java_args.push_oop(arg_handle); // Push handle
1024     }
1025   }
1026 
1027   assert(java_args.size_of_parameters() == method->size_of_parameters(),
1028     "just checking");
1029 
1030   // All oops (including receiver) is passed in as Handles. An potential oop is returned as an
1031   // oop (i.e., NOT as an handle)
1032   JavaValue result(rtype);
1033   JavaCalls::call(&result, method, &java_args, THREAD);
1034 
1035   if (HAS_PENDING_EXCEPTION) {
1036     // Method threw an exception; wrap it in an InvocationTargetException
1037     oop target_exception = PENDING_EXCEPTION;
1038     CLEAR_PENDING_EXCEPTION;
1039     // JVMTI has already reported the pending exception
1040     // JVMTI internal flag reset is needed in order to report InvocationTargetException
1041     if (THREAD->is_Java_thread()) {
1042       JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
1043     }
1044 
1045     JavaCallArguments args(Handle(THREAD, target_exception));
1046     THROW_ARG_0(vmSymbols::java_lang_reflect_InvocationTargetException(),
1047                 vmSymbols::throwable_void_signature(),
1048                 &args);
1049   } else {
1050     if (rtype == T_BOOLEAN || rtype == T_BYTE || rtype == T_CHAR || rtype == T_SHORT) {
1051       narrow((jvalue*)result.get_value_addr(), rtype, CHECK_NULL);
1052     }
1053     return Reflection::box((jvalue*)result.get_value_addr(), rtype, THREAD);
1054   }
1055 }
1056 
1057 // This would be nicer if, say, java.lang.reflect.Method was a subclass
1058 // of java.lang.reflect.Constructor
1059 
1060 oop Reflection::invoke_method(oop method_mirror, Handle receiver, objArrayHandle args, TRAPS) {
1061   oop mirror             = java_lang_reflect_Method::clazz(method_mirror);
1062   int slot               = java_lang_reflect_Method::slot(method_mirror);
1063   bool override          = java_lang_reflect_Method::override(method_mirror) != 0;
1064   objArrayHandle ptypes(THREAD, objArrayOop(java_lang_reflect_Method::parameter_types(method_mirror)));
1065 
1066   oop return_type_mirror = java_lang_reflect_Method::return_type(method_mirror);
1067   BasicType rtype;
1068   if (java_lang_Class::is_primitive(return_type_mirror)) {
1069     rtype = basic_type_mirror_to_basic_type(return_type_mirror, CHECK_NULL);
1070   } else {
1071     rtype = T_OBJECT;
1072   }
1073 
1074   instanceKlassHandle klass(THREAD, java_lang_Class::as_Klass(mirror));
1075   Method* m = klass->method_with_idnum(slot);
1076   if (m == NULL) {
1077     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "invoke");
1078   }
1079   methodHandle method(THREAD, m);
1080 
1081   return invoke(klass, method, receiver, override, ptypes, rtype, args, true, THREAD);
1082 }
1083 
1084 
1085 oop Reflection::invoke_constructor(oop constructor_mirror, objArrayHandle args, TRAPS) {
1086   oop mirror             = java_lang_reflect_Constructor::clazz(constructor_mirror);
1087   int slot               = java_lang_reflect_Constructor::slot(constructor_mirror);
1088   bool override          = java_lang_reflect_Constructor::override(constructor_mirror) != 0;
1089   objArrayHandle ptypes(THREAD, objArrayOop(java_lang_reflect_Constructor::parameter_types(constructor_mirror)));
1090 
1091   instanceKlassHandle klass(THREAD, java_lang_Class::as_Klass(mirror));
1092   Method* m = klass->method_with_idnum(slot);
1093   if (m == NULL) {
1094     THROW_MSG_0(vmSymbols::java_lang_InternalError(), "invoke");
1095   }
1096   methodHandle method(THREAD, m);
1097   assert(method->name() == vmSymbols::object_initializer_name(), "invalid constructor");
1098 
1099   // Make sure klass gets initialize
1100   klass->initialize(CHECK_NULL);
1101 
1102   // Create new instance (the receiver)
1103   klass->check_valid_for_instantiation(false, CHECK_NULL);
1104   Handle receiver = klass->allocate_instance_handle(CHECK_NULL);
1105 
1106   // Ignore result from call and return receiver
1107   invoke(klass, method, receiver, override, ptypes, T_VOID, args, false, CHECK_NULL);
1108   return receiver();
1109 }