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/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "memory/oopFactory.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "memory/universe.hpp"
  31 #include "oops/instanceKlass.hpp"
  32 #include "oops/oop.inline.hpp"
  33 #include "oops/symbol.hpp"
  34 #include "oops/typeArrayKlass.hpp"
  35 #include "oops/valueKlass.hpp"
  36 #include "runtime/handles.inline.hpp"
  37 #include "runtime/signature.hpp"
  38 
  39 // Implementation of SignatureIterator
  40 
  41 // Signature syntax:
  42 //
  43 // Signature  = "(" {Parameter} ")" ReturnType.
  44 // Parameter  = FieldType.
  45 // ReturnType = FieldType | "V".
  46 // FieldType  = "B" | "C" | "D" | "F" | "I" | "J" | "S" | "Z" | "L" ClassName ";" | "Q" ValueClassName ";" | "[" FieldType.
  47 // ClassName  = string.
  48 
  49 
  50 SignatureIterator::SignatureIterator(Symbol* signature) {
  51   _signature       = signature;
  52   _parameter_index = 0;
  53 }
  54 
  55 void SignatureIterator::expect(char c) {
  56   if (_signature->char_at(_index) != c) fatal("expecting %c", c);
  57   _index++;
  58 }
  59 
  60 int SignatureIterator::parse_type() {
  61   // Note: This function could be simplified by using "return T_XXX_size;"
  62   //       instead of the assignment and the break statements. However, it
  63   //       seems that the product build for win32_i486 with MS VC++ 6.0 doesn't
  64   //       work (stack underflow for some tests) - this seems to be a VC++ 6.0
  65   //       compiler bug (was problem - gri 4/27/2000).
  66   int size = -1;
  67   switch(_signature->char_at(_index)) {
  68     case 'B': do_byte  (); if (_parameter_index < 0 ) _return_type = T_BYTE;
  69               _index++; size = T_BYTE_size   ; break;
  70     case 'C': do_char  (); if (_parameter_index < 0 ) _return_type = T_CHAR;
  71               _index++; size = T_CHAR_size   ; break;
  72     case 'D': do_double(); if (_parameter_index < 0 ) _return_type = T_DOUBLE;
  73               _index++; size = T_DOUBLE_size ; break;
  74     case 'F': do_float (); if (_parameter_index < 0 ) _return_type = T_FLOAT;
  75               _index++; size = T_FLOAT_size  ; break;
  76     case 'I': do_int   (); if (_parameter_index < 0 ) _return_type = T_INT;
  77               _index++; size = T_INT_size    ; break;
  78     case 'J': do_long  (); if (_parameter_index < 0 ) _return_type = T_LONG;
  79               _index++; size = T_LONG_size   ; break;
  80     case 'S': do_short (); if (_parameter_index < 0 ) _return_type = T_SHORT;
  81               _index++; size = T_SHORT_size  ; break;
  82     case 'Z': do_bool  (); if (_parameter_index < 0 ) _return_type = T_BOOLEAN;
  83               _index++; size = T_BOOLEAN_size; break;
  84     case 'V': do_void  (); if (_parameter_index < 0 ) _return_type = T_VOID;
  85               _index++; size = T_VOID_size;  ; break;
  86     case 'L':
  87       { int begin = ++_index;
  88         Symbol* sig = _signature;
  89         while (sig->char_at(_index++) != ';') ;
  90         do_object(begin, _index);
  91       }
  92       if (_parameter_index < 0 ) _return_type = T_OBJECT;
  93       size = T_OBJECT_size;
  94       break;
  95     case 'Q':
  96       { int begin = ++_index;
  97       Symbol* sig = _signature;
  98       while (sig->char_at(_index++) != ';') ;
  99       do_valuetype(begin, _index);
 100       }
 101       if (_parameter_index < 0 ) _return_type = T_VALUETYPE;
 102       size = T_VALUETYPE_size;
 103       break;
 104     case '[':
 105       { int begin = ++_index;
 106         Symbol* sig = _signature;
 107         while (sig->char_at(_index) == '[') {
 108           _index++;
 109         }
 110         if (sig->char_at(_index) == 'L' || sig->char_at(_index) == 'Q') {
 111           while (sig->char_at(_index++) != ';') ;
 112         } else {
 113           _index++;
 114         }
 115         do_array(begin, _index);
 116        if (_parameter_index < 0 ) _return_type = T_ARRAY;
 117       }
 118       size = T_ARRAY_size;
 119       break;
 120     default:
 121       ShouldNotReachHere();
 122       break;
 123   }
 124   assert(size >= 0, "size must be set");
 125   return size;
 126 }
 127 
 128 
 129 void SignatureIterator::check_signature_end() {
 130   if (_index < _signature->utf8_length()) {
 131     tty->print_cr("too many chars in signature");
 132     _signature->print_value_on(tty);
 133     tty->print_cr(" @ %d", _index);
 134   }
 135 }
 136 
 137 
 138 void SignatureIterator::iterate_parameters() {
 139   // Parse parameters
 140   _index = 0;
 141   _parameter_index = 0;
 142   expect('(');
 143   while (_signature->char_at(_index) != ')') _parameter_index += parse_type();
 144   expect(')');
 145   _parameter_index = 0;
 146 }
 147 
 148 // Optimized version of iterate_parameters when fingerprint is known
 149 void SignatureIterator::iterate_parameters( uint64_t fingerprint ) {
 150   uint64_t saved_fingerprint = fingerprint;
 151 
 152   // Check for too many arguments
 153   if (fingerprint == (uint64_t)CONST64(-1)) {
 154     SignatureIterator::iterate_parameters();
 155     return;
 156   }
 157 
 158   assert(fingerprint, "Fingerprint should not be 0");
 159 
 160   _parameter_index = 0;
 161   fingerprint = fingerprint >> (static_feature_size + result_feature_size);
 162   while ( 1 ) {
 163     switch ( fingerprint & parameter_feature_mask ) {
 164       case bool_parm:
 165         do_bool();
 166         _parameter_index += T_BOOLEAN_size;
 167         break;
 168       case byte_parm:
 169         do_byte();
 170         _parameter_index += T_BYTE_size;
 171         break;
 172       case char_parm:
 173         do_char();
 174         _parameter_index += T_CHAR_size;
 175         break;
 176       case short_parm:
 177         do_short();
 178         _parameter_index += T_SHORT_size;
 179         break;
 180       case int_parm:
 181         do_int();
 182         _parameter_index += T_INT_size;
 183         break;
 184       case obj_parm:
 185         do_object(0, 0);
 186         _parameter_index += T_OBJECT_size;
 187         break;
 188       case long_parm:
 189         do_long();
 190         _parameter_index += T_LONG_size;
 191         break;
 192       case float_parm:
 193         do_float();
 194         _parameter_index += T_FLOAT_size;
 195         break;
 196       case double_parm:
 197         do_double();
 198         _parameter_index += T_DOUBLE_size;
 199         break;
 200       case done_parm:
 201         return;
 202       default:
 203         tty->print_cr("*** parameter is " UINT64_FORMAT, fingerprint & parameter_feature_mask);
 204         tty->print_cr("*** fingerprint is " PTR64_FORMAT, saved_fingerprint);
 205         ShouldNotReachHere();
 206         break;
 207     }
 208     fingerprint >>= parameter_feature_size;
 209   }
 210 }
 211 
 212 
 213 void SignatureIterator::iterate_returntype() {
 214   // Ignore parameters
 215   _index = 0;
 216   expect('(');
 217   Symbol* sig = _signature;
 218   // Need to skip over each type in the signature's argument list until a
 219   // closing ')' is found., then get the return type.  We cannot just scan
 220   // for the first ')' because ')' is a legal character in a type name.
 221   while (sig->char_at(_index) != ')') {
 222     switch(sig->char_at(_index)) {
 223       case 'B':
 224       case 'C':
 225       case 'D':
 226       case 'F':
 227       case 'I':
 228       case 'J':
 229       case 'S':
 230       case 'Z':
 231       case 'V':
 232         {
 233           _index++;
 234         }
 235         break;
 236       case 'Q':
 237       case 'L':
 238         {
 239           while (sig->char_at(_index++) != ';') ;
 240         }
 241         break;
 242       case '[':
 243         {
 244           while (sig->char_at(++_index) == '[') ;
 245           if (sig->char_at(_index) == 'L' || sig->char_at(_index) == 'Q' ) {
 246             while (sig->char_at(_index++) != ';') ;
 247           } else {
 248             _index++;
 249           }
 250         }
 251         break;
 252       default:
 253         ShouldNotReachHere();
 254         break;
 255     }
 256   }
 257   expect(')');
 258   // Parse return type
 259   _parameter_index = -1;
 260   parse_type();
 261   check_signature_end();
 262   _parameter_index = 0;
 263 }
 264 
 265 
 266 void SignatureIterator::iterate() {
 267   // Parse parameters
 268   _parameter_index = 0;
 269   _index = 0;
 270   expect('(');
 271   while (_signature->char_at(_index) != ')') _parameter_index += parse_type();
 272   expect(')');
 273   // Parse return type
 274   _parameter_index = -1;
 275   parse_type();
 276   check_signature_end();
 277   _parameter_index = 0;
 278 }
 279 
 280 
 281 // Implementation of SignatureStream
 282 SignatureStream::SignatureStream(Symbol* signature, bool is_method) :
 283                    _signature(signature), _at_return_type(false), _previous_name(NULL), _names(NULL) {
 284   _begin = _end = (is_method ? 1 : 0);  // skip first '(' in method signatures
 285   next();
 286 }
 287 
 288 SignatureStream::~SignatureStream() {
 289   // decrement refcount for names created during signature parsing
 290   if (_names != NULL) {
 291     for (int i = 0; i < _names->length(); i++) {
 292       _names->at(i)->decrement_refcount();
 293     }
 294   }
 295 }
 296 
 297 bool SignatureStream::is_done() const {
 298   return _end > _signature->utf8_length();
 299 }
 300 
 301 
 302 void SignatureStream::next_non_primitive(int t) {
 303   switch (t) {
 304     case 'L': {
 305       _type = T_OBJECT;
 306       Symbol* sig = _signature;
 307       while (sig->char_at(_end++) != ';');
 308       break;
 309     }
 310     case 'Q': {
 311       _type = T_VALUETYPE;
 312       Symbol* sig = _signature;
 313       while (sig->char_at(_end++) != ';');
 314       break;
 315     }
 316     case '[': {
 317       _type = T_ARRAY;
 318       Symbol* sig = _signature;
 319       char c = sig->char_at(_end);
 320       while ('0' <= c && c <= '9') c = sig->char_at(_end++);
 321       while (sig->char_at(_end) == '[') {
 322         _end++;
 323         c = sig->char_at(_end);
 324         while ('0' <= c && c <= '9') c = sig->char_at(_end++);
 325       }
 326       switch(sig->char_at(_end)) {
 327         case 'B':
 328         case 'C':
 329         case 'D':
 330         case 'F':
 331         case 'I':
 332         case 'J':
 333         case 'S':
 334         case 'Z':_end++; break;
 335         default: {
 336           while (sig->char_at(_end++) != ';');
 337           break;
 338         }
 339       }
 340       break;
 341     }
 342     case ')': _end++; next(); _at_return_type = true; break;
 343     default : ShouldNotReachHere();
 344   }
 345 }
 346 
 347 
 348 bool SignatureStream::is_object() const {
 349   return _type == T_OBJECT
 350       || _type == T_ARRAY
 351       || _type == T_VALUETYPE;
 352 }
 353 
 354 bool SignatureStream::is_array() const {
 355   return _type == T_ARRAY;
 356 }
 357 
 358 Symbol* SignatureStream::as_symbol() {
 359   // Create a symbol from for string _begin _end
 360   int begin = _begin;
 361   int end   = _end;
 362 
 363   if (  (_signature->char_at(_begin) == 'L' || _signature->char_at(_begin) == 'Q')
 364       && _signature->char_at(_end-1) == ';') {
 365     begin++;
 366     end--;
 367   }
 368 
 369   const char* symbol_chars = (const char*)_signature->base() + begin;
 370   int len = end - begin;
 371 
 372   // Quick check for common symbols in signatures
 373   assert((vmSymbols::java_lang_String()->utf8_length() == 16 && vmSymbols::java_lang_Object()->utf8_length() == 16), "sanity");
 374   if (len == 16 &&
 375       strncmp(symbol_chars, "java/lang/", 10) == 0) {
 376     if (strncmp("String", symbol_chars + 10, 6) == 0) {
 377       return vmSymbols::java_lang_String();
 378     } else if (strncmp("Object", symbol_chars + 10, 6) == 0) {
 379       return vmSymbols::java_lang_Object();
 380     }
 381   }
 382 
 383   Symbol* name = _previous_name;
 384   if (name != NULL && name->equals(symbol_chars, len)) {
 385     return name;
 386   }
 387 
 388   // Save names for cleaning up reference count at the end of
 389   // SignatureStream scope.
 390   name = SymbolTable::new_symbol(symbol_chars, len);
 391   if (!name->is_permanent()) {
 392     if (_names == NULL) {
 393       _names = new GrowableArray<Symbol*>(10);
 394     }
 395     _names->push(name);  // save new symbol for decrementing later
 396   }
 397   _previous_name = name;
 398   return name;
 399 }
 400 
 401 ValueKlass* SignatureStream::as_value_klass(InstanceKlass* holder) {
 402   Thread* THREAD = Thread::current();
 403   Handle class_loader(THREAD, holder->class_loader());
 404   Handle protection_domain(THREAD, holder->protection_domain());
 405   Klass* k = as_klass(class_loader, protection_domain, SignatureStream::ReturnNull, THREAD);
 406   assert(k != NULL && !HAS_PENDING_EXCEPTION, "unresolved value klass");
 407   return ValueKlass::cast(k);
 408 }
 409 
 410 Klass* SignatureStream::as_klass(Handle class_loader, Handle protection_domain,
 411                                  FailureMode failure_mode, TRAPS) {
 412   if (!is_object())  return NULL;
 413   Symbol* name = as_symbol();
 414   if (failure_mode == ReturnNull) {
 415     return SystemDictionary::resolve_or_null(name, class_loader, protection_domain, THREAD);
 416   } else {
 417     bool throw_error = (failure_mode == NCDFError);
 418     return SystemDictionary::resolve_or_fail(name, class_loader, protection_domain, throw_error, THREAD);
 419   }
 420 }
 421 
 422 oop SignatureStream::as_java_mirror(Handle class_loader, Handle protection_domain,
 423                                     FailureMode failure_mode, TRAPS) {
 424   if (!is_object())
 425     return Universe::java_mirror(type());
 426   Klass* klass = as_klass(class_loader, protection_domain, failure_mode, THREAD);
 427   if (klass == NULL)  return NULL;
 428   if (klass->is_value()) {
 429     ValueKlass* vk = ValueKlass::cast(InstanceKlass::cast(klass));
 430     return _type == T_VALUETYPE ? vk->value_mirror() : vk->indirect_mirror();
 431   } else {
 432     assert(_type != T_VALUETYPE, "must not be value type");
 433     return klass->java_mirror();
 434   }
 435 }
 436 
 437 Symbol* SignatureStream::as_symbol_or_null() {
 438   // Create a symbol from for string _begin _end
 439   ResourceMark rm;
 440 
 441   int begin = _begin;
 442   int end   = _end;
 443 
 444   if (  (_signature->char_at(_begin) == 'L' || _signature->char_at(_begin) == 'Q')
 445       && _signature->char_at(_end-1) == ';') {
 446     begin++;
 447     end--;
 448   }
 449 
 450   char* buffer = NEW_RESOURCE_ARRAY(char, end - begin);
 451   for (int index = begin; index < end; index++) {
 452     buffer[index - begin] = _signature->char_at(index);
 453   }
 454   Symbol* result = SymbolTable::probe(buffer, end - begin);
 455   return result;
 456 }
 457 
 458 int SignatureStream::reference_parameter_count() {
 459   int args_count = 0;
 460   for ( ; !at_return_type(); next()) {
 461     if (is_object()) {
 462       args_count++;
 463     }
 464   }
 465   return args_count;
 466 }
 467 
 468 #ifdef ASSERT
 469 bool SignatureVerifier::is_valid_method_signature(const Symbol* sig) {
 470   const char* method_sig = (const char*)sig->bytes();
 471   ssize_t len = sig->utf8_length();
 472   ssize_t index = 0;
 473   if (method_sig != NULL && len > 1 && method_sig[index] == '(') {
 474     ++index;
 475     while (index < len && method_sig[index] != ')') {
 476       ssize_t res = is_valid_type(&method_sig[index], len - index);
 477       if (res == -1) {
 478         return false;
 479       } else {
 480         index += res;
 481       }
 482     }
 483     if (index < len && method_sig[index] == ')') {
 484       // check the return type
 485       ++index;
 486       return (is_valid_type(&method_sig[index], len - index) == (len - index));
 487     }
 488   }
 489   return false;
 490 }
 491 
 492 bool SignatureVerifier::is_valid_type_signature(const Symbol* sig) {
 493   const char* type_sig = (const char*)sig->bytes();
 494   ssize_t len = sig->utf8_length();
 495   return (type_sig != NULL && len >= 1 &&
 496           (is_valid_type(type_sig, len) == len));
 497 }
 498 
 499 // Checks to see if the type (not to go beyond 'limit') refers to a valid type.
 500 // Returns -1 if it is not, or the index of the next character that is not part
 501 // of the type.  The type encoding may end before 'limit' and that's ok.
 502 ssize_t SignatureVerifier::is_valid_type(const char* type, ssize_t limit) {
 503   ssize_t index = 0;
 504 
 505   // Iterate over any number of array dimensions
 506   while (index < limit && type[index] == '[') ++index;
 507   if (index >= limit) {
 508     return -1;
 509   }
 510   switch (type[index]) {
 511     case 'B': case 'C': case 'D': case 'F': case 'I':
 512     case 'J': case 'S': case 'Z': case 'V':
 513       return index + 1;
 514     case 'Q': // fall through
 515     case 'L':
 516       for (index = index + 1; index < limit; ++index) {
 517         char c = type[index];
 518         switch (c) {
 519           case ';':
 520             return index + 1;
 521           case '\0': case '.': case '[':
 522             return -1;
 523           default: ; // fall through
 524         }
 525       }
 526       // fall through
 527     default: ; // fall through
 528   }
 529   return -1;
 530 }
 531 #endif // ASSERT
 532 
 533 // Adds an argument to the signature
 534 void SigEntry::add_entry(GrowableArray<SigEntry>* sig, BasicType bt, int offset) {
 535   sig->append(SigEntry(bt, offset));
 536   if (bt == T_LONG || bt == T_DOUBLE) {
 537     sig->append(SigEntry(T_VOID, offset)); // Longs and doubles take two stack slots
 538   }
 539 }
 540 
 541 // Inserts a reserved argument at position 'i'
 542 void SigEntry::insert_reserved_entry(GrowableArray<SigEntry>* sig, int i, BasicType bt) {
 543   if (bt == T_OBJECT || bt == T_ARRAY || bt == T_VALUETYPE) {
 544     // Treat this as INT to not confuse the GC
 545     bt = T_INT;
 546   } else if (bt == T_LONG || bt == T_DOUBLE) {
 547     // Longs and doubles take two stack slots
 548     sig->insert_before(i, SigEntry(T_VOID, SigEntry::ReservedOffset));
 549   }
 550   sig->insert_before(i, SigEntry(bt, SigEntry::ReservedOffset));
 551 }
 552 
 553 // Returns true if the argument at index 'i' is a reserved argument
 554 bool SigEntry::is_reserved_entry(const GrowableArray<SigEntry>* sig, int i) {
 555   return sig->at(i)._offset == SigEntry::ReservedOffset;
 556 }
 557 
 558 // Returns true if the argument at index 'i' is not a value type delimiter
 559 bool SigEntry::skip_value_delimiters(const GrowableArray<SigEntry>* sig, int i) {
 560   return (sig->at(i)._bt != T_VALUETYPE &&
 561           (sig->at(i)._bt != T_VOID || sig->at(i-1)._bt == T_LONG || sig->at(i-1)._bt == T_DOUBLE));
 562 }
 563 
 564 // Fill basic type array from signature array
 565 int SigEntry::fill_sig_bt(const GrowableArray<SigEntry>* sig, BasicType* sig_bt) {
 566   int count = 0;
 567   for (int i = 0; i < sig->length(); i++) {
 568     if (skip_value_delimiters(sig, i)) {
 569       sig_bt[count++] = sig->at(i)._bt;
 570     }
 571   }
 572   return count;
 573 }
 574 
 575 // Create a temporary symbol from the signature array
 576 TempNewSymbol SigEntry::create_symbol(const GrowableArray<SigEntry>* sig) {
 577   ResourceMark rm;
 578   int length = sig->length();
 579   char* sig_str = NEW_RESOURCE_ARRAY(char, 2*length + 3);
 580   int idx = 0;
 581   sig_str[idx++] = '(';
 582   for (int i = 0; i < length; i++) {
 583     BasicType bt = sig->at(i)._bt;
 584     if (bt == T_VALUETYPE || bt == T_VOID) {
 585       // Ignore
 586     } else {
 587       if (bt == T_ARRAY) {
 588         bt = T_OBJECT; // We don't know the element type, treat as Object
 589       }
 590       sig_str[idx++] = type2char(bt);
 591       if (bt == T_OBJECT) {
 592         sig_str[idx++] = ';';
 593       }
 594     }
 595   }
 596   sig_str[idx++] = ')';
 597   sig_str[idx++] = '\0';
 598   return SymbolTable::new_symbol(sig_str);
 599 }
 600 
 601 // Increment signature iterator (skips value type delimiters and T_VOID) and check if next entry is reserved
 602 bool SigEntry::next_is_reserved(ExtendedSignature& sig, BasicType& bt, bool can_be_void) {
 603   assert(can_be_void || bt != T_VOID, "should never see void");
 604   if (sig.at_end() || (can_be_void && type2size[bt] == 2 && (*sig)._offset != SigEntry::ReservedOffset)) {
 605     // Don't increment at the end or at a T_LONG/T_DOUBLE which will be followed by a (skipped) T_VOID
 606     return false;
 607   }
 608   assert(bt == T_VOID || type2wfield[bt] == type2wfield[(*sig)._bt], "inconsistent signature");
 609   ++sig;
 610   if (!sig.at_end() && (*sig)._offset == SigEntry::ReservedOffset) {
 611     bt = (*sig)._bt;
 612     return true;
 613   }
 614   return false;
 615 }