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