1 /*
  2  * Copyright (c) 1997, 2023, 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 "asm/assembler.hpp"
 27 #include "classfile/symbolTable.hpp"
 28 #include "classfile/systemDictionary.hpp"
 29 #include "classfile/vmSymbols.hpp"
 30 #include "memory/oopFactory.hpp"
 31 #include "memory/resourceArea.hpp"
 32 #include "memory/universe.hpp"
 33 #include "oops/instanceKlass.hpp"
 34 #include "oops/klass.inline.hpp"
 35 #include "oops/oop.inline.hpp"
 36 #include "oops/symbol.hpp"
 37 #include "oops/typeArrayKlass.hpp"
 38 #include "oops/inlineKlass.inline.hpp"
 39 #include "runtime/fieldDescriptor.inline.hpp"
 40 #include "runtime/handles.inline.hpp"
 41 #include "runtime/interfaceSupport.inline.hpp"
 42 #include "runtime/safepointVerifiers.hpp"
 43 #include "runtime/sharedRuntime.hpp"
 44 #include "runtime/signature.hpp"
 45 #include "runtime/sharedRuntime.hpp"
 46 
 47 // Implementation of SignatureIterator
 48 
 49 // Signature syntax:
 50 //
 51 // Signature  = "(" {Parameter} ")" ReturnType.
 52 // Parameter  = FieldType.
 53 // ReturnType = FieldType | "V".
 54 // FieldType  = "B" | "C" | "D" | "F" | "I" | "J" | "S" | "Z" | "L" ClassName ";" | "Q" ValueClassName ";" | "[" FieldType.
 55 // ClassName  = string.
 56 
 57 // The ClassName string can be any JVM-style UTF8 string except:
 58 //  - an empty string (the empty string is never a name of any kind)
 59 //  - a string which begins or ends with slash '/' (the package separator)
 60 //  - a string which contains adjacent slashes '//' (no empty package names)
 61 //  - a string which contains a semicolon ';' (the end-delimiter)
 62 //  - a string which contains a left bracket '[' (the array marker)
 63 //  - a string which contains a dot '.' (the external package separator)
 64 //
 65 // Other "meta-looking" characters, such as '(' and '<' and '+',
 66 // are perfectly legitimate within a class name, for the JVM.
 67 // Class names which contain double slashes ('a//b') and non-initial
 68 // brackets ('a[b]') are reserved for possible enrichment of the
 69 // type language.
 70 
 71 void SignatureIterator::set_fingerprint(fingerprint_t fingerprint) {
 72   if (!fp_is_valid(fingerprint)) {
 73     _fingerprint = fingerprint;
 74     _return_type = T_ILLEGAL;
 75   } else if (fingerprint != _fingerprint) {
 76     assert(_fingerprint == zero_fingerprint(), "consistent fingerprint values");
 77     _fingerprint = fingerprint;
 78     _return_type = fp_return_type(fingerprint);
 79   }
 80 }
 81 
 82 BasicType SignatureIterator::return_type() {
 83   if (_return_type == T_ILLEGAL) {
 84     SignatureStream ss(_signature);
 85     ss.skip_to_return_type();
 86     _return_type = ss.type();
 87     assert(_return_type != T_ILLEGAL, "illegal return type");
 88   }
 89   return _return_type;
 90 }
 91 
 92 bool SignatureIterator::fp_is_valid_type(BasicType type, bool for_return_type) {
 93   assert(type != (BasicType)fp_parameters_done, "fingerprint is incorrectly at done");
 94   assert(((int)type & ~fp_parameter_feature_mask) == 0, "fingerprint feature mask yielded non-zero value");
 95   return (is_java_primitive(type) ||
 96           is_reference_type(type) ||
 97           (for_return_type && type == T_VOID));
 98 }
 99 
100 ArgumentSizeComputer::ArgumentSizeComputer(Symbol* signature)
101   : SignatureIterator(signature)
102 {
103   _size = 0;
104   do_parameters_on(this);  // non-virtual template execution
105 }
106 
107 ArgumentCount::ArgumentCount(Symbol* signature)
108   : SignatureIterator(signature)
109 {
110   _size = 0;
111   do_parameters_on(this);  // non-virtual template execution
112 }
113 
114 ReferenceArgumentCount::ReferenceArgumentCount(Symbol* signature)
115   : SignatureIterator(signature)
116 {
117   _refs = 0;
118   do_parameters_on(this);  // non-virtual template execution
119 }
120 
121 #if !defined(_LP64) || defined(ZERO) || defined(ASSERT)
122 static int compute_num_stack_arg_slots(Symbol* signature, int sizeargs, bool is_static) {
123   ResourceMark rm;
124   BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
125   VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
126 
127   int sig_index = 0;
128   if (!is_static) {
129     sig_bt[sig_index++] = T_OBJECT; // 'this'
130   }
131   for (SignatureStream ss(signature); !ss.at_return_type(); ss.next()) {
132     BasicType t = ss.type();
133     assert(type2size[t] == 1 || type2size[t] == 2, "size is 1 or 2");
134     sig_bt[sig_index++] = t;
135     if (type2size[t] == 2) {
136       sig_bt[sig_index++] = T_VOID;
137     }
138   }
139   assert(sig_index == sizeargs, "sig_index: %d sizeargs: %d", sig_index, sizeargs);
140 
141   return SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);
142 }
143 #endif
144 
145 void Fingerprinter::compute_fingerprint_and_return_type(bool static_flag) {
146   // See if we fingerprinted this method already
147   if (_method != nullptr) {
148     assert(!static_flag, "must not be passed by caller");
149     static_flag = _method->is_static();
150     _fingerprint = _method->constMethod()->fingerprint();
151 
152     if (_fingerprint != zero_fingerprint()) {
153       _return_type = _method->result_type();
154       assert(is_java_type(_return_type), "return type must be a java type");
155       return;
156     }
157 
158     if (_method->size_of_parameters() > fp_max_size_of_parameters) {
159       _fingerprint = overflow_fingerprint();
160       _method->constMethod()->set_fingerprint(_fingerprint);
161       // as long as we are here compute the return type:
162       _return_type = ResultTypeFinder(_method->signature()).type();
163       assert(is_java_type(_return_type), "return type must be a java type");
164       return;
165     }
166   }
167 
168   // Note:  This will always take the slow path, since _fp==zero_fp.
169   initialize_accumulator();
170   initialize_calling_convention(static_flag);
171   do_parameters_on(this);
172   assert(fp_is_valid_type(_return_type, true), "bad result type");
173 
174   // Fill in the return type and static bits:
175   _accumulator |= _return_type << fp_static_feature_size;
176   if (static_flag) {
177     _accumulator |= fp_is_static_bit;
178   } else {
179     _param_size += 1;  // this is the convention for Method::compute_size_of_parameters
180   }
181 
182 #if defined(_LP64) && !defined(ZERO)
183   _stack_arg_slots = align_up(_stack_arg_slots, 2);
184 #ifdef ASSERT
185   int dbg_stack_arg_slots = compute_num_stack_arg_slots(_signature, _param_size, static_flag);
186   assert(_stack_arg_slots == dbg_stack_arg_slots, "fingerprinter: %d full: %d", _stack_arg_slots, dbg_stack_arg_slots);
187 #endif
188 #else
189   // Fallback: computed _stack_arg_slots is unreliable, compute directly.
190   _stack_arg_slots = compute_num_stack_arg_slots(_signature, _param_size, static_flag);
191 #endif
192 
193   // Detect overflow.  (We counted _param_size correctly.)
194   if (_method == nullptr && _param_size > fp_max_size_of_parameters) {
195     // We did a one-pass computation of argument size, return type,
196     // and fingerprint.
197     _fingerprint = overflow_fingerprint();
198     return;
199   }
200 
201   assert(_shift_count < BitsPerLong,
202          "shift count overflow %d (%d vs. %d): %s",
203          _shift_count, _param_size, fp_max_size_of_parameters,
204          _signature->as_C_string());
205   assert((_accumulator >> _shift_count) == fp_parameters_done, "must be zero");
206 
207   // This is the result, along with _return_type:
208   _fingerprint = _accumulator;
209 
210   // Cache the result on the method itself:
211   if (_method != nullptr) {
212     _method->constMethod()->set_fingerprint(_fingerprint);
213   }
214 }
215 
216 void Fingerprinter::initialize_calling_convention(bool static_flag) {
217   _int_args = 0;
218   _fp_args = 0;
219 
220   if (!static_flag) { // `this` takes up an int register
221     _int_args++;
222   }
223 }
224 
225 void Fingerprinter::do_type_calling_convention(BasicType type) {
226   // We compute the number of slots for stack-passed arguments in compiled calls.
227   // TODO: SharedRuntime::java_calling_convention is the shared code that knows all details
228   // about the platform-specific calling conventions. This method tries to compute the stack
229   // args number... poorly, at least for 32-bit ports and for zero. Current code has the fallback
230   // that recomputes the stack args number from SharedRuntime::java_calling_convention.
231 #if defined(_LP64) && !defined(ZERO)
232   switch (type) {
233   case T_VOID:
234     break;
235   case T_BOOLEAN:
236   case T_CHAR:
237   case T_BYTE:
238   case T_SHORT:
239   case T_INT:
240 #if defined(PPC64) || defined(S390)
241     if (_int_args < Argument::n_int_register_parameters_j) {
242       _int_args++;
243     } else {
244       _stack_arg_slots += 1;
245     }
246     break;
247 #endif // defined(PPC64) || defined(S390)
248   case T_LONG:
249   case T_OBJECT:
250   case T_ARRAY:
251   case T_ADDRESS:
252     if (_int_args < Argument::n_int_register_parameters_j) {
253       _int_args++;
254     } else {
255       PPC64_ONLY(_stack_arg_slots = align_up(_stack_arg_slots, 2));
256       S390_ONLY(_stack_arg_slots = align_up(_stack_arg_slots, 2));
257       _stack_arg_slots += 2;
258     }
259     break;
260   case T_FLOAT:
261 #if defined(PPC64) || defined(S390)
262     if (_fp_args < Argument::n_float_register_parameters_j) {
263       _fp_args++;
264     } else {
265       _stack_arg_slots += 1;
266     }
267     break;
268 #endif // defined(PPC64) || defined(S390)
269   case T_DOUBLE:
270     if (_fp_args < Argument::n_float_register_parameters_j) {
271       _fp_args++;
272     } else {
273       PPC64_ONLY(_stack_arg_slots = align_up(_stack_arg_slots, 2));
274       S390_ONLY(_stack_arg_slots = align_up(_stack_arg_slots, 2));
275       _stack_arg_slots += 2;
276     }
277     break;
278   default:
279     ShouldNotReachHere();
280     break;
281   }
282 #endif
283 }
284 
285 // Implementation of SignatureStream
286 
287 static inline BasicType decode_signature_char(int ch) {
288   switch (ch) {
289 #define EACH_SIG(ch, bt, ignore) \
290     case ch: return bt;
291     SIGNATURE_TYPES_DO(EACH_SIG, ignore)
292 #undef EACH_SIG
293   }
294   return (BasicType)0;
295 }
296 
297 SignatureStream::SignatureStream(const Symbol* signature,
298                                  bool is_method) {
299   assert(!is_method || signature->starts_with(JVM_SIGNATURE_FUNC),
300          "method signature required");
301   _signature = signature;
302   _limit = signature->utf8_length();
303   int oz = (is_method ? _s_method : _s_field);
304   _state = oz;
305   _begin = _end = oz; // skip first '(' in method signatures
306   _array_prefix = 0;  // just for definiteness
307 
308   // assigning java/lang/Object to _previous_name means we can
309   // avoid a number of null checks in the parser
310   _previous_name = vmSymbols::java_lang_Object();
311   _names = nullptr;
312   next();
313 }
314 
315 SignatureStream::~SignatureStream() {
316   if (_previous_name == vmSymbols::java_lang_Object()) {
317     // no names were created
318     assert(_names == nullptr, "_names unexpectedly created");
319     return;
320   }
321 
322   // decrement refcount for names created during signature parsing
323   _previous_name->decrement_refcount();
324   if (_names != nullptr) {
325     for (int i = 0; i < _names->length(); i++) {
326       _names->at(i)->decrement_refcount();
327     }
328   }
329 }
330 
331 inline int SignatureStream::scan_type(BasicType type) {
332   const u1* base = _signature->bytes();
333   int end = _end;
334   int limit = _limit;
335   const u1* tem;
336   switch (type) {
337   case T_OBJECT:
338     tem = (const u1*) memchr(&base[end], JVM_SIGNATURE_ENDCLASS, limit - end);
339     return (tem == nullptr ? limit : pointer_delta_as_int(tem + 1, base));
340 
341   case T_ARRAY:
342     while ((end < limit) && ((char)base[end] == JVM_SIGNATURE_ARRAY)) { end++; }
343     // If we discovered only the string of '[', this means something is wrong.
344     if (end >= limit) {
345       assert(false, "Invalid type detected");
346       return limit;
347     }
348     _array_prefix = end - _end;  // number of '[' chars just skipped
349     if (Signature::has_envelope(base[end])) {
350       tem = (const u1 *) memchr(&base[end], JVM_SIGNATURE_ENDCLASS, limit - end);
351       return (tem == nullptr ? limit : pointer_delta_as_int(tem + 1, base));
352     }
353     // Skipping over a single character for a primitive type.
354     assert(is_java_primitive(decode_signature_char(base[end])), "only primitives expected");
355     return end + 1;
356 
357   default:
358     // Skipping over a single character for a primitive type (or void).
359     assert(!is_reference_type(type), "only primitives or void expected");
360     return end + 1;
361   }
362 }
363 
364 void SignatureStream::next() {
365   const Symbol* sig = _signature;
366   int len = _limit;
367   if (_end >= len) { set_done(); return; }
368   _begin = _end;
369   int ch = sig->char_at(_begin);
370   if (ch == JVM_SIGNATURE_ENDFUNC) {
371     assert(_state == _s_method, "must be in method");
372     _state = _s_method_return;
373     _begin = ++_end;
374     if (_end >= len) { set_done(); return; }
375     ch = sig->char_at(_begin);
376   }
377   BasicType bt = decode_signature_char(ch);
378   assert(ch == type2char(bt), "bad signature char %c/%d", ch, ch);
379   _type = bt;
380   _end = scan_type(bt);
381 }
382 
383 int SignatureStream::skip_whole_array_prefix() {
384   assert(_type == T_ARRAY, "must be");
385 
386   // we are stripping all levels of T_ARRAY,
387   // so we must decode the next character
388   int whole_array_prefix = _array_prefix;
389   int new_begin = _begin + whole_array_prefix;
390   _begin = new_begin;
391   int ch = _signature->char_at(new_begin);
392   BasicType bt = decode_signature_char(ch);
393   assert(ch == type2char(bt), "bad signature char %c/%d", ch, ch);
394   _type = bt;
395   assert(bt != T_VOID && bt != T_ARRAY, "bad signature type");
396   // Don't bother to re-scan, since it won't change the value of _end.
397   return whole_array_prefix;
398 }
399 
400 bool Signature::is_valid_array_signature(const Symbol* sig) {
401   assert(sig->utf8_length() > 1, "this should already have been checked");
402   assert(sig->char_at(0) == JVM_SIGNATURE_ARRAY, "this should already have been checked");
403   // The first character is already checked
404   int i = 1;
405   int len = sig->utf8_length();
406   // First skip all '['s
407   while(i < len - 1 && sig->char_at(i) == JVM_SIGNATURE_ARRAY) i++;
408 
409   // Check type
410   switch(sig->char_at(i)) {
411   case JVM_SIGNATURE_BYTE:
412   case JVM_SIGNATURE_CHAR:
413   case JVM_SIGNATURE_DOUBLE:
414   case JVM_SIGNATURE_FLOAT:
415   case JVM_SIGNATURE_INT:
416   case JVM_SIGNATURE_LONG:
417   case JVM_SIGNATURE_SHORT:
418   case JVM_SIGNATURE_BOOLEAN:
419     // If it is an array, the type is the last character
420     return (i + 1 == len);
421   case JVM_SIGNATURE_CLASS:
422     // If it is an object, the last character must be a ';'
423     return sig->char_at(len - 1) == JVM_SIGNATURE_ENDCLASS;
424   }
425   return false;
426 }
427 
428 BasicType Signature::basic_type(int ch) {
429   BasicType btcode = decode_signature_char(ch);
430   if (btcode == 0)  return T_ILLEGAL;
431   return btcode;
432 }
433 
434 Symbol* Signature::strip_envelope(const Symbol* signature) {
435   assert(has_envelope(signature), "precondition");
436   return SymbolTable::new_symbol((char*) signature->bytes() + 1,
437                                  signature->utf8_length() - 2);
438 }
439 
440 static const int jl_len = 10, object_len = 6, jl_object_len = jl_len + object_len;
441 static const char jl_str[] = "java/lang/";
442 
443 #ifdef ASSERT
444 static bool signature_symbols_sane() {
445   static bool done;
446   if (done)  return true;
447   done = true;
448   // test some tense code that looks for common symbol names:
449   assert(vmSymbols::java_lang_Object()->utf8_length() == jl_object_len &&
450          vmSymbols::java_lang_Object()->starts_with(jl_str, jl_len) &&
451          vmSymbols::java_lang_Object()->ends_with("Object", object_len) &&
452          vmSymbols::java_lang_Object()->is_permanent() &&
453          vmSymbols::java_lang_String()->utf8_length() == jl_object_len &&
454          vmSymbols::java_lang_String()->starts_with(jl_str, jl_len) &&
455          vmSymbols::java_lang_String()->ends_with("String", object_len) &&
456          vmSymbols::java_lang_String()->is_permanent(),
457          "sanity");
458   return true;
459 }
460 #endif //ASSERT
461 
462 // returns a symbol; the caller is responsible for decrementing it
463 Symbol* SignatureStream::find_symbol() {
464   // Create a symbol from for string _begin _end
465   int begin = raw_symbol_begin();
466   int end   = raw_symbol_end();
467 
468   const char* symbol_chars = (const char*)_signature->base() + begin;
469   int len = end - begin;
470 
471   // Quick check for common symbols in signatures
472   assert(signature_symbols_sane(), "incorrect signature sanity check");
473   if (len == jl_object_len &&
474       memcmp(symbol_chars, jl_str, jl_len) == 0) {
475     if (memcmp("String", symbol_chars + jl_len, object_len) == 0) {
476       return vmSymbols::java_lang_String();
477     } else if (memcmp("Object", symbol_chars + jl_len, object_len) == 0) {
478       return vmSymbols::java_lang_Object();
479     }
480   }
481 
482   Symbol* name = _previous_name;
483   if (name->equals(symbol_chars, len)) {
484     return name;
485   }
486 
487   // Save names for cleaning up reference count at the end of
488   // SignatureStream scope.
489   name = SymbolTable::new_symbol(symbol_chars, len);
490 
491   // Only allocate the GrowableArray for the _names buffer if more than
492   // one name is being processed in the signature.
493   if (!_previous_name->is_permanent()) {
494     if (_names == nullptr) {
495       _names = new GrowableArray<Symbol*>(10);
496     }
497     _names->push(_previous_name);
498   }
499   _previous_name = name;
500   return name;
501 }
502 
503 InlineKlass* SignatureStream::as_inline_klass(InstanceKlass* holder) {
504   ThreadInVMfromUnknown tiv;
505   JavaThread* THREAD = JavaThread::current();
506   HandleMark hm(THREAD);
507   Handle class_loader(THREAD, holder->class_loader());
508   Handle protection_domain(THREAD, holder->protection_domain());
509   Klass* k = as_klass(class_loader, protection_domain, SignatureStream::CachedOrNull, THREAD);
510   assert(!HAS_PENDING_EXCEPTION, "Should never throw");
511   if (k != nullptr && k->is_inline_klass()) {
512     return InlineKlass::cast(k);
513   } else {
514     return nullptr;
515   }
516 }
517 
518 Klass* SignatureStream::as_klass(Handle class_loader, Handle protection_domain,
519                                  FailureMode failure_mode, TRAPS) {
520   if (!is_reference()) {
521     return nullptr;
522   }
523   Symbol* name = as_symbol();
524   Klass* k = nullptr;
525   if (failure_mode == ReturnNull) {
526     // Note:  SD::resolve_or_null returns null for most failure modes,
527     // but not all.  Circularity errors, invalid PDs, etc., throw.
528     k = SystemDictionary::resolve_or_null(name, class_loader, protection_domain, CHECK_NULL);
529   } else if (failure_mode == CachedOrNull) {
530     NoSafepointVerifier nsv;  // no loading, now, we mean it!
531     assert(!HAS_PENDING_EXCEPTION, "");
532     k = SystemDictionary::find_instance_klass(THREAD, name, class_loader, protection_domain);
533     // SD::find does not trigger loading, so there should be no throws
534     // Still, bad things can happen, so we CHECK_NULL and ask callers
535     // to do likewise.
536     return k;
537   } else {
538     // The only remaining failure mode is NCDFError.
539     // The test here allows for an additional mode CNFException
540     // if callers need to request the reflective error instead.
541     bool throw_error = (failure_mode == NCDFError);
542     k = SystemDictionary::resolve_or_fail(name, class_loader, protection_domain, throw_error, CHECK_NULL);
543   }
544 
545   return k;
546 }
547 
548 oop SignatureStream::as_java_mirror(Handle class_loader, Handle protection_domain,
549                                     FailureMode failure_mode, TRAPS) {
550   if (!is_reference()) {
551     return Universe::java_mirror(type());
552   }
553   Klass* klass = as_klass(class_loader, protection_domain, failure_mode, CHECK_NULL);
554   if (klass == nullptr) {
555     return nullptr;
556   }
557   return klass->java_mirror();
558 }
559 
560 void SignatureStream::skip_to_return_type() {
561   while (!at_return_type()) {
562     next();
563   }
564 }
565 
566 ResolvingSignatureStream::ResolvingSignatureStream(Symbol* signature,
567                                                    Handle class_loader,
568                                                    Handle protection_domain,
569                                                    bool is_method)
570   : SignatureStream(signature, is_method),
571     _class_loader(class_loader), _protection_domain(protection_domain)
572 {
573   initialize_load_origin(nullptr);
574 }
575 
576 ResolvingSignatureStream::ResolvingSignatureStream(Symbol* signature, Klass* load_origin, bool is_method)
577   : SignatureStream(signature, is_method)
578 {
579   assert(load_origin != nullptr, "");
580   initialize_load_origin(load_origin);
581 }
582 
583 ResolvingSignatureStream::ResolvingSignatureStream(const Method* method)
584   : SignatureStream(method->signature(), true)
585 {
586   initialize_load_origin(method->method_holder());
587 }
588 
589 void ResolvingSignatureStream::cache_handles() {
590   assert(_load_origin != nullptr, "");
591   JavaThread* current = JavaThread::current();
592   _class_loader = Handle(current, _load_origin->class_loader());
593   _protection_domain = Handle(current, _load_origin->protection_domain());
594 }
595 
596 #ifdef ASSERT
597 extern bool signature_constants_sane(); // called from basic_types_init()
598 
599 bool signature_constants_sane() {
600   // for the lookup table, test every 8-bit code point, and then some:
601   for (int i = -256; i <= 256; i++) {
602     int btcode = 0;
603     switch (i) {
604 #define EACH_SIG(ch, bt, ignore) \
605     case ch: { btcode = bt; break; }
606     SIGNATURE_TYPES_DO(EACH_SIG, ignore)
607 #undef EACH_SIG
608     }
609     int btc = decode_signature_char(i);
610     assert(btc == btcode, "misconfigured table: %d => %d not %d", i, btc, btcode);
611   }
612   return true;
613 }
614 
615 bool SignatureVerifier::is_valid_method_signature(const Symbol* sig) {
616   const char* method_sig = (const char*)sig->bytes();
617   ssize_t len = sig->utf8_length();
618   ssize_t index = 0;
619   if (method_sig != nullptr && len > 1 && method_sig[index] == JVM_SIGNATURE_FUNC) {
620     ++index;
621     while (index < len && method_sig[index] != JVM_SIGNATURE_ENDFUNC) {
622       ssize_t res = is_valid_type(&method_sig[index], len - index);
623       if (res == -1) {
624         return false;
625       } else {
626         index += res;
627       }
628     }
629     if (index < len && method_sig[index] == JVM_SIGNATURE_ENDFUNC) {
630       // check the return type
631       ++index;
632       return (is_valid_type(&method_sig[index], len - index) == (len - index));
633     }
634   }
635   return false;
636 }
637 
638 bool SignatureVerifier::is_valid_type_signature(const Symbol* sig) {
639   const char* type_sig = (const char*)sig->bytes();
640   ssize_t len = sig->utf8_length();
641   return (type_sig != nullptr && len >= 1 &&
642           (is_valid_type(type_sig, len) == len));
643 }
644 
645 // Checks to see if the type (not to go beyond 'limit') refers to a valid type.
646 // Returns -1 if it is not, or the index of the next character that is not part
647 // of the type.  The type encoding may end before 'limit' and that's ok.
648 ssize_t SignatureVerifier::is_valid_type(const char* type, ssize_t limit) {
649   ssize_t index = 0;
650 
651   // Iterate over any number of array dimensions
652   while (index < limit && type[index] == JVM_SIGNATURE_ARRAY) ++index;
653   if (index >= limit) {
654     return -1;
655   }
656   switch (type[index]) {
657     case JVM_SIGNATURE_BYTE:
658     case JVM_SIGNATURE_CHAR:
659     case JVM_SIGNATURE_FLOAT:
660     case JVM_SIGNATURE_DOUBLE:
661     case JVM_SIGNATURE_INT:
662     case JVM_SIGNATURE_LONG:
663     case JVM_SIGNATURE_SHORT:
664     case JVM_SIGNATURE_BOOLEAN:
665     case JVM_SIGNATURE_VOID:
666       return index + 1;
667     case JVM_SIGNATURE_CLASS:
668       for (index = index + 1; index < limit; ++index) {
669         char c = type[index];
670         switch (c) {
671           case JVM_SIGNATURE_ENDCLASS:
672             return index + 1;
673           case '\0': case JVM_SIGNATURE_DOT: case JVM_SIGNATURE_ARRAY:
674             return -1;
675           default: ; // fall through
676         }
677       }
678       // fall through
679     default: ; // fall through
680   }
681   return -1;
682 }
683 
684 #endif // ASSERT
685 
686 // Adds an argument to the signature
687 void SigEntry::add_entry(GrowableArray<SigEntry>* sig, BasicType bt, Symbol* symbol, int offset) {
688   sig->append(SigEntry(bt, offset, symbol));
689   if (bt == T_LONG || bt == T_DOUBLE) {
690     sig->append(SigEntry(T_VOID, offset, symbol)); // Longs and doubles take two stack slots
691   }
692 }
693 
694 // Returns true if the argument at index 'i' is not an inline type delimiter
695 bool SigEntry::skip_value_delimiters(const GrowableArray<SigEntry>* sig, int i) {
696   return (sig->at(i)._bt != T_METADATA &&
697           (sig->at(i)._bt != T_VOID || sig->at(i-1)._bt == T_LONG || sig->at(i-1)._bt == T_DOUBLE));
698 }
699 
700 // Fill basic type array from signature array
701 int SigEntry::fill_sig_bt(const GrowableArray<SigEntry>* sig, BasicType* sig_bt) {
702   int count = 0;
703   for (int i = 0; i < sig->length(); i++) {
704     if (skip_value_delimiters(sig, i)) {
705       sig_bt[count++] = sig->at(i)._bt;
706     }
707   }
708   return count;
709 }
710 
711 // Create a temporary symbol from the signature array
712 TempNewSymbol SigEntry::create_symbol(const GrowableArray<SigEntry>* sig) {
713   ResourceMark rm;
714   int length = sig->length();
715   char* sig_str = NEW_RESOURCE_ARRAY(char, 2*length + 3);
716   int idx = 0;
717   sig_str[idx++] = '(';
718   for (int i = 0; i < length; i++) {
719     BasicType bt = sig->at(i)._bt;
720     if (bt == T_METADATA || bt == T_VOID) {
721       // Ignore
722     } else {
723       if (bt == T_ARRAY) {
724         bt = T_OBJECT; // We don't know the element type, treat as Object
725       }
726       sig_str[idx++] = type2char(bt);
727       if (bt == T_OBJECT) {
728         sig_str[idx++] = ';';
729       }
730     }
731   }
732   sig_str[idx++] = ')';
733   // Add a dummy return type. It won't be used but SignatureStream needs it.
734   sig_str[idx++] = 'V';
735   sig_str[idx++] = '\0';
736   return SymbolTable::new_symbol(sig_str);
737 }