1 /*
  2  * Copyright (c) 1997, 2021, 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 "classfile/vmSymbols.hpp"
 29 #include "memory/oopFactory.hpp"
 30 #include "memory/resourceArea.hpp"
 31 #include "memory/universe.hpp"
 32 #include "oops/instanceKlass.hpp"
 33 #include "oops/klass.inline.hpp"
 34 #include "oops/oop.inline.hpp"
 35 #include "oops/symbol.hpp"
 36 #include "oops/typeArrayKlass.hpp"
 37 #include "runtime/fieldDescriptor.inline.hpp"
 38 #include "runtime/handles.inline.hpp"
 39 #include "runtime/safepointVerifiers.hpp"
 40 #include "runtime/signature.hpp"
 41 
 42 // Implementation of SignatureIterator
 43 
 44 // Signature syntax:
 45 //
 46 // Signature  = "(" {Parameter} ")" ReturnType.
 47 // Parameter  = FieldType.
 48 // ReturnType = FieldType | "V".
 49 // FieldType  = "B" | "C" | "D" | "F" | "I" | "J" | "S" | "Z" | "L" ClassName ";" | "[" FieldType.
 50 // ClassName  = string.
 51 
 52 // The ClassName string can be any JVM-style UTF8 string except:
 53 //  - an empty string (the empty string is never a name of any kind)
 54 //  - a string which begins or ends with slash '/' (the package separator)
 55 //  - a string which contains adjacent slashes '//' (no empty package names)
 56 //  - a string which contains a semicolon ';' (the end-delimiter)
 57 //  - a string which contains a left bracket '[' (the array marker)
 58 //  - a string which contains a dot '.' (the external package separator)
 59 //
 60 // Other "meta-looking" characters, such as '(' and '<' and '+',
 61 // are perfectly legitimate within a class name, for the JVM.
 62 // Class names which contain double slashes ('a//b') and non-initial
 63 // brackets ('a[b]') are reserved for possible enrichment of the
 64 // type language.
 65 
 66 void SignatureIterator::set_fingerprint(fingerprint_t fingerprint) {
 67   if (!fp_is_valid(fingerprint)) {
 68     _fingerprint = fingerprint;
 69     _return_type = T_ILLEGAL;
 70   } else if (fingerprint != _fingerprint) {
 71     assert(_fingerprint == zero_fingerprint(), "consistent fingerprint values");
 72     _fingerprint = fingerprint;
 73     _return_type = fp_return_type(fingerprint);
 74   }
 75 }
 76 
 77 BasicType SignatureIterator::return_type() {
 78   if (_return_type == T_ILLEGAL) {
 79     SignatureStream ss(_signature);
 80     ss.skip_to_return_type();
 81     _return_type = ss.type();
 82     assert(_return_type != T_ILLEGAL, "illegal return type");
 83   }
 84   return _return_type;
 85 }
 86 
 87 bool SignatureIterator::fp_is_valid_type(BasicType type, bool for_return_type) {
 88   assert(type != (BasicType)fp_parameters_done, "fingerprint is incorrectly at done");
 89   assert(((int)type & ~fp_parameter_feature_mask) == 0, "fingerprint feature mask yielded non-zero value");
 90   return (is_java_primitive(type) ||
 91           is_reference_type(type) ||
 92           (for_return_type && type == T_VOID));
 93 }
 94 
 95 ArgumentSizeComputer::ArgumentSizeComputer(Symbol* signature)
 96   : SignatureIterator(signature)
 97 {
 98   _size = 0;
 99   do_parameters_on(this);  // non-virtual template execution
100 }
101 
102 ArgumentCount::ArgumentCount(Symbol* signature)
103   : SignatureIterator(signature)
104 {
105   _size = 0;
106   do_parameters_on(this);  // non-virtual template execution
107 }
108 
109 ReferenceArgumentCount::ReferenceArgumentCount(Symbol* signature)
110   : SignatureIterator(signature)
111 {
112   _refs = 0;
113   do_parameters_on(this);  // non-virtual template execution
114 }
115 
116 void Fingerprinter::compute_fingerprint_and_return_type(bool static_flag) {
117   // See if we fingerprinted this method already
118   if (_method != NULL) {
119     assert(!static_flag, "must not be passed by caller");
120     static_flag = _method->is_static();
121     _fingerprint = _method->constMethod()->fingerprint();
122 
123     if (_fingerprint != zero_fingerprint()) {
124       _return_type = _method->result_type();
125       assert(is_java_type(_return_type), "return type must be a java type");
126       return;
127     }
128 
129     if (_method->size_of_parameters() > fp_max_size_of_parameters) {
130       _fingerprint = overflow_fingerprint();
131       _method->constMethod()->set_fingerprint(_fingerprint);
132       // as long as we are here compute the return type:
133       _return_type = ResultTypeFinder(_method->signature()).type();
134       assert(is_java_type(_return_type), "return type must be a java type");
135       return;
136     }
137   }
138 
139   // Note:  This will always take the slow path, since _fp==zero_fp.
140   initialize_accumulator();
141   do_parameters_on(this);
142   assert(fp_is_valid_type(_return_type, true), "bad result type");
143 
144   // Fill in the return type and static bits:
145   _accumulator |= _return_type << fp_static_feature_size;
146   if (static_flag) {
147     _accumulator |= fp_is_static_bit;
148   } else {
149     _param_size += 1;  // this is the convention for Method::compute_size_of_parameters
150   }
151 
152   // Detect overflow.  (We counted _param_size correctly.)
153   if (_method == NULL && _param_size > fp_max_size_of_parameters) {
154     // We did a one-pass computation of argument size, return type,
155     // and fingerprint.
156     _fingerprint = overflow_fingerprint();
157     return;
158   }
159 
160   assert(_shift_count < BitsPerLong,
161          "shift count overflow %d (%d vs. %d): %s",
162          _shift_count, _param_size, fp_max_size_of_parameters,
163          _signature->as_C_string());
164   assert((_accumulator >> _shift_count) == fp_parameters_done, "must be zero");
165 
166   // This is the result, along with _return_type:
167   _fingerprint = _accumulator;
168 
169   // Cache the result on the method itself:
170   if (_method != NULL) {
171     _method->constMethod()->set_fingerprint(_fingerprint);
172   }
173 }
174 
175 // Implementation of SignatureStream
176 
177 static inline BasicType decode_signature_char(int ch) {
178   switch (ch) {
179 #define EACH_SIG(ch, bt, ignore) \
180     case ch: return bt;
181     SIGNATURE_TYPES_DO(EACH_SIG, ignore)
182 #undef EACH_SIG
183   }
184   return (BasicType)0;
185 }
186 
187 SignatureStream::SignatureStream(const Symbol* signature,
188                                  bool is_method) {
189   assert(!is_method || signature->starts_with(JVM_SIGNATURE_FUNC),
190          "method signature required");
191   _signature = signature;
192   _limit = signature->utf8_length();
193   int oz = (is_method ? _s_method : _s_field);
194   _state = oz;
195   _begin = _end = oz; // skip first '(' in method signatures
196   _array_prefix = 0;  // just for definiteness
197 
198   // assigning java/lang/Object to _previous_name means we can
199   // avoid a number of NULL checks in the parser
200   _previous_name = vmSymbols::java_lang_Object();
201   _names = NULL;
202   next();
203 }
204 
205 SignatureStream::~SignatureStream() {
206   if (_previous_name == vmSymbols::java_lang_Object()) {
207     // no names were created
208     assert(_names == NULL, "_names unexpectedly created");
209     return;
210   }
211 
212   // decrement refcount for names created during signature parsing
213   _previous_name->decrement_refcount();
214   if (_names != NULL) {
215     for (int i = 0; i < _names->length(); i++) {
216       _names->at(i)->decrement_refcount();
217     }
218   }
219 }
220 
221 inline int SignatureStream::scan_type(BasicType type) {
222   const u1* base = _signature->bytes();
223   int end = _end;
224   int limit = _limit;
225   const u1* tem;
226   switch (type) {
227   case T_OBJECT:
228     tem = (const u1*) memchr(&base[end], JVM_SIGNATURE_ENDCLASS, limit - end);
229     return (tem == NULL ? limit : tem + 1 - base);
230 
231   case T_ARRAY:
232     while ((end < limit) && ((char)base[end] == JVM_SIGNATURE_ARRAY)) { end++; }
233     _array_prefix = end - _end;  // number of '[' chars just skipped
234     if (Signature::has_envelope(base[end])) {
235       tem = (const u1 *) memchr(&base[end], JVM_SIGNATURE_ENDCLASS, limit - end);
236       return (tem == NULL ? limit : tem + 1 - base);
237     }
238     // Skipping over a single character for a primitive type.
239     assert(is_java_primitive(decode_signature_char(base[end])), "only primitives expected");
240     return end + 1;
241 
242   default:
243     // Skipping over a single character for a primitive type (or void).
244     assert(!is_reference_type(type), "only primitives or void expected");
245     return end + 1;
246   }
247 }
248 
249 void SignatureStream::next() {
250   const Symbol* sig = _signature;
251   int len = _limit;
252   if (_end >= len) { set_done(); return; }
253   _begin = _end;
254   int ch = sig->char_at(_begin);
255   if (ch == JVM_SIGNATURE_ENDFUNC) {
256     assert(_state == _s_method, "must be in method");
257     _state = _s_method_return;
258     _begin = ++_end;
259     if (_end >= len) { set_done(); return; }
260     ch = sig->char_at(_begin);
261   }
262   BasicType bt = decode_signature_char(ch);
263   assert(ch == type2char(bt), "bad signature char %c/%d", ch, ch);
264   _type = bt;
265   _end = scan_type(bt);
266 }
267 
268 int SignatureStream::skip_whole_array_prefix() {
269   assert(_type == T_ARRAY, "must be");
270 
271   // we are stripping all levels of T_ARRAY,
272   // so we must decode the next character
273   int whole_array_prefix = _array_prefix;
274   int new_begin = _begin + whole_array_prefix;
275   _begin = new_begin;
276   int ch = _signature->char_at(new_begin);
277   BasicType bt = decode_signature_char(ch);
278   assert(ch == type2char(bt), "bad signature char %c/%d", ch, ch);
279   _type = bt;
280   assert(bt != T_VOID && bt != T_ARRAY, "bad signature type");
281   // Don't bother to re-scan, since it won't change the value of _end.
282   return whole_array_prefix;
283 }
284 
285 bool Signature::is_valid_array_signature(const Symbol* sig) {
286   assert(sig->utf8_length() > 1, "this should already have been checked");
287   assert(sig->char_at(0) == JVM_SIGNATURE_ARRAY, "this should already have been checked");
288   // The first character is already checked
289   int i = 1;
290   int len = sig->utf8_length();
291   // First skip all '['s
292   while(i < len - 1 && sig->char_at(i) == JVM_SIGNATURE_ARRAY) i++;
293 
294   // Check type
295   switch(sig->char_at(i)) {
296   case JVM_SIGNATURE_BYTE:
297   case JVM_SIGNATURE_CHAR:
298   case JVM_SIGNATURE_DOUBLE:
299   case JVM_SIGNATURE_FLOAT:
300   case JVM_SIGNATURE_INT:
301   case JVM_SIGNATURE_LONG:
302   case JVM_SIGNATURE_SHORT:
303   case JVM_SIGNATURE_BOOLEAN:
304     // If it is an array, the type is the last character
305     return (i + 1 == len);
306   case JVM_SIGNATURE_CLASS:
307     // If it is an object, the last character must be a ';'
308     return sig->char_at(len - 1) == JVM_SIGNATURE_ENDCLASS;
309   }
310   return false;
311 }
312 
313 BasicType Signature::basic_type(int ch) {
314   BasicType btcode = decode_signature_char(ch);
315   if (btcode == 0)  return T_ILLEGAL;
316   return btcode;
317 }
318 
319 Symbol* Signature::strip_envelope(const Symbol* signature) {
320   assert(has_envelope(signature), "precondition");
321   return SymbolTable::new_symbol((char*) signature->bytes() + 1,
322                                  signature->utf8_length() - 2);
323 }
324 
325 static const int jl_len = 10, object_len = 6, jl_object_len = jl_len + object_len;
326 static const char jl_str[] = "java/lang/";
327 
328 #ifdef ASSERT
329 static bool signature_symbols_sane() {
330   static bool done;
331   if (done)  return true;
332   done = true;
333   // test some tense code that looks for common symbol names:
334   assert(vmSymbols::java_lang_Object()->utf8_length() == jl_object_len &&
335          vmSymbols::java_lang_Object()->starts_with(jl_str, jl_len) &&
336          vmSymbols::java_lang_Object()->ends_with("Object", object_len) &&
337          vmSymbols::java_lang_Object()->is_permanent() &&
338          vmSymbols::java_lang_String()->utf8_length() == jl_object_len &&
339          vmSymbols::java_lang_String()->starts_with(jl_str, jl_len) &&
340          vmSymbols::java_lang_String()->ends_with("String", object_len) &&
341          vmSymbols::java_lang_String()->is_permanent(),
342          "sanity");
343   return true;
344 }
345 #endif //ASSERT
346 
347 // returns a symbol; the caller is responsible for decrementing it
348 Symbol* SignatureStream::find_symbol() {
349   // Create a symbol from for string _begin _end
350   int begin = raw_symbol_begin();
351   int end   = raw_symbol_end();
352 
353   const char* symbol_chars = (const char*)_signature->base() + begin;
354   int len = end - begin;
355 
356   // Quick check for common symbols in signatures
357   assert(signature_symbols_sane(), "incorrect signature sanity check");
358   if (len == jl_object_len &&
359       memcmp(symbol_chars, jl_str, jl_len) == 0) {
360     if (memcmp("String", symbol_chars + jl_len, object_len) == 0) {
361       return vmSymbols::java_lang_String();
362     } else if (memcmp("Object", symbol_chars + jl_len, object_len) == 0) {
363       return vmSymbols::java_lang_Object();
364     }
365   }
366 
367   Symbol* name = _previous_name;
368   if (name->equals(symbol_chars, len)) {
369     return name;
370   }
371 
372   // Save names for cleaning up reference count at the end of
373   // SignatureStream scope.
374   name = SymbolTable::new_symbol(symbol_chars, len);
375 
376   // Only allocate the GrowableArray for the _names buffer if more than
377   // one name is being processed in the signature.
378   if (!_previous_name->is_permanent()) {
379     if (_names == NULL) {
380       _names = new GrowableArray<Symbol*>(10);
381     }
382     _names->push(_previous_name);
383   }
384   _previous_name = name;
385   return name;
386 }
387 
388 Klass* SignatureStream::as_klass(Handle class_loader, Handle protection_domain,
389                                  FailureMode failure_mode, TRAPS) {
390   if (!is_reference()) {
391     return NULL;
392   }
393   Symbol* name = as_symbol();
394   Klass* k = NULL;
395   if (failure_mode == ReturnNull) {
396     // Note:  SD::resolve_or_null returns NULL for most failure modes,
397     // but not all.  Circularity errors, invalid PDs, etc., throw.
398     k = SystemDictionary::resolve_or_null(name, class_loader, protection_domain, CHECK_NULL);
399   } else if (failure_mode == CachedOrNull) {
400     NoSafepointVerifier nsv;  // no loading, now, we mean it!
401     assert(!HAS_PENDING_EXCEPTION, "");
402     k = SystemDictionary::find_instance_klass(name, class_loader, protection_domain);
403     // SD::find does not trigger loading, so there should be no throws
404     // Still, bad things can happen, so we CHECK_NULL and ask callers
405     // to do likewise.
406     return k;
407   } else {
408     // The only remaining failure mode is NCDFError.
409     // The test here allows for an additional mode CNFException
410     // if callers need to request the reflective error instead.
411     bool throw_error = (failure_mode == NCDFError);
412     k = SystemDictionary::resolve_or_fail(name, class_loader, protection_domain, throw_error, CHECK_NULL);
413   }
414 
415   return k;
416 }
417 
418 oop SignatureStream::as_java_mirror(Handle class_loader, Handle protection_domain,
419                                     FailureMode failure_mode, TRAPS) {
420   if (!is_reference()) {
421     return Universe::java_mirror(type());
422   }
423   Klass* klass = as_klass(class_loader, protection_domain, failure_mode, CHECK_NULL);
424   if (klass == NULL) {
425     return NULL;
426   }
427   return klass->java_mirror();
428 }
429 
430 void SignatureStream::skip_to_return_type() {
431   while (!at_return_type()) {
432     next();
433   }
434 }
435 
436 ResolvingSignatureStream::ResolvingSignatureStream(Symbol* signature,
437                                                    Handle class_loader,
438                                                    Handle protection_domain,
439                                                    bool is_method)
440   : SignatureStream(signature, is_method),
441     _class_loader(class_loader), _protection_domain(protection_domain)
442 {
443   initialize_load_origin(NULL);
444 }
445 
446 ResolvingSignatureStream::ResolvingSignatureStream(Symbol* signature, Klass* load_origin, bool is_method)
447   : SignatureStream(signature, is_method)
448 {
449   assert(load_origin != NULL, "");
450   initialize_load_origin(load_origin);
451 }
452 
453 ResolvingSignatureStream::ResolvingSignatureStream(const Method* method)
454   : SignatureStream(method->signature(), true)
455 {
456   initialize_load_origin(method->method_holder());
457 }
458 
459 ResolvingSignatureStream::ResolvingSignatureStream(fieldDescriptor& field)
460   : SignatureStream(field.signature(), false)
461 {
462   initialize_load_origin(field.field_holder());
463 }
464 
465 void ResolvingSignatureStream::cache_handles() {
466   assert(_load_origin != NULL, "");
467   JavaThread* current = JavaThread::current();
468   _class_loader = Handle(current, _load_origin->class_loader());
469   _protection_domain = Handle(current, _load_origin->protection_domain());
470 }
471 
472 Klass* ResolvingSignatureStream::as_klass_if_loaded(TRAPS) {
473   Klass* klass = as_klass(CachedOrNull, THREAD);
474   // SD::find does not trigger loading, so there should be no throws
475   // Still, bad things can happen, so we CHECK_NULL and ask callers
476   // to do likewise.
477   if (HAS_PENDING_EXCEPTION) {
478     CLEAR_PENDING_EXCEPTION;
479   }
480   return klass;
481 }
482 
483 #ifdef ASSERT
484 
485 extern bool signature_constants_sane(); // called from basic_types_init()
486 
487 bool signature_constants_sane() {
488   // for the lookup table, test every 8-bit code point, and then some:
489   for (int i = -256; i <= 256; i++) {
490     int btcode = 0;
491     switch (i) {
492 #define EACH_SIG(ch, bt, ignore) \
493     case ch: { btcode = bt; break; }
494     SIGNATURE_TYPES_DO(EACH_SIG, ignore)
495 #undef EACH_SIG
496     }
497     int btc = decode_signature_char(i);
498     assert(btc == btcode, "misconfigured table: %d => %d not %d", i, btc, btcode);
499   }
500   return true;
501 }
502 
503 bool SignatureVerifier::is_valid_method_signature(Symbol* sig) {
504   const char* method_sig = (const char*)sig->bytes();
505   ssize_t len = sig->utf8_length();
506   ssize_t index = 0;
507   if (method_sig != NULL && len > 1 && method_sig[index] == JVM_SIGNATURE_FUNC) {
508     ++index;
509     while (index < len && method_sig[index] != JVM_SIGNATURE_ENDFUNC) {
510       ssize_t res = is_valid_type(&method_sig[index], len - index);
511       if (res == -1) {
512         return false;
513       } else {
514         index += res;
515       }
516     }
517     if (index < len && method_sig[index] == JVM_SIGNATURE_ENDFUNC) {
518       // check the return type
519       ++index;
520       return (is_valid_type(&method_sig[index], len - index) == (len - index));
521     }
522   }
523   return false;
524 }
525 
526 bool SignatureVerifier::is_valid_type_signature(Symbol* sig) {
527   const char* type_sig = (const char*)sig->bytes();
528   ssize_t len = sig->utf8_length();
529   return (type_sig != NULL && len >= 1 &&
530           (is_valid_type(type_sig, len) == len));
531 }
532 
533 // Checks to see if the type (not to go beyond 'limit') refers to a valid type.
534 // Returns -1 if it is not, or the index of the next character that is not part
535 // of the type.  The type encoding may end before 'limit' and that's ok.
536 ssize_t SignatureVerifier::is_valid_type(const char* type, ssize_t limit) {
537   ssize_t index = 0;
538 
539   // Iterate over any number of array dimensions
540   while (index < limit && type[index] == JVM_SIGNATURE_ARRAY) ++index;
541   if (index >= limit) {
542     return -1;
543   }
544   switch (type[index]) {
545     case JVM_SIGNATURE_BYTE:
546     case JVM_SIGNATURE_CHAR:
547     case JVM_SIGNATURE_FLOAT:
548     case JVM_SIGNATURE_DOUBLE:
549     case JVM_SIGNATURE_INT:
550     case JVM_SIGNATURE_LONG:
551     case JVM_SIGNATURE_SHORT:
552     case JVM_SIGNATURE_BOOLEAN:
553     case JVM_SIGNATURE_VOID:
554       return index + 1;
555     case JVM_SIGNATURE_CLASS:
556       for (index = index + 1; index < limit; ++index) {
557         char c = type[index];
558         switch (c) {
559           case JVM_SIGNATURE_ENDCLASS:
560             return index + 1;
561           case '\0': case JVM_SIGNATURE_DOT: case JVM_SIGNATURE_ARRAY:
562             return -1;
563           default: ; // fall through
564         }
565       }
566       // fall through
567     default: ; // fall through
568   }
569   return -1;
570 }
571 
572 #endif // ASSERT