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