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