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