1 /*
  2  * Copyright (c) 2015, 2025, 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 "cds/aotConstantPoolResolver.hpp"
 26 #include "cds/archiveUtils.hpp"
 27 #include "cds/classListParser.hpp"
 28 #include "cds/lambdaFormInvokers.hpp"
 29 #include "cds/lambdaProxyClassDictionary.hpp"
 30 #include "cds/metaspaceShared.hpp"
 31 #include "cds/unregisteredClasses.hpp"
 32 #include "classfile/classLoaderExt.hpp"
 33 #include "classfile/javaClasses.inline.hpp"
 34 #include "classfile/symbolTable.hpp"
 35 #include "classfile/systemDictionary.hpp"
 36 #include "classfile/systemDictionaryShared.hpp"
 37 #include "classfile/vmClasses.hpp"
 38 #include "classfile/vmSymbols.hpp"
 39 #include "interpreter/bytecode.hpp"
 40 #include "interpreter/bytecodeStream.hpp"
 41 #include "interpreter/linkResolver.hpp"
 42 #include "jimage.hpp"
 43 #include "jvm.h"
 44 #include "logging/log.hpp"
 45 #include "logging/logTag.hpp"
 46 #include "memory/oopFactory.hpp"
 47 #include "memory/resourceArea.hpp"
 48 #include "oops/constantPool.inline.hpp"
 49 #include "runtime/atomic.hpp"
 50 #include "runtime/globals_extension.hpp"
 51 #include "runtime/handles.inline.hpp"
 52 #include "runtime/java.hpp"
 53 #include "runtime/javaCalls.hpp"
 54 #include "utilities/defaultStream.hpp"
 55 #include "utilities/macros.hpp"
 56 #include "utilities/utf8.hpp"
 57 
 58 const char* ClassListParser::CONSTANT_POOL_TAG = "@cp";
 59 const char* ClassListParser::LAMBDA_FORM_TAG = "@lambda-form-invoker";
 60 const char* ClassListParser::LAMBDA_PROXY_TAG = "@lambda-proxy";
 61 
 62 volatile Thread* ClassListParser::_parsing_thread = nullptr;
 63 ClassListParser* ClassListParser::_instance = nullptr;
 64 
 65 ClassListParser::ClassListParser(const char* file, ParseMode parse_mode) :
 66     _classlist_file(file),
 67     _id2klass_table(INITIAL_TABLE_SIZE, MAX_TABLE_SIZE),
 68     _file_input(do_open(file), /* need_close=*/true),
 69     _input_stream(&_file_input),
 70     _parse_mode(parse_mode) {
 71   log_info(cds)("Parsing %s%s", file,
 72                 parse_lambda_forms_invokers_only() ? " (lambda form invokers only)" : "");
 73   if (!_file_input.is_open()) {
 74     char reason[JVM_MAXPATHLEN];
 75     os::lasterror(reason, JVM_MAXPATHLEN);
 76     vm_exit_during_initialization(err_msg("Loading %s %s failed",
 77                                           FLAG_IS_DEFAULT(AOTConfiguration) ?
 78                                           "classlist" : "AOTConfiguration file",
 79                                           file),
 80                                   reason);
 81   }
 82   _token = _line = nullptr;
 83   _interfaces = new (mtClass) GrowableArray<int>(10, mtClass);
 84   _indy_items = new (mtClass) GrowableArray<const char*>(9, mtClass);
 85 
 86   // _instance should only be accessed by the thread that created _instance.
 87   assert(_instance == nullptr, "must be singleton");
 88   _instance = this;
 89   Atomic::store(&_parsing_thread, Thread::current());
 90 }
 91 
 92 FILE* ClassListParser::do_open(const char* file) {
 93   // Use os::open() because neither fopen() nor os::fopen()
 94   // can handle long path name on Windows. (See JDK-8216184)
 95   int fd = os::open(file, O_RDONLY, S_IREAD);
 96   FILE* fp = nullptr;
 97   if (fd != -1) {
 98     // Obtain a FILE* from the file descriptor so that _input_stream
 99     // can be used in ClassListParser::parse()
100     fp = os::fdopen(fd, "r");
101   }
102   return fp;
103 }
104 
105 bool ClassListParser::is_parsing_thread() {
106   return Atomic::load(&_parsing_thread) == Thread::current();
107 }
108 
109 ClassListParser::~ClassListParser() {
110   Atomic::store(&_parsing_thread, (Thread*)nullptr);
111   delete _indy_items;
112   delete _interfaces;
113   _instance = nullptr;
114 }
115 
116 void ClassListParser::parse_classlist(const char* classlist_path, ParseMode parse_mode, TRAPS) {
117   UnregisteredClasses::initialize(CHECK);
118   ClassListParser parser(classlist_path, parse_mode);
119   parser.parse(THREAD);
120 }
121 
122 void ClassListParser::parse(TRAPS) {
123   for (; !_input_stream.done(); _input_stream.next()) {
124     _line = _input_stream.current_line();
125     clean_up_input_line();
126 
127     // Each line in the classlist can be one of three forms:
128     if (_line[0] == '#') {
129       // A comment; ignore it
130     } else if (_line[0] == '@') {
131       // @xxx - a tag like @lambda-proxy, to be parsed by parse_at_tags()
132       parse_at_tags(CHECK);
133     } else {
134       // A class name, followed by optional attributes. E.g.
135       //   java/lang/String
136       //   java/lang/Object id: 1
137       //   my/pkg/TestClass id: 5 super: 1 interfaces: 3 4 source: foo.jar
138       parse_class_name_and_attributes(CHECK);
139     }
140   }
141 }
142 
143 void ClassListParser::parse_class_name_and_attributes(TRAPS) {
144   read_class_name_and_attributes();
145 
146   if (parse_lambda_forms_invokers_only()) {
147     return;
148   }
149 
150   check_class_name(_class_name);
151   TempNewSymbol class_name_symbol = SymbolTable::new_symbol(_class_name);
152   Klass* klass = load_current_class(class_name_symbol, THREAD);
153   if (HAS_PENDING_EXCEPTION) {
154     if (PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())) {
155       // If we have run out of memory, don't try to load the rest of the classes in
156       // the classlist. Throw an exception, which will terminate the dumping process.
157       return; // THROW
158     }
159 
160     ResourceMark rm(THREAD);
161     char* ex_msg = (char*)"";
162     oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
163     if (message != nullptr) {
164       ex_msg = java_lang_String::as_utf8_string(message);
165     }
166     log_warning(cds)("%s: %s", PENDING_EXCEPTION->klass()->external_name(), ex_msg);
167     // We might have an invalid class name or an bad class. Warn about it
168     // and keep going to the next line.
169     CLEAR_PENDING_EXCEPTION;
170     log_warning(cds)("Preload Warning: Cannot find %s", _class_name);
171     return;
172   }
173 
174   assert(klass != nullptr, "sanity");
175   if (log_is_enabled(Trace, cds)) {
176     ResourceMark rm(THREAD);
177     log_trace(cds)("Shared spaces preloaded: %s", klass->external_name());
178   }
179 
180   if (klass->is_instance_klass()) {
181     InstanceKlass* ik = InstanceKlass::cast(klass);
182 
183     // Link the class to cause the bytecodes to be rewritten and the
184     // cpcache to be created. The linking is done as soon as classes
185     // are loaded in order that the related data structures (klass and
186     // cpCache) are located together.
187     MetaspaceShared::try_link_class(THREAD, ik);
188   }
189 }
190 
191 void ClassListParser::clean_up_input_line() {
192   int len = (int)strlen(_line);
193   int i;
194   // Replace \t\r\n\f with ' '
195   for (i=0; i<len; i++) {
196     if (_line[i] == '\t' || _line[i] == '\r' || _line[i] == '\n' || _line[i] == '\f') {
197       _line[i] = ' ';
198     }
199   }
200 
201   // Remove trailing newline/space
202   while (len > 0) {
203     if (_line[len-1] == ' ') {
204       _line[len-1] = '\0';
205       len --;
206     } else {
207       break;
208     }
209   }
210   _line_len = len;
211 }
212 
213 void ClassListParser::read_class_name_and_attributes() {
214   _class_name = _line;
215   _id = _unspecified;
216   _super = _unspecified;
217   _interfaces->clear();
218   _source = nullptr;
219   _interfaces_specified = false;
220 
221   if ((_token = strchr(_line, ' ')) == nullptr) {
222     // No optional attributes are specified.
223     return;
224   }
225 
226   // Mark the end of the name, and go to the next input char
227   *_token++ = '\0';
228 
229   while (*_token) {
230     skip_whitespaces();
231 
232     if (parse_uint_option("id:", &_id)) {
233       continue;
234     } else if (parse_uint_option("super:", &_super)) {
235       check_already_loaded("Super class", _super);
236       continue;
237     } else if (skip_token("interfaces:")) {
238       int i;
239       while (try_parse_uint(&i)) {
240         check_already_loaded("Interface", i);
241         _interfaces->append(i);
242       }
243     } else if (skip_token("source:")) {
244       skip_whitespaces();
245       _source = _token;
246       char* s = strchr(_token, ' ');
247       if (s == nullptr) {
248         break; // end of input line
249       } else {
250         *s = '\0'; // mark the end of _source
251         _token = s+1;
252       }
253     } else {
254       error("Unknown input");
255     }
256   }
257 
258   // if src is specified
259   //     id super interfaces must all be specified
260   //     loader may be specified
261   // else
262   //     # the class is loaded from classpath
263   //     id may be specified
264   //     super, interfaces, loader must not be specified
265 }
266 
267 void ClassListParser::split_tokens_by_whitespace(int offset, GrowableArray<const char*>* items) {
268   int start = offset;
269   int end;
270   bool done = false;
271   while (!done) {
272     while (_line[start] == ' ' || _line[start] == '\t') start++;
273     end = start;
274     while (_line[end] && _line[end] != ' ' && _line[end] != '\t') end++;
275     if (_line[end] == '\0') {
276       done = true;
277     } else {
278       _line[end] = '\0';
279     }
280     items->append(_line + start);
281     start = ++end;
282   }
283 }
284 
285 int ClassListParser::split_at_tag_from_line() {
286   _token = _line;
287   char* ptr;
288   if ((ptr = strchr(_line, ' ')) == nullptr) {
289     error("Too few items following the @ tag \"%s\" line #%zu", _line, lineno());
290     return 0;
291   }
292   *ptr++ = '\0';
293   while (*ptr == ' ' || *ptr == '\t') ptr++;
294   return (int)(ptr - _line);
295 }
296 
297 void ClassListParser::parse_at_tags(TRAPS) {
298   assert(_line[0] == '@', "must be");
299   int offset = split_at_tag_from_line();
300   assert(offset > 0, "would have exited VM");
301 
302   if (strcmp(_token, LAMBDA_PROXY_TAG) == 0) {
303     _indy_items->clear();
304     split_tokens_by_whitespace(offset, _indy_items);
305     if (_indy_items->length() < 2) {
306       error("Line with @ tag has too few items \"%s\" line #%zu", _token, lineno());
307     }
308     if (!parse_lambda_forms_invokers_only()) {
309       _class_name = _indy_items->at(0);
310       check_class_name(_class_name);
311       TempNewSymbol class_name_symbol = SymbolTable::new_symbol(_class_name);
312       if (_indy_items->length() > 0) {
313         // The current line is "@lambda-proxy class_name". Load the proxy class.
314         resolve_indy(THREAD, class_name_symbol);
315       }
316     }
317   } else if (strcmp(_token, LAMBDA_FORM_TAG) == 0) {
318     LambdaFormInvokers::append(os::strdup((const char*)(_line + offset), mtInternal));
319   } else if (strcmp(_token, CONSTANT_POOL_TAG) == 0) {
320     _token = _line + offset;
321     parse_constant_pool_tag();
322   } else {
323     error("Invalid @ tag at the beginning of line \"%s\" line #%zu", _token, lineno());
324   }
325 }
326 
327 void ClassListParser::skip_whitespaces() {
328   while (*_token == ' ' || *_token == '\t') {
329     _token ++;
330   }
331 }
332 
333 void ClassListParser::skip_non_whitespaces() {
334   while (*_token && *_token != ' ' && *_token != '\t') {
335     _token ++;
336   }
337 }
338 
339 void ClassListParser::parse_int(int* value) {
340   skip_whitespaces();
341   if (sscanf(_token, "%i", value) == 1) {
342     skip_non_whitespaces();
343   } else {
344     error("Error: expected integer");
345   }
346 }
347 
348 void ClassListParser::parse_uint(int* value) {
349   parse_int(value);
350   if (*value < 0) {
351     error("Error: negative integers not allowed (%d)", *value);
352   }
353 }
354 
355 bool ClassListParser::try_parse_uint(int* value) {
356   skip_whitespaces();
357   if (sscanf(_token, "%i", value) == 1) {
358     skip_non_whitespaces();
359     return true;
360   }
361   return false;
362 }
363 
364 bool ClassListParser::skip_token(const char* option_name) {
365   size_t len = strlen(option_name);
366   if (strncmp(_token, option_name, len) == 0) {
367     _token += len;
368     return true;
369   } else {
370     return false;
371   }
372 }
373 
374 bool ClassListParser::parse_int_option(const char* option_name, int* value) {
375   if (skip_token(option_name)) {
376     if (*value != _unspecified) {
377       error("%s specified twice", option_name);
378     } else {
379       parse_int(value);
380       return true;
381     }
382   }
383   return false;
384 }
385 
386 bool ClassListParser::parse_uint_option(const char* option_name, int* value) {
387   if (skip_token(option_name)) {
388     if (*value != _unspecified) {
389       error("%s specified twice", option_name);
390     } else {
391       parse_uint(value);
392       return true;
393     }
394   }
395   return false;
396 }
397 
398 objArrayOop ClassListParser::get_specified_interfaces(TRAPS) {
399   const int n = _interfaces->length();
400   if (n == 0) {
401     return nullptr;
402   } else {
403     objArrayOop array = oopFactory::new_objArray(vmClasses::Class_klass(), n, CHECK_NULL);
404     for (int i = 0; i < n; i++) {
405       array->obj_at_put(i, lookup_class_by_id(_interfaces->at(i))->java_mirror());
406     }
407     return array;
408   }
409 }
410 
411 void ClassListParser::print_specified_interfaces() {
412   const int n = _interfaces->length();
413   jio_fprintf(defaultStream::error_stream(), "Currently specified interfaces[%d] = {\n", n);
414   for (int i=0; i<n; i++) {
415     InstanceKlass* k = lookup_class_by_id(_interfaces->at(i));
416     jio_fprintf(defaultStream::error_stream(), "  %4d = %s\n", _interfaces->at(i), k->name()->as_klass_external_name());
417   }
418   jio_fprintf(defaultStream::error_stream(), "}\n");
419 }
420 
421 void ClassListParser::print_actual_interfaces(InstanceKlass* ik) {
422   int n = ik->local_interfaces()->length();
423   jio_fprintf(defaultStream::error_stream(), "Actual interfaces[%d] = {\n", n);
424   for (int i = 0; i < n; i++) {
425     InstanceKlass* e = ik->local_interfaces()->at(i);
426     jio_fprintf(defaultStream::error_stream(), "  %s\n", e->name()->as_klass_external_name());
427   }
428   jio_fprintf(defaultStream::error_stream(), "}\n");
429 }
430 
431 void ClassListParser::print_diagnostic_info(outputStream* st, const char* msg, ...) {
432   va_list ap;
433   va_start(ap, msg);
434   print_diagnostic_info(st, msg, ap);
435   va_end(ap);
436 }
437 
438 void ClassListParser::print_diagnostic_info(outputStream* st, const char* msg, va_list ap) {
439   int error_index = pointer_delta_as_int(_token, _line);
440   if (error_index >= _line_len) {
441     error_index = _line_len - 1;
442   }
443   if (error_index < 0) {
444     error_index = 0;
445   }
446 
447   st->print("An error has occurred while processing class list file %s %zu:%d.\n",
448             _classlist_file, lineno(), (error_index + 1));
449   st->vprint(msg, ap);
450 
451   if (_line_len <= 0) {
452     st->print("\n");
453   } else {
454     st->print(":\n");
455     for (int i=0; i<_line_len; i++) {
456       char c = _line[i];
457       if (c == '\0') {
458         st->print("%s", " ");
459       } else {
460         st->print("%c", c);
461       }
462     }
463     st->print("\n");
464     for (int i=0; i<error_index; i++) {
465       st->print("%s", " ");
466     }
467     st->print("^\n");
468   }
469 }
470 
471 void ClassListParser::error(const char* msg, ...) {
472   va_list ap;
473   va_start(ap, msg);
474   fileStream fs(defaultStream::error_stream());
475   //TODO: we should write to UL/error instead, but that requires fixing some tests cases.
476   //LogTarget(Error, cds) lt;
477   //LogStream ls(lt);
478   print_diagnostic_info(&fs, msg, ap);
479   va_end(ap);
480   vm_exit_during_initialization("class list format error.", nullptr);
481 }
482 
483 void ClassListParser::check_class_name(const char* class_name) {
484   const char* err = nullptr;
485   size_t len = strlen(class_name);
486   if (len > (size_t)Symbol::max_length()) {
487     err = "class name too long";
488   } else {
489     assert(Symbol::max_length() < INT_MAX && len < INT_MAX, "must be");
490     if (!UTF8::is_legal_utf8((const unsigned char*)class_name, len, /*version_leq_47*/false)) {
491       err = "class name is not valid UTF8";
492     }
493   }
494   if (err != nullptr) {
495     jio_fprintf(defaultStream::error_stream(),
496               "An error has occurred while processing class list file %s:%zu %s\n",
497               _classlist_file, lineno(), err);
498     vm_exit_during_initialization("class list format error.", nullptr);
499   }
500 }
501 
502 void ClassListParser::constant_pool_resolution_warning(const char* msg, ...) {
503   va_list ap;
504   va_start(ap, msg);
505   LogTarget(Warning, cds, resolve) lt;
506   LogStream ls(lt);
507   print_diagnostic_info(&ls, msg, ap);
508   ls.print("Your classlist may be out of sync with the JDK or the application.");
509   va_end(ap);
510 }
511 
512 // This function is used for loading classes for customized class loaders
513 // during archive dumping.
514 InstanceKlass* ClassListParser::load_class_from_source(Symbol* class_name, TRAPS) {
515 #if !(defined(_LP64) && (defined(LINUX) || defined(__APPLE__) || defined(_WINDOWS)))
516   // The only supported platforms are: (1) Linux/64-bit and (2) Solaris/64-bit and
517   // (3) MacOSX/64-bit and (4) Windowss/64-bit
518   // This #if condition should be in sync with the areCustomLoadersSupportedForCDS
519   // method in test/lib/jdk/test/lib/Platform.java.
520   error("AppCDS custom class loaders not supported on this platform");
521 #endif
522 
523   if (!is_super_specified()) {
524     error("If source location is specified, super class must be also specified");
525   }
526   if (!is_id_specified()) {
527     error("If source location is specified, id must be also specified");
528   }
529   if (strncmp(_class_name, "java/", 5) == 0) {
530     log_info(cds)("Prohibited package for non-bootstrap classes: %s.class from %s",
531           _class_name, _source);
532     THROW_NULL(vmSymbols::java_lang_ClassNotFoundException());
533   }
534 
535   ResourceMark rm;
536   char * source_path = os::strdup_check_oom(ClassLoader::uri_to_path(_source));
537   InstanceKlass* specified_super = lookup_class_by_id(_super);
538   Handle super_class(THREAD, specified_super->java_mirror());
539   objArrayOop r = get_specified_interfaces(CHECK_NULL);
540   objArrayHandle interfaces(THREAD, r);
541   InstanceKlass* k = UnregisteredClasses::load_class(class_name, source_path,
542                                                      super_class, interfaces, CHECK_NULL);
543   if (k->java_super() != specified_super) {
544     error("The specified super class %s (id %d) does not match actual super class %s",
545           specified_super->external_name(), _super,
546           k->java_super()->external_name());
547   }
548   if (k->local_interfaces()->length() != _interfaces->length()) {
549     print_specified_interfaces();
550     print_actual_interfaces(k);
551     error("The number of interfaces (%d) specified in class list does not match the class file (%d)",
552           _interfaces->length(), k->local_interfaces()->length());
553   }
554 
555   assert(k->is_shared_unregistered_class(), "must be");
556 
557   bool added = SystemDictionaryShared::add_unregistered_class(THREAD, k);
558   if (!added) {
559     // We allow only a single unregistered class for each unique name.
560     error("Duplicated class %s", _class_name);
561   }
562 
563   return k;
564 }
565 
566 void ClassListParser::populate_cds_indy_info(const constantPoolHandle &pool, int cp_index, CDSIndyInfo* cii, TRAPS) {
567   // Caller needs to allocate ResourceMark.
568   int type_index = pool->bootstrap_name_and_type_ref_index_at(cp_index);
569   int name_index = pool->name_ref_index_at(type_index);
570   cii->add_item(pool->symbol_at(name_index)->as_C_string());
571   int sig_index = pool->signature_ref_index_at(type_index);
572   cii->add_item(pool->symbol_at(sig_index)->as_C_string());
573   int argc = pool->bootstrap_argument_count_at(cp_index);
574   if (argc > 0) {
575     for (int arg_i = 0; arg_i < argc; arg_i++) {
576       int arg = pool->bootstrap_argument_index_at(cp_index, arg_i);
577       jbyte tag = pool->tag_at(arg).value();
578       if (tag == JVM_CONSTANT_MethodType) {
579         cii->add_item(pool->method_type_signature_at(arg)->as_C_string());
580       } else if (tag == JVM_CONSTANT_MethodHandle) {
581         cii->add_ref_kind(pool->method_handle_ref_kind_at(arg));
582         int callee_index = pool->method_handle_klass_index_at(arg);
583         Klass* callee = pool->klass_at(callee_index, CHECK);
584         cii->add_item(callee->name()->as_C_string());
585         cii->add_item(pool->method_handle_name_ref_at(arg)->as_C_string());
586         cii->add_item(pool->method_handle_signature_ref_at(arg)->as_C_string());
587       } else {
588         ShouldNotReachHere();
589       }
590     }
591   }
592 }
593 
594 bool ClassListParser::is_matching_cp_entry(const constantPoolHandle &pool, int cp_index, TRAPS) {
595   ResourceMark rm(THREAD);
596   CDSIndyInfo cii;
597   populate_cds_indy_info(pool, cp_index, &cii, CHECK_0);
598   GrowableArray<const char*>* items = cii.items();
599   int indy_info_offset = 1;
600   if (_indy_items->length() - indy_info_offset != items->length()) {
601     return false;
602   }
603   for (int i = 0; i < items->length(); i++) {
604     if (strcmp(_indy_items->at(i + indy_info_offset), items->at(i)) != 0) {
605       return false;
606     }
607   }
608   return true;
609 }
610 
611 void ClassListParser::resolve_indy(JavaThread* current, Symbol* class_name_symbol) {
612   ExceptionMark em(current);
613   JavaThread* THREAD = current; // For exception macros.
614   ClassListParser::resolve_indy_impl(class_name_symbol, THREAD);
615   if (HAS_PENDING_EXCEPTION) {
616     ResourceMark rm(current);
617     char* ex_msg = (char*)"";
618     oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
619     if (message != nullptr) {
620       ex_msg = java_lang_String::as_utf8_string(message);
621     }
622     log_warning(cds)("resolve_indy for class %s has encountered exception: %s %s",
623                      class_name_symbol->as_C_string(),
624                      PENDING_EXCEPTION->klass()->external_name(),
625                      ex_msg);
626     CLEAR_PENDING_EXCEPTION;
627   }
628 }
629 
630 void ClassListParser::resolve_indy_impl(Symbol* class_name_symbol, TRAPS) {
631   if (CDSConfig::is_dumping_method_handles()) {
632     // The CP entry for the invokedynamic instruction will be resolved.
633     // No need to do the following.
634     return;
635   }
636 
637   // This is an older CDS optimization:
638   // We store a pre-generated version of the lambda proxy class in the AOT cache,
639   // which will be loaded via JVM_LookupLambdaProxyClassFromArchive().
640   // This eliminate dynamic class generation of the proxy class, but we still need to
641   // resolve the CP entry for the invokedynamic instruction, which may result in
642   // generation of LambdaForm classes.
643   Handle class_loader(THREAD, SystemDictionary::java_system_loader());
644   Klass* klass = SystemDictionary::resolve_or_fail(class_name_symbol, class_loader, true, CHECK);
645   if (klass->is_instance_klass()) {
646     InstanceKlass* ik = InstanceKlass::cast(klass);
647     MetaspaceShared::try_link_class(THREAD, ik);
648     if (!ik->is_linked()) {
649       // Verification of ik has failed
650       return;
651     }
652 
653     ConstantPool* cp = ik->constants();
654     ConstantPoolCache* cpcache = cp->cache();
655     bool found = false;
656     for (int indy_index = 0; indy_index < cpcache->resolved_indy_entries_length(); indy_index++) {
657       int pool_index = cpcache->resolved_indy_entry_at(indy_index)->constant_pool_index();
658       constantPoolHandle pool(THREAD, cp);
659       BootstrapInfo bootstrap_specifier(pool, pool_index, indy_index);
660       Handle bsm = bootstrap_specifier.resolve_bsm(CHECK);
661       if (!LambdaProxyClassDictionary::is_supported_invokedynamic(&bootstrap_specifier)) {
662         log_debug(cds, lambda)("is_supported_invokedynamic check failed for cp_index %d", pool_index);
663         continue;
664       }
665       bool matched = is_matching_cp_entry(pool, pool_index, CHECK);
666       if (matched) {
667         found = true;
668         CallInfo info;
669         bool is_done = bootstrap_specifier.resolve_previously_linked_invokedynamic(info, CHECK);
670         if (!is_done) {
671           // resolve it
672           Handle recv;
673           LinkResolver::resolve_invoke(info,
674                                        recv,
675                                        pool,
676                                        indy_index,
677                                        Bytecodes::_invokedynamic, CHECK);
678           break;
679         }
680         cpcache->set_dynamic_call(info, indy_index);
681       }
682     }
683     if (!found) {
684       ResourceMark rm(THREAD);
685       log_warning(cds)("No invoke dynamic constant pool entry can be found for class %s. The classlist is probably out-of-date.",
686                      class_name_symbol->as_C_string());
687     }
688   }
689 }
690 
691 Klass* ClassListParser::load_current_class(Symbol* class_name_symbol, TRAPS) {
692   Klass* klass;
693   if (!is_loading_from_source()) {
694     // Load classes for the boot/platform/app loaders only.
695     if (is_super_specified()) {
696       error("If source location is not specified, super class must not be specified");
697     }
698     if (are_interfaces_specified()) {
699       error("If source location is not specified, interface(s) must not be specified");
700     }
701 
702     if (Signature::is_array(class_name_symbol)) {
703       // array classes are not supported in class list.
704       THROW_NULL(vmSymbols::java_lang_ClassNotFoundException());
705     }
706 
707     JavaValue result(T_OBJECT);
708     // Call java_system_loader().loadClass() directly, which will
709     // delegate to the correct loader (boot, platform or app) depending on
710     // the package name.
711 
712     // ClassLoader.loadClass() wants external class name format, i.e., convert '/' chars to '.'
713     Handle ext_class_name = java_lang_String::externalize_classname(class_name_symbol, CHECK_NULL);
714     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
715 
716     JavaCalls::call_virtual(&result,
717                             loader, //SystemDictionary::java_system_loader(),
718                             vmClasses::ClassLoader_klass(),
719                             vmSymbols::loadClass_name(),
720                             vmSymbols::string_class_signature(),
721                             ext_class_name,
722                             CHECK_NULL);
723 
724     assert(result.get_type() == T_OBJECT, "just checking");
725     oop obj = result.get_oop();
726     assert(obj != nullptr, "jdk.internal.loader.BuiltinClassLoader::loadClass never returns null");
727     klass = java_lang_Class::as_Klass(obj);
728   } else {
729     // If "source:" tag is specified, all super class and super interfaces must be specified in the
730     // class list file.
731     klass = load_class_from_source(class_name_symbol, CHECK_NULL);
732   }
733 
734   assert(klass != nullptr, "exception should have been thrown");
735   assert(klass->is_instance_klass(), "array classes should have been filtered out");
736 
737   if (is_id_specified()) {
738     InstanceKlass* ik = InstanceKlass::cast(klass);
739     int id = this->id();
740     SystemDictionaryShared::update_shared_entry(ik, id);
741     bool created;
742     id2klass_table()->put_if_absent(id, ik, &created);
743     if (!created) {
744       error("Duplicated ID %d for class %s", id, _class_name);
745     }
746     if (id2klass_table()->maybe_grow()) {
747       log_info(cds, hashtables)("Expanded id2klass_table() to %d", id2klass_table()->table_size());
748     }
749   }
750 
751   return klass;
752 }
753 
754 bool ClassListParser::is_loading_from_source() {
755   return (_source != nullptr);
756 }
757 
758 InstanceKlass* ClassListParser::lookup_class_by_id(int id) {
759   InstanceKlass** klass_ptr = id2klass_table()->get(id);
760   if (klass_ptr == nullptr) {
761     error("Class ID %d has not been defined", id);
762   }
763   assert(*klass_ptr != nullptr, "must be");
764   return *klass_ptr;
765 }
766 
767 InstanceKlass* ClassListParser::find_builtin_class_helper(JavaThread* current, Symbol* class_name_symbol, oop class_loader_oop) {
768   Handle class_loader(current, class_loader_oop);
769   return SystemDictionary::find_instance_klass(current, class_name_symbol, class_loader);
770 }
771 
772 InstanceKlass* ClassListParser::find_builtin_class(JavaThread* current, const char* class_name) {
773   TempNewSymbol class_name_symbol = SymbolTable::new_symbol(class_name);
774   InstanceKlass* ik;
775 
776   if ( (ik = find_builtin_class_helper(current, class_name_symbol, nullptr)) != nullptr
777     || (ik = find_builtin_class_helper(current, class_name_symbol, SystemDictionary::java_platform_loader())) != nullptr
778     || (ik = find_builtin_class_helper(current, class_name_symbol, SystemDictionary::java_system_loader())) != nullptr) {
779     return ik;
780   } else {
781     return nullptr;
782   }
783 }
784 
785 void ClassListParser::parse_constant_pool_tag() {
786   if (parse_lambda_forms_invokers_only()) {
787     return;
788   }
789 
790   JavaThread* THREAD = JavaThread::current();
791   skip_whitespaces();
792   char* class_name = _token;
793   skip_non_whitespaces();
794   *_token = '\0';
795   _token ++;
796 
797   InstanceKlass* ik = find_builtin_class(THREAD, class_name);
798   if (ik == nullptr) {
799     _token = class_name;
800     if (strstr(class_name, "/$Proxy") != nullptr ||
801         strstr(class_name, "MethodHandle$Species_") != nullptr) {
802       // ignore -- TODO: we should filter these out in classListWriter.cpp
803     } else {
804       constant_pool_resolution_warning("class %s is not (yet) loaded by one of the built-in loaders", class_name);
805     }
806     return;
807   }
808 
809   ResourceMark rm(THREAD);
810   constantPoolHandle cp(THREAD, ik->constants());
811   GrowableArray<bool> preresolve_list(cp->length(), cp->length(), false);
812   bool preresolve_class = false;
813   bool preresolve_fmi = false;
814   bool preresolve_indy = false;
815 
816   while (*_token) {
817     int cp_index;
818     skip_whitespaces();
819     parse_uint(&cp_index);
820     if (cp_index < 1 || cp_index >= cp->length()) {
821       constant_pool_resolution_warning("Invalid constant pool index %d", cp_index);
822       return;
823     } else {
824       preresolve_list.at_put(cp_index, true);
825     }
826     constantTag cp_tag = cp->tag_at(cp_index);
827     switch (cp_tag.value()) {
828     case JVM_CONSTANT_UnresolvedClass:
829       preresolve_class = true;
830       break;
831     case JVM_CONSTANT_UnresolvedClassInError:
832     case JVM_CONSTANT_Class:
833       // ignore
834       break;
835     case JVM_CONSTANT_Fieldref:
836     case JVM_CONSTANT_Methodref:
837     case JVM_CONSTANT_InterfaceMethodref:
838       preresolve_fmi = true;
839       break;
840     case JVM_CONSTANT_InvokeDynamic:
841       preresolve_indy = true;
842       break;
843     default:
844       constant_pool_resolution_warning("Unsupported constant pool index %d: %s (type=%d)",
845                                        cp_index, cp_tag.internal_name(), cp_tag.value());
846       return;
847     }
848   }
849 
850   if (SystemDictionaryShared::should_be_excluded(ik)) {
851     if (log_is_enabled(Warning, cds, resolve)) {
852       ResourceMark rm;
853       log_warning(cds, resolve)("Cannot aot-resolve constants for %s because it is excluded", ik->external_name());
854     }
855     return;
856   }
857 
858   if (preresolve_class) {
859     AOTConstantPoolResolver::preresolve_class_cp_entries(THREAD, ik, &preresolve_list);
860   }
861   if (preresolve_fmi) {
862     AOTConstantPoolResolver::preresolve_field_and_method_cp_entries(THREAD, ik, &preresolve_list);
863   }
864   if (preresolve_indy) {
865     AOTConstantPoolResolver::preresolve_indy_cp_entries(THREAD, ik, &preresolve_list);
866   }
867 }