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   const int actual_num_interfaces = k->local_interfaces()->length();
549   const int specified_num_interfaces = _interfaces->length(); // specified in classlist
550   int expected_num_interfaces = actual_num_interfaces;
551 
552   if (specified_num_interfaces != expected_num_interfaces) {
553     print_specified_interfaces();
554     print_actual_interfaces(k);
555     error("The number of interfaces (%d) specified in class list does not match the class file (%d)",
556           specified_num_interfaces, expected_num_interfaces);
557   }
558 
559   assert(k->is_shared_unregistered_class(), "must be");
560 
561   bool added = SystemDictionaryShared::add_unregistered_class(THREAD, k);
562   if (!added) {
563     // We allow only a single unregistered class for each unique name.
564     error("Duplicated class %s", _class_name);
565   }
566 
567   return k;
568 }
569 
570 void ClassListParser::populate_cds_indy_info(const constantPoolHandle &pool, int cp_index, CDSIndyInfo* cii, TRAPS) {
571   // Caller needs to allocate ResourceMark.
572   int type_index = pool->bootstrap_name_and_type_ref_index_at(cp_index);
573   int name_index = pool->name_ref_index_at(type_index);
574   cii->add_item(pool->symbol_at(name_index)->as_C_string());
575   int sig_index = pool->signature_ref_index_at(type_index);
576   cii->add_item(pool->symbol_at(sig_index)->as_C_string());
577   int argc = pool->bootstrap_argument_count_at(cp_index);
578   if (argc > 0) {
579     for (int arg_i = 0; arg_i < argc; arg_i++) {
580       int arg = pool->bootstrap_argument_index_at(cp_index, arg_i);
581       jbyte tag = pool->tag_at(arg).value();
582       if (tag == JVM_CONSTANT_MethodType) {
583         cii->add_item(pool->method_type_signature_at(arg)->as_C_string());
584       } else if (tag == JVM_CONSTANT_MethodHandle) {
585         cii->add_ref_kind(pool->method_handle_ref_kind_at(arg));
586         int callee_index = pool->method_handle_klass_index_at(arg);
587         Klass* callee = pool->klass_at(callee_index, CHECK);
588         cii->add_item(callee->name()->as_C_string());
589         cii->add_item(pool->method_handle_name_ref_at(arg)->as_C_string());
590         cii->add_item(pool->method_handle_signature_ref_at(arg)->as_C_string());
591       } else {
592         ShouldNotReachHere();
593       }
594     }
595   }
596 }
597 
598 bool ClassListParser::is_matching_cp_entry(const constantPoolHandle &pool, int cp_index, TRAPS) {
599   ResourceMark rm(THREAD);
600   CDSIndyInfo cii;
601   populate_cds_indy_info(pool, cp_index, &cii, CHECK_0);
602   GrowableArray<const char*>* items = cii.items();
603   int indy_info_offset = 1;
604   if (_indy_items->length() - indy_info_offset != items->length()) {
605     return false;
606   }
607   for (int i = 0; i < items->length(); i++) {
608     if (strcmp(_indy_items->at(i + indy_info_offset), items->at(i)) != 0) {
609       return false;
610     }
611   }
612   return true;
613 }
614 
615 void ClassListParser::resolve_indy(JavaThread* current, Symbol* class_name_symbol) {
616   ExceptionMark em(current);
617   JavaThread* THREAD = current; // For exception macros.
618   ClassListParser::resolve_indy_impl(class_name_symbol, THREAD);
619   if (HAS_PENDING_EXCEPTION) {
620     ResourceMark rm(current);
621     char* ex_msg = (char*)"";
622     oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
623     if (message != nullptr) {
624       ex_msg = java_lang_String::as_utf8_string(message);
625     }
626     log_warning(cds)("resolve_indy for class %s has encountered exception: %s %s",
627                      class_name_symbol->as_C_string(),
628                      PENDING_EXCEPTION->klass()->external_name(),
629                      ex_msg);
630     CLEAR_PENDING_EXCEPTION;
631   }
632 }
633 
634 void ClassListParser::resolve_indy_impl(Symbol* class_name_symbol, TRAPS) {
635   if (CDSConfig::is_dumping_method_handles()) {
636     // The CP entry for the invokedynamic instruction will be resolved.
637     // No need to do the following.
638     return;
639   }
640 
641   // This is an older CDS optimization:
642   // We store a pre-generated version of the lambda proxy class in the AOT cache,
643   // which will be loaded via JVM_LookupLambdaProxyClassFromArchive().
644   // This eliminate dynamic class generation of the proxy class, but we still need to
645   // resolve the CP entry for the invokedynamic instruction, which may result in
646   // generation of LambdaForm classes.
647   Handle class_loader(THREAD, SystemDictionary::java_system_loader());
648   Klass* klass = SystemDictionary::resolve_or_fail(class_name_symbol, class_loader, true, CHECK);
649   if (klass->is_instance_klass()) {
650     InstanceKlass* ik = InstanceKlass::cast(klass);
651     MetaspaceShared::try_link_class(THREAD, ik);
652     if (!ik->is_linked()) {
653       // Verification of ik has failed
654       return;
655     }
656 
657     ConstantPool* cp = ik->constants();
658     ConstantPoolCache* cpcache = cp->cache();
659     bool found = false;
660     for (int indy_index = 0; indy_index < cpcache->resolved_indy_entries_length(); indy_index++) {
661       int pool_index = cpcache->resolved_indy_entry_at(indy_index)->constant_pool_index();
662       constantPoolHandle pool(THREAD, cp);
663       BootstrapInfo bootstrap_specifier(pool, pool_index, indy_index);
664       Handle bsm = bootstrap_specifier.resolve_bsm(CHECK);
665       if (!LambdaProxyClassDictionary::is_supported_invokedynamic(&bootstrap_specifier)) {
666         log_debug(cds, lambda)("is_supported_invokedynamic check failed for cp_index %d", pool_index);
667         continue;
668       }
669       bool matched = is_matching_cp_entry(pool, pool_index, CHECK);
670       if (matched) {
671         found = true;
672         CallInfo info;
673         bool is_done = bootstrap_specifier.resolve_previously_linked_invokedynamic(info, CHECK);
674         if (!is_done) {
675           // resolve it
676           Handle recv;
677           LinkResolver::resolve_invoke(info,
678                                        recv,
679                                        pool,
680                                        indy_index,
681                                        Bytecodes::_invokedynamic, CHECK);
682           break;
683         }
684         cpcache->set_dynamic_call(info, indy_index);
685       }
686     }
687     if (!found) {
688       ResourceMark rm(THREAD);
689       log_warning(cds)("No invoke dynamic constant pool entry can be found for class %s. The classlist is probably out-of-date.",
690                      class_name_symbol->as_C_string());
691     }
692   }
693 }
694 
695 Klass* ClassListParser::load_current_class(Symbol* class_name_symbol, TRAPS) {
696   Klass* klass;
697   if (!is_loading_from_source()) {
698     // Load classes for the boot/platform/app loaders only.
699     if (is_super_specified()) {
700       error("If source location is not specified, super class must not be specified");
701     }
702     if (are_interfaces_specified()) {
703       error("If source location is not specified, interface(s) must not be specified");
704     }
705 
706     if (Signature::is_array(class_name_symbol)) {
707       // array classes are not supported in class list.
708       THROW_NULL(vmSymbols::java_lang_ClassNotFoundException());
709     }
710 
711     JavaValue result(T_OBJECT);
712     // Call java_system_loader().loadClass() directly, which will
713     // delegate to the correct loader (boot, platform or app) depending on
714     // the package name.
715 
716     // ClassLoader.loadClass() wants external class name format, i.e., convert '/' chars to '.'
717     Handle ext_class_name = java_lang_String::externalize_classname(class_name_symbol, CHECK_NULL);
718     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
719 
720     JavaCalls::call_virtual(&result,
721                             loader, //SystemDictionary::java_system_loader(),
722                             vmClasses::ClassLoader_klass(),
723                             vmSymbols::loadClass_name(),
724                             vmSymbols::string_class_signature(),
725                             ext_class_name,
726                             CHECK_NULL);
727 
728     assert(result.get_type() == T_OBJECT, "just checking");
729     oop obj = result.get_oop();
730     assert(obj != nullptr, "jdk.internal.loader.BuiltinClassLoader::loadClass never returns null");
731     klass = java_lang_Class::as_Klass(obj);
732   } else {
733     // If "source:" tag is specified, all super class and super interfaces must be specified in the
734     // class list file.
735     klass = load_class_from_source(class_name_symbol, CHECK_NULL);
736   }
737 
738   assert(klass != nullptr, "exception should have been thrown");
739   assert(klass->is_instance_klass(), "array classes should have been filtered out");
740 
741   if (is_id_specified()) {
742     InstanceKlass* ik = InstanceKlass::cast(klass);
743     int id = this->id();
744     SystemDictionaryShared::update_shared_entry(ik, id);
745     bool created;
746     id2klass_table()->put_if_absent(id, ik, &created);
747     if (!created) {
748       error("Duplicated ID %d for class %s", id, _class_name);
749     }
750     if (id2klass_table()->maybe_grow()) {
751       log_info(cds, hashtables)("Expanded id2klass_table() to %d", id2klass_table()->table_size());
752     }
753   }
754 
755   return klass;
756 }
757 
758 bool ClassListParser::is_loading_from_source() {
759   return (_source != nullptr);
760 }
761 
762 InstanceKlass* ClassListParser::lookup_class_by_id(int id) {
763   InstanceKlass** klass_ptr = id2klass_table()->get(id);
764   if (klass_ptr == nullptr) {
765     error("Class ID %d has not been defined", id);
766   }
767   assert(*klass_ptr != nullptr, "must be");
768   return *klass_ptr;
769 }
770 
771 InstanceKlass* ClassListParser::find_builtin_class_helper(JavaThread* current, Symbol* class_name_symbol, oop class_loader_oop) {
772   Handle class_loader(current, class_loader_oop);
773   return SystemDictionary::find_instance_klass(current, class_name_symbol, class_loader);
774 }
775 
776 InstanceKlass* ClassListParser::find_builtin_class(JavaThread* current, const char* class_name) {
777   TempNewSymbol class_name_symbol = SymbolTable::new_symbol(class_name);
778   InstanceKlass* ik;
779 
780   if ( (ik = find_builtin_class_helper(current, class_name_symbol, nullptr)) != nullptr
781     || (ik = find_builtin_class_helper(current, class_name_symbol, SystemDictionary::java_platform_loader())) != nullptr
782     || (ik = find_builtin_class_helper(current, class_name_symbol, SystemDictionary::java_system_loader())) != nullptr) {
783     return ik;
784   } else {
785     return nullptr;
786   }
787 }
788 
789 void ClassListParser::parse_constant_pool_tag() {
790   if (parse_lambda_forms_invokers_only()) {
791     return;
792   }
793 
794   JavaThread* THREAD = JavaThread::current();
795   skip_whitespaces();
796   char* class_name = _token;
797   skip_non_whitespaces();
798   *_token = '\0';
799   _token ++;
800 
801   InstanceKlass* ik = find_builtin_class(THREAD, class_name);
802   if (ik == nullptr) {
803     _token = class_name;
804     if (strstr(class_name, "/$Proxy") != nullptr ||
805         strstr(class_name, "MethodHandle$Species_") != nullptr) {
806       // ignore -- TODO: we should filter these out in classListWriter.cpp
807     } else {
808       constant_pool_resolution_warning("class %s is not (yet) loaded by one of the built-in loaders", class_name);
809     }
810     return;
811   }
812 
813   ResourceMark rm(THREAD);
814   constantPoolHandle cp(THREAD, ik->constants());
815   GrowableArray<bool> preresolve_list(cp->length(), cp->length(), false);
816   bool preresolve_class = false;
817   bool preresolve_fmi = false;
818   bool preresolve_indy = false;
819 
820   while (*_token) {
821     int cp_index;
822     skip_whitespaces();
823     parse_uint(&cp_index);
824     if (cp_index < 1 || cp_index >= cp->length()) {
825       constant_pool_resolution_warning("Invalid constant pool index %d", cp_index);
826       return;
827     } else {
828       preresolve_list.at_put(cp_index, true);
829     }
830     constantTag cp_tag = cp->tag_at(cp_index);
831     switch (cp_tag.value()) {
832     case JVM_CONSTANT_UnresolvedClass:
833       preresolve_class = true;
834       break;
835     case JVM_CONSTANT_UnresolvedClassInError:
836     case JVM_CONSTANT_Class:
837       // ignore
838       break;
839     case JVM_CONSTANT_Fieldref:
840     case JVM_CONSTANT_Methodref:
841     case JVM_CONSTANT_InterfaceMethodref:
842       preresolve_fmi = true;
843       break;
844     case JVM_CONSTANT_InvokeDynamic:
845       preresolve_indy = true;
846       break;
847     default:
848       constant_pool_resolution_warning("Unsupported constant pool index %d: %s (type=%d)",
849                                        cp_index, cp_tag.internal_name(), cp_tag.value());
850       return;
851     }
852   }
853 
854   if (SystemDictionaryShared::should_be_excluded(ik)) {
855     if (log_is_enabled(Warning, cds, resolve)) {
856       ResourceMark rm;
857       log_warning(cds, resolve)("Cannot aot-resolve constants for %s because it is excluded", ik->external_name());
858     }
859     return;
860   }
861 
862   if (preresolve_class) {
863     AOTConstantPoolResolver::preresolve_class_cp_entries(THREAD, ik, &preresolve_list);
864   }
865   if (preresolve_fmi) {
866     AOTConstantPoolResolver::preresolve_field_and_method_cp_entries(THREAD, ik, &preresolve_list);
867   }
868   if (preresolve_indy) {
869     AOTConstantPoolResolver::preresolve_indy_cp_entries(THREAD, ik, &preresolve_list);
870   }
871 }