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