1 /*
   2  * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/aotClassLocation.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/cdsConfig.hpp"
  28 #include "cds/dynamicArchive.hpp"
  29 #include "cds/filemap.hpp"
  30 #include "cds/metaspaceShared.hpp"
  31 #include "cds/serializeClosure.hpp"
  32 #include "classfile/classLoader.hpp"
  33 #include "classfile/classLoaderData.hpp"
  34 #include "classfile/javaClasses.hpp"
  35 #include "logging/log.hpp"
  36 #include "logging/logStream.hpp"
  37 #include "memory/metadataFactory.hpp"
  38 #include "memory/metaspaceClosure.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "oops/array.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "runtime/arguments.hpp"
  43 #include "utilities/classpathStream.hpp"
  44 #include "utilities/formatBuffer.hpp"
  45 #include "utilities/stringUtils.hpp"
  46 
  47 #include <sys/stat.h>
  48 #include <errno.h>
  49 
  50 Array<ClassPathZipEntry*>* AOTClassLocationConfig::_dumptime_jar_files = nullptr;
  51 AOTClassLocationConfig* AOTClassLocationConfig::_dumptime_instance = nullptr;
  52 const AOTClassLocationConfig* AOTClassLocationConfig::_runtime_instance = nullptr;
  53 
  54 // A ClassLocationStream represents a list of code locations, which can be iterated using
  55 // start() and has_next().
  56 class ClassLocationStream {
  57 protected:
  58   GrowableArray<const char*> _array;
  59   int _current;
  60 
  61   // Add one path to this stream.
  62   void add_one_path(const char* path) {
  63     _array.append(path);
  64   }
  65 
  66   // Add all paths specified in cp; cp must be from -classpath or -Xbootclasspath/a.
  67   void add_paths_in_classpath(const char* cp) {
  68     ClasspathStream cp_stream(cp);
  69     while (cp_stream.has_next()) {
  70       add_one_path(cp_stream.get_next());
  71     }
  72   }
  73 
  74 public:
  75   ClassLocationStream() : _array(), _current(0) {}
  76 
  77   void print(outputStream* st) const {
  78     const char* sep = "";
  79     for (int i = 0; i < _array.length(); i++) {
  80       st->print("%s%s", sep, _array.at(i));
  81       sep = os::path_separator();
  82     }
  83   }
  84 
  85   void add(ClassLocationStream& css) {
  86     for (css.start(); css.has_next();) {
  87       add_one_path(css.get_next());
  88     }
  89   }
  90 
  91   // Iteration
  92   void start() { _current = 0; }
  93   bool has_next() const { return _current < _array.length(); }
  94   const char* get_next() {
  95     return _array.at(_current++);
  96   }
  97 
  98   int current() const { return _current; }
  99   bool is_empty() const { return _array.length() == 0; }
 100 };
 101 
 102 class BootCpClassLocationStream : public ClassLocationStream {
 103 public:
 104   BootCpClassLocationStream() : ClassLocationStream() {
 105     // Arguments::get_boot_class_path() contains $JAVA_HOME/lib/modules, but we treat that separately
 106     for (const char* bootcp = Arguments::get_boot_class_path(); *bootcp != '\0'; ++bootcp) {
 107       if (*bootcp == *os::path_separator()) {
 108         ++bootcp;
 109         add_paths_in_classpath(bootcp);
 110         break;
 111       }
 112     }
 113   }
 114 };
 115 
 116 class AppCpClassLocationStream : public ClassLocationStream {
 117 public:
 118   AppCpClassLocationStream() : ClassLocationStream() {
 119     const char* appcp = Arguments::get_appclasspath();
 120     if (strcmp(appcp, ".") == 0) {
 121       appcp = "";
 122     }
 123     add_paths_in_classpath(appcp);
 124   }
 125 };
 126 
 127 class ModulePathClassLocationStream : public ClassLocationStream {
 128   bool _has_non_jar_modules;
 129 public:
 130   ModulePathClassLocationStream();
 131   bool has_non_jar_modules() { return _has_non_jar_modules; }
 132 };
 133 
 134 // AllClassLocationStreams is used to iterate over all the code locations that
 135 // are available to the application from -Xbootclasspath, -classpath and --module-path.
 136 // When creating an AOT cache, we store the contents from AllClassLocationStreams
 137 // into an array of AOTClassLocations. See AOTClassLocationConfig::dumptime_init_helper().
 138 // When loading the AOT cache in a production run, we compare the contents of the
 139 // stored AOTClassLocations against the current AllClassLocationStreams to determine whether
 140 // the AOT cache is compatible with the current JVM. See AOTClassLocationConfig::validate().
 141 class AllClassLocationStreams {
 142   BootCpClassLocationStream _boot_cp;          // Specified by -Xbootclasspath/a
 143   AppCpClassLocationStream _app_cp;            // Specified by -classpath
 144   ModulePathClassLocationStream _module_path;  // Specified by --module-path
 145   ClassLocationStream _boot_and_app_cp;        // Convenience for iterating over both _boot and _app
 146 public:
 147   BootCpClassLocationStream& boot_cp()             { return _boot_cp; }
 148   AppCpClassLocationStream& app_cp()               { return _app_cp; }
 149   ModulePathClassLocationStream& module_path()     { return _module_path; }
 150   ClassLocationStream& boot_and_app_cp()           { return _boot_and_app_cp; }
 151 
 152   AllClassLocationStreams() : _boot_cp(), _app_cp(), _module_path(), _boot_and_app_cp() {
 153     _boot_and_app_cp.add(_boot_cp);
 154     _boot_and_app_cp.add(_app_cp);
 155   }
 156 };
 157 
 158 static bool has_jar_suffix(const char* filename) {
 159   // In jdk.internal.module.ModulePath.readModule(), it checks for the ".jar" suffix.
 160   // Performing the same check here.
 161   const char* dot = strrchr(filename, '.');
 162   if (dot != nullptr && strcmp(dot + 1, "jar") == 0) {
 163     return true;
 164   }
 165   return false;
 166 }
 167 
 168 static int compare_module_path_by_name(const char** p1, const char** p2) {
 169   return strcmp(*p1, *p2);
 170 }
 171 
 172 ModulePathClassLocationStream::ModulePathClassLocationStream() : ClassLocationStream(), _has_non_jar_modules(false) {
 173   // Note: for handling of --module-path, see
 174   //   https://openjdk.org/jeps/261#Module-paths
 175   //   https://docs.oracle.com/en/java/javase/23/docs/api/java.base/java/lang/module/ModuleFinder.html#of(java.nio.file.Path...)
 176 
 177   const char* jdk_module_path = Arguments::get_property("jdk.module.path");
 178   if (jdk_module_path == nullptr) {
 179     return;
 180   }
 181 
 182   ClasspathStream cp_stream(jdk_module_path);
 183   while (cp_stream.has_next()) {
 184     const char* path = cp_stream.get_next();
 185     DIR* dirp = os::opendir(path);
 186     if (dirp == nullptr && errno == ENOTDIR && has_jar_suffix(path)) {
 187       add_one_path(path);
 188     } else if (dirp != nullptr) {
 189       struct dirent* dentry;
 190       bool found_jar = false;
 191       while ((dentry = os::readdir(dirp)) != nullptr) {
 192         const char* file_name = dentry->d_name;
 193         if (has_jar_suffix(file_name)) {
 194           size_t full_name_len = strlen(path) + strlen(file_name) + strlen(os::file_separator()) + 1;
 195           char* full_name = NEW_RESOURCE_ARRAY(char, full_name_len);
 196           int n = os::snprintf(full_name, full_name_len, "%s%s%s", path, os::file_separator(), file_name);
 197           assert((size_t)n == full_name_len - 1, "Unexpected number of characters in string");
 198           add_one_path(full_name);
 199           found_jar = true;
 200         } else if (strcmp(file_name, ".") != 0 && strcmp(file_name, "..") != 0) {
 201           // Found some non jar entries
 202           _has_non_jar_modules = true;
 203           log_info(class, path)("Found non-jar path: '%s%s%s'", path, os::file_separator(), file_name);
 204         }
 205       }
 206       if (!found_jar) {
 207         log_info(class, path)("Found exploded module path: '%s'", path);
 208         _has_non_jar_modules = true;
 209       }
 210       os::closedir(dirp);
 211     } else {
 212       _has_non_jar_modules = true;
 213     }
 214   }
 215 
 216   _array.sort(compare_module_path_by_name);
 217 }
 218 
 219 AOTClassLocation* AOTClassLocation::allocate(JavaThread* current, const char* path, int index,
 220                                              Group group, bool from_cpattr, bool is_jrt) {
 221   size_t path_length = 0;
 222   size_t manifest_length = 0;
 223   bool check_time = false;
 224   time_t timestamp = 0;
 225   int64_t filesize = 0;
 226   FileType type = FileType::NORMAL;
 227   // Do not record the actual path of the jrt, as the entire JDK can be moved to a different
 228   // directory.
 229   const char* recorded_path = is_jrt ? "" : path;
 230   path_length = strlen(recorded_path);
 231 
 232   struct stat st;
 233   if (os::stat(path, &st) == 0) {
 234     if ((st.st_mode & S_IFMT) == S_IFDIR) {
 235       type = FileType::DIR;
 236     } else {
 237       timestamp = st.st_mtime;
 238       filesize = st.st_size;
 239 
 240       // The timestamp of $JAVA_HOME/lib/modules is not checked at runtime.
 241       check_time = !is_jrt;
 242     }
 243 #ifdef _WINDOWS
 244   } else if (errno == ERROR_FILE_NOT_FOUND || errno == ERROR_PATH_NOT_FOUND) {
 245     // On Windows, the errno could be ERROR_PATH_NOT_FOUND (3) in case the directory
 246     // path doesn't exist.
 247     type = FileType::NOT_EXIST;
 248 #endif
 249   } else if (errno == ENOENT) {
 250     // We allow the file to not exist, as long as it also doesn't exist during runtime.
 251     type = FileType::NOT_EXIST;
 252   } else {
 253     log_error(cds)("Unable to open file %s.", path);
 254     MetaspaceShared::unrecoverable_loading_error();
 255   }
 256 
 257   ResourceMark rm(current);
 258   char* manifest = nullptr;
 259 
 260   if (!is_jrt && type == FileType::NORMAL) {
 261     manifest = read_manifest(current, path, manifest_length); // resource allocated
 262   }
 263 
 264   size_t cs_size = header_size() +
 265     + path_length + 1 /* nul-terminated */
 266     + manifest_length + 1; /* nul-terminated */
 267 
 268   AOTClassLocation* cs = (AOTClassLocation*)os::malloc(cs_size, mtClassShared);
 269   memset(cs, 0, cs_size);
 270   cs->_path_length = path_length;
 271   cs->_manifest_length = manifest_length;
 272   cs->_check_time = check_time;
 273   cs->_from_cpattr = from_cpattr;
 274   cs->_timestamp = timestamp;
 275   cs->_filesize = filesize;
 276   cs->_file_type = type;
 277   cs->_group = group;
 278   cs->_index = index;
 279 
 280   strcpy(((char*)cs) + cs->path_offset(), recorded_path);
 281   if (manifest_length > 0) {
 282     memcpy(((char*)cs) + cs->manifest_offset(), manifest, manifest_length);
 283   }
 284   assert(*(cs->manifest() + cs->manifest_length()) == '\0', "should be nul-terminated");
 285 
 286   if (strstr(cs->manifest(), "Multi-Release: true") != nullptr) {
 287     cs->_is_multi_release_jar = true;
 288   }
 289 
 290   if (strstr(cs->manifest(), "Extension-List:") != nullptr) {
 291     vm_exit_during_cds_dumping(err_msg("-Xshare:dump does not support Extension-List in JAR manifest: %s", path));
 292   }
 293 
 294   return cs;
 295 }
 296 
 297 char* AOTClassLocation::read_manifest(JavaThread* current, const char* path, size_t& manifest_length) {
 298   manifest_length = 0;
 299 
 300   struct stat st;
 301   if (os::stat(path, &st) != 0) {
 302     return nullptr;
 303   }
 304 
 305   ClassPathEntry* cpe = ClassLoader::create_class_path_entry(current, path, &st);
 306   if (cpe == nullptr) {
 307     // <path> is a file, but not a JAR file
 308     return nullptr;
 309   }
 310   assert(cpe->is_jar_file(), "should not be called with a directory");
 311 
 312   const char* name = "META-INF/MANIFEST.MF";
 313   char* manifest;
 314   jint size;
 315   manifest = (char*) ((ClassPathZipEntry*)cpe)->open_entry(current, name, &size, true);
 316 
 317   if (manifest == nullptr || size <= 0) { // No Manifest
 318     manifest_length = 0;
 319   } else {
 320     manifest_length = (size_t)size;
 321   }
 322 
 323   delete cpe;
 324   return manifest;
 325 }
 326 
 327 // The result is resource allocated.
 328 char* AOTClassLocation::get_cpattr() const {
 329   if (_manifest_length == 0) {
 330     return nullptr;
 331   }
 332 
 333   size_t buf_size = _manifest_length + 1;
 334   char* buf = NEW_RESOURCE_ARRAY(char, buf_size);
 335   memcpy(buf, manifest(), _manifest_length);
 336   buf[_manifest_length] = 0; // make sure it's 0-terminated
 337 
 338   // See http://docs.oracle.com/javase/6/docs/technotes/guides/jar/jar.html#JAR%20Manifest
 339   // Replace all CR/LF and CR with LF
 340   StringUtils::replace_no_expand(buf, "\r\n", "\n");
 341   // Remove all new-line continuation (remove all "\n " substrings)
 342   StringUtils::replace_no_expand(buf, "\n ", "");
 343 
 344   const char* tag = "Class-Path: ";
 345   size_t tag_len = strlen(tag);
 346   char* found = nullptr;
 347   char* line_start = buf;
 348   char* end = buf + _manifest_length;
 349 
 350   assert(*end == 0, "must be nul-terminated");
 351 
 352   while (line_start < end) {
 353     char* line_end = strchr(line_start, '\n');
 354     if (line_end == nullptr) {
 355       // JAR spec require the manifest file to be terminated by a new line.
 356       break;
 357     }
 358     if (strncmp(tag, line_start, tag_len) == 0) {
 359       if (found != nullptr) {
 360         // Same behavior as jdk/src/share/classes/java/util/jar/Attributes.java
 361         // If duplicated entries are found, the last one is used.
 362         log_warning(cds)("Warning: Duplicate name in Manifest: %s.\n"
 363                          "Ensure that the manifest does not have duplicate entries, and\n"
 364                          "that blank lines separate individual sections in both your\n"
 365                          "manifest and in the META-INF/MANIFEST.MF entry in the jar file:\n%s\n", tag, path());
 366       }
 367       found = line_start + tag_len;
 368       assert(found <= line_end, "sanity");
 369       *line_end = '\0';
 370     }
 371     line_start = line_end + 1;
 372   }
 373 
 374   return found;
 375 }
 376 
 377 AOTClassLocation* AOTClassLocation::write_to_archive() const {
 378   AOTClassLocation* archived_copy = (AOTClassLocation*)ArchiveBuilder::ro_region_alloc(total_size());
 379   memcpy((char*)archived_copy, (char*)this, total_size());
 380   return archived_copy;
 381 }
 382 
 383 const char* AOTClassLocation::file_type_string() const {
 384   switch (_file_type) {
 385   case FileType::NORMAL: return "file";
 386   case FileType::DIR: return "dir";
 387   case FileType::NOT_EXIST: default: return "not-exist";
 388   }
 389 }
 390 
 391 bool AOTClassLocation::check(const char* runtime_path, bool has_aot_linked_classes) const {
 392   struct stat st;
 393   if (os::stat(runtime_path, &st) != 0) {
 394     if (_file_type != FileType::NOT_EXIST) {
 395       log_warning(cds)("Required classpath entry does not exist: %s", runtime_path);
 396       return false;
 397     }
 398   } else if ((st.st_mode & S_IFMT) == S_IFDIR) {
 399     if (_file_type == FileType::NOT_EXIST) {
 400       log_warning(cds)("'%s' must not exist", runtime_path);
 401       return false;
 402     }
 403     if (_file_type == FileType::NORMAL) {
 404       log_warning(cds)("'%s' must be a file", runtime_path);
 405       return false;
 406     }
 407     if (!os::dir_is_empty(runtime_path)) {
 408       log_warning(cds)("directory is not empty: '%s'", runtime_path);
 409       return false;
 410     }
 411   } else {
 412     if (_file_type == FileType::NOT_EXIST) {
 413       log_warning(cds)("'%s' must not exist", runtime_path);
 414       if (has_aot_linked_classes) {
 415         log_error(cds)("CDS archive has aot-linked classes. It cannot be used because the "
 416                        "file %s exists", runtime_path);
 417         return false;
 418       } else {
 419         log_warning(cds)("Archived non-system classes are disabled because the "
 420                          "file %s exists", runtime_path);
 421         FileMapInfo::current_info()->set_has_platform_or_app_classes(false);
 422         if (DynamicArchive::is_mapped()) {
 423           FileMapInfo::dynamic_info()->set_has_platform_or_app_classes(false);
 424         }
 425       }
 426     }
 427     if (_file_type == FileType::DIR) {
 428       log_warning(cds)("'%s' must be a directory", runtime_path);
 429       return false;
 430     }
 431     bool size_differs = _filesize != st.st_size;
 432     bool time_differs = _check_time && (_timestamp != st.st_mtime);
 433     if (size_differs || time_differs) {
 434       log_warning(cds)("This file is not the one used while building the shared archive file: '%s'%s%s",
 435                        runtime_path,
 436                        time_differs ? ", timestamp has changed" : "",
 437                        size_differs ? ", size has changed" : "");
 438       return false;
 439     }
 440   }
 441 
 442   log_info(class, path)("ok");
 443   return true;
 444 }
 445 
 446 void AOTClassLocationConfig::dumptime_init(JavaThread* current) {
 447   assert(CDSConfig::is_dumping_archive(), "");
 448   _dumptime_instance = NEW_C_HEAP_OBJ(AOTClassLocationConfig, mtClassShared);
 449   _dumptime_instance->dumptime_init_helper(current);
 450   if (current->has_pending_exception()) {
 451     // we can get an exception only when we run out of metaspace, but that
 452     // shouldn't happen this early in bootstrap.
 453     java_lang_Throwable::print(current->pending_exception(), tty);
 454     vm_exit_during_initialization("AOTClassLocationConfig::dumptime_init_helper() failed unexpectedly");
 455   }
 456 }
 457 
 458 void AOTClassLocationConfig::dumptime_init_helper(TRAPS) {
 459   ResourceMark rm;
 460   GrowableClassLocationArray tmp_array;
 461   AllClassLocationStreams all_css;
 462 
 463   AOTClassLocation* jrt = AOTClassLocation::allocate(THREAD, ClassLoader::get_jrt_entry()->name(),
 464                                                0, Group::MODULES_IMAGE,
 465                                                /*from_cpattr*/false, /*is_jrt*/true);
 466   tmp_array.append(jrt);
 467 
 468   parse(THREAD, tmp_array, all_css.boot_cp(), Group::BOOT_CLASSPATH, /*parse_manifest*/true);
 469   _boot_classpath_end = tmp_array.length();
 470 
 471   parse(THREAD, tmp_array, all_css.app_cp(), Group::APP_CLASSPATH, /*parse_manifest*/true);
 472   _app_classpath_end = tmp_array.length();
 473 
 474   parse(THREAD, tmp_array, all_css.module_path(), Group::MODULE_PATH, /*parse_manifest*/false);
 475   _module_end = tmp_array.length();
 476 
 477   _class_locations =  MetadataFactory::new_array<AOTClassLocation*>(ClassLoaderData::the_null_class_loader_data(),
 478                                                                tmp_array.length(), CHECK);
 479   for (int i = 0; i < tmp_array.length(); i++) {
 480     _class_locations->at_put(i, tmp_array.at(i));
 481   }
 482 
 483   _dumptime_jar_files = MetadataFactory::new_array<ClassPathZipEntry*>(ClassLoaderData::the_null_class_loader_data(),
 484                                                                        tmp_array.length(), CHECK);
 485   for (int i = 1; i < tmp_array.length(); i++) {
 486     ClassPathZipEntry* jar_file = ClassLoader::create_class_path_zip_entry(tmp_array.at(i)->path());
 487     _dumptime_jar_files->at_put(i, jar_file); // may be null if the path is not a valid JAR file
 488   }
 489 
 490   const char* lcp = find_lcp(all_css.boot_and_app_cp(), _dumptime_lcp_len);
 491   if (_dumptime_lcp_len > 0) {
 492     os::free((void*)lcp);
 493     log_info(class, path)("Longest common prefix = %s (%zu chars)", lcp, _dumptime_lcp_len);
 494   } else {
 495     assert(_dumptime_lcp_len == 0, "sanity");
 496     log_info(class, path)("Longest common prefix = <none> (0 chars)");
 497   }
 498 
 499   _has_non_jar_modules = all_css.module_path().has_non_jar_modules();
 500   _has_platform_classes = false;
 501   _has_app_classes = false;
 502   _max_used_index = 0;
 503 }
 504 
 505 // Find the longest common prefix of two paths, up to max_lcp_len.
 506 // E.g.   p1 = "/a/b/foo"
 507 //        p2 = "/a/b/bar"
 508 //        max_lcp_len = 3
 509 // -> returns 3
 510 static size_t find_lcp_of_two_paths(const char* p1, const char* p2, size_t max_lcp_len) {
 511   size_t lcp_len = 0;
 512   char sep = os::file_separator()[0];
 513   for (size_t i = 0; ; i++) {
 514     char c1 = *p1++;
 515     char c2 = *p2++;
 516     if (c1 == 0 || c2 == 0 || c1 != c2) {
 517       break;
 518     }
 519     if (c1 == sep) {
 520       lcp_len = i + 1;
 521       assert(lcp_len <= max_lcp_len, "sanity");
 522       if (lcp_len == max_lcp_len) {
 523         break;
 524       }
 525     }
 526   }
 527   return lcp_len;
 528 }
 529 
 530 // cheap-allocated if lcp_len > 0
 531 const char* AOTClassLocationConfig::find_lcp(ClassLocationStream& css, size_t& lcp_len) {
 532   const char* first_path = nullptr;
 533   char sep = os::file_separator()[0];
 534 
 535   for (css.start(); css.has_next(); ) {
 536     const char* path = css.get_next();
 537     if (first_path == nullptr) {
 538       first_path = path;
 539       const char* p = strrchr(first_path, sep);
 540       if (p == nullptr) {
 541         lcp_len = 0;
 542         return "";
 543       } else {
 544         lcp_len = p - first_path + 1;
 545       }
 546     } else {
 547       lcp_len = find_lcp_of_two_paths(first_path, path, lcp_len);
 548       if (lcp_len == 0) {
 549         return "";
 550       }
 551     }
 552   }
 553 
 554   if (first_path != nullptr && lcp_len > 0) {
 555     char* lcp = NEW_C_HEAP_ARRAY(char, lcp_len + 1, mtClassShared);
 556     lcp[0] = 0;
 557     strncat(lcp, first_path, lcp_len);
 558     return lcp;
 559   } else {
 560     lcp_len = 0;
 561     return "";
 562   }
 563 }
 564 
 565 void AOTClassLocationConfig::parse(JavaThread* current, GrowableClassLocationArray& tmp_array,
 566                                    ClassLocationStream& css, Group group, bool parse_manifest) {
 567   for (css.start(); css.has_next(); ) {
 568     add_class_location(current, tmp_array, css.get_next(), group, parse_manifest, /*from_cpattr*/false);
 569   }
 570 }
 571 
 572 void AOTClassLocationConfig::add_class_location(JavaThread* current, GrowableClassLocationArray& tmp_array,
 573                                                 const char* path, Group group, bool parse_manifest, bool from_cpattr) {
 574   AOTClassLocation* cs = AOTClassLocation::allocate(current, path, tmp_array.length(), group, from_cpattr);
 575   tmp_array.append(cs);
 576 
 577   if (!parse_manifest) {
 578     // parse_manifest is true for -classpath and -Xbootclasspath/a, and false for --module-path.
 579     return;
 580   }
 581 
 582   ResourceMark rm;
 583   char* cp_attr = cs->get_cpattr(); // resource allocated
 584   if (cp_attr != nullptr && strlen(cp_attr) > 0) {
 585     //trace_class_path("found Class-Path: ", cp_attr); FIXME
 586 
 587     char sep = os::file_separator()[0];
 588     const char* dir_name = cs->path();
 589     const char* dir_tail = strrchr(dir_name, sep);
 590 #ifdef _WINDOWS
 591     // On Windows, we also support forward slash as the file separator when locating entries in the classpath entry.
 592     const char* dir_tail2 = strrchr(dir_name, '/');
 593     if (dir_tail == nullptr) {
 594       dir_tail = dir_tail2;
 595     } else if (dir_tail2 != nullptr && dir_tail2 > dir_tail) {
 596       dir_tail = dir_tail2;
 597     }
 598 #endif
 599     int dir_len;
 600     if (dir_tail == nullptr) {
 601       dir_len = 0;
 602     } else {
 603       dir_len = pointer_delta_as_int(dir_tail, dir_name) + 1;
 604     }
 605 
 606     // Split the cp_attr by spaces, and add each file
 607     char* file_start = cp_attr;
 608     char* end = file_start + strlen(file_start);
 609 
 610     while (file_start < end) {
 611       char* file_end = strchr(file_start, ' ');
 612       if (file_end != nullptr) {
 613         *file_end = 0;
 614         file_end += 1;
 615       } else {
 616         file_end = end;
 617       }
 618 
 619       size_t name_len = strlen(file_start);
 620       if (name_len > 0) {
 621         ResourceMark rm(current);
 622         size_t libname_len = dir_len + name_len;
 623         char* libname = NEW_RESOURCE_ARRAY(char, libname_len + 1);
 624         int n = os::snprintf(libname, libname_len + 1, "%.*s%s", dir_len, dir_name, file_start);
 625         assert((size_t)n == libname_len, "Unexpected number of characters in string");
 626 
 627         // Avoid infinite recursion when two JAR files refer to each
 628         // other via cpattr.
 629         bool found_duplicate = false;
 630         for (int i = boot_cp_start_index(); i < tmp_array.length(); i++) {
 631           if (strcmp(tmp_array.at(i)->path(), libname) == 0) {
 632             found_duplicate = true;
 633             break;
 634           }
 635         }
 636         if (!found_duplicate) {
 637           add_class_location(current, tmp_array, libname, group, parse_manifest, /*from_cpattr*/true);
 638         }
 639       }
 640 
 641       file_start = file_end;
 642     }
 643   }
 644 }
 645 
 646 AOTClassLocation const* AOTClassLocationConfig::class_location_at(int index) const {
 647   return _class_locations->at(index);
 648 }
 649 
 650 int AOTClassLocationConfig::get_module_shared_path_index(Symbol* location) const {
 651   if (location == nullptr) {
 652     return 0; // Used by java/lang/reflect/Proxy$ProxyBuilder
 653   }
 654 
 655   if (location->starts_with("jrt:", 4)) {
 656     assert(class_location_at(0)->is_modules_image(), "sanity");
 657     return 0;
 658   }
 659 
 660   if (num_module_paths() == 0) {
 661     // The archive(s) were created without --module-path option
 662     return -1;
 663   }
 664 
 665   if (!location->starts_with("file:", 5)) {
 666     return -1;
 667   }
 668 
 669   // skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table()
 670   ResourceMark rm;
 671   const char* file = ClassLoader::uri_to_path(location->as_C_string());
 672   for (int i = module_path_start_index(); i < module_path_end_index(); i++) {
 673     const AOTClassLocation* cs = class_location_at(i);
 674     assert(!cs->has_unnamed_module(), "must be");
 675     bool same = os::same_files(file, cs->path());
 676     log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i,
 677                            location->as_C_string(), cs->path(), same ? "same" : "different");
 678     if (same) {
 679       return i;
 680     }
 681   }
 682   return -1;
 683 }
 684 
 685 // We allow non-empty dirs as long as no classes have been loaded from them.
 686 void AOTClassLocationConfig::check_nonempty_dirs() const {
 687   assert(CDSConfig::is_dumping_archive(), "sanity");
 688 
 689   bool has_nonempty_dir = false;
 690   dumptime_iterate([&](AOTClassLocation* cs) {
 691     if (cs->index() > _max_used_index) {
 692       return false; // stop iterating
 693     }
 694     if (cs->is_dir()) {
 695       if (!os::dir_is_empty(cs->path())) {
 696         log_error(cds)("Error: non-empty directory '%s'", cs->path());
 697         has_nonempty_dir = true;
 698       }
 699     }
 700     return true; // keep iterating
 701   });
 702 
 703   if (has_nonempty_dir) {
 704     vm_exit_during_cds_dumping("Cannot have non-empty directory in paths", nullptr);
 705   }
 706 }
 707 
 708 // It's possible to use reflection+setAccessible to call into ClassLoader::defineClass() to
 709 // pretend that a dynamically generated class comes from a JAR file in the classpath.
 710 // Detect such classes and exclude them from the archive.
 711 void AOTClassLocationConfig::check_invalid_classpath_index(int classpath_index, InstanceKlass* ik) {
 712   if (1 <= classpath_index && classpath_index < length()) {
 713     ClassPathZipEntry *zip = _dumptime_jar_files->at(classpath_index);
 714     if (zip != nullptr) {
 715       JavaThread* current = JavaThread::current();
 716       ResourceMark rm(current);
 717       const char* const class_name = ik->name()->as_C_string();
 718       const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
 719                                                                           ik->name()->utf8_length());
 720       if (!zip->has_entry(current, file_name)) {
 721         log_warning(cds)("class %s cannot be archived because it was not define from %s as claimed",
 722                          class_name, zip->name());
 723         ik->set_shared_classpath_index(-1);
 724       }
 725     }
 726   }
 727 }
 728 
 729 AOTClassLocationConfig* AOTClassLocationConfig::write_to_archive() const {
 730   Array<AOTClassLocation*>* archived_copy = ArchiveBuilder::new_ro_array<AOTClassLocation*>(_class_locations->length());
 731   for (int i = 0; i < _class_locations->length(); i++) {
 732     archived_copy->at_put(i, _class_locations->at(i)->write_to_archive());
 733     ArchivePtrMarker::mark_pointer((address*)archived_copy->adr_at(i));
 734   }
 735 
 736   AOTClassLocationConfig* dumped = (AOTClassLocationConfig*)ArchiveBuilder::ro_region_alloc(sizeof(AOTClassLocationConfig));
 737   memcpy(dumped, this, sizeof(AOTClassLocationConfig));
 738   dumped->_class_locations = archived_copy;
 739   ArchivePtrMarker::mark_pointer(&dumped->_class_locations);
 740 
 741   return dumped;
 742 }
 743 
 744 bool AOTClassLocationConfig::check_classpaths(bool is_boot_classpath, bool has_aot_linked_classes,
 745                                               int index_start, int index_end,
 746                                               ClassLocationStream& runtime_css,
 747                                               bool use_lcp_match, const char* runtime_lcp,
 748                                               size_t runtime_lcp_len) const {
 749   if (index_start >= index_end && runtime_css.is_empty()) { // nothing to check
 750     return true;
 751   }
 752 
 753   ResourceMark rm;
 754   const char* which = is_boot_classpath ? "boot" : "app";
 755   LogTarget(Info, class, path) lt;
 756   if (lt.is_enabled()) {
 757     LogStream ls(lt);
 758     ls.print("Checking %s classpath", which);
 759     ls.print_cr("%s", use_lcp_match ? " (with longest common prefix substitution)" : "");
 760     ls.print("- expected : '");
 761     print_dumptime_classpath(ls, index_start, index_end, use_lcp_match, _dumptime_lcp_len, runtime_lcp, runtime_lcp_len);
 762     ls.print_cr("'");
 763     ls.print("- actual   : '");
 764     runtime_css.print(&ls);
 765     ls.print_cr("'");
 766   }
 767 
 768   runtime_css.start();
 769   for (int i = index_start; i < index_end; i++) {
 770     ResourceMark rm;
 771     const AOTClassLocation* cs = class_location_at(i);
 772     const char* effective_dumptime_path = cs->path();
 773     if (use_lcp_match && _dumptime_lcp_len > 0) {
 774       effective_dumptime_path = substitute(effective_dumptime_path, _dumptime_lcp_len, runtime_lcp, runtime_lcp_len);
 775     }
 776 
 777     log_info(class, path)("Checking '%s' %s%s", effective_dumptime_path, cs->file_type_string(),
 778                           cs->from_cpattr() ? " (from JAR manifest ClassPath attribute)" : "");
 779     if (!cs->from_cpattr() && file_exists(effective_dumptime_path)) {
 780       if (!runtime_css.has_next()) {
 781         log_warning(cds)("%s classpath has fewer elements than expected", which);
 782         return false;
 783       }
 784       const char* runtime_path = runtime_css.get_next();
 785       while (!file_exists(runtime_path) && runtime_css.has_next()) {
 786         runtime_path = runtime_css.get_next();
 787       }
 788       if (!os::same_files(effective_dumptime_path, runtime_path)) {
 789         log_warning(cds)("The name of %s classpath [%d] does not match: expected '%s', got '%s'",
 790                          which, runtime_css.current(), effective_dumptime_path, runtime_path);
 791         return false;
 792       }
 793     }
 794 
 795     if (!cs->check(effective_dumptime_path, has_aot_linked_classes)) {
 796       return false;
 797     }
 798   }
 799 
 800   // Check if the runtime boot classpath has more entries than the one stored in the archive and if the app classpath
 801   // or the module path requires validation.
 802   if (is_boot_classpath && runtime_css.has_next() && (need_to_check_app_classpath() || num_module_paths() > 0)) {
 803     // the check passes if all the extra runtime boot classpath entries are non-existent
 804     if (check_paths_existence(runtime_css)) {
 805       log_warning(cds)("boot classpath is longer than expected");
 806       return false;
 807     }
 808   }
 809 
 810   return true;
 811 }
 812 
 813 bool AOTClassLocationConfig::file_exists(const char* filename) const{
 814   struct stat st;
 815   return (os::stat(filename, &st) == 0 && st.st_size > 0);
 816 }
 817 
 818 bool AOTClassLocationConfig::check_paths_existence(ClassLocationStream& runtime_css) const {
 819   bool exist = false;
 820   while (runtime_css.has_next()) {
 821     const char* path = runtime_css.get_next();
 822     if (file_exists(path)) {
 823       exist = true;
 824       break;
 825     }
 826   }
 827   return exist;
 828 }
 829 
 830 bool AOTClassLocationConfig::check_module_paths(bool has_aot_linked_classes, int index_start, int index_end,
 831                                                 ClassLocationStream& runtime_css,
 832                                                 bool* has_extra_module_paths) const {
 833   if (index_start >= index_end && runtime_css.is_empty()) { // nothing to check
 834     return true;
 835   }
 836 
 837   ResourceMark rm;
 838 
 839   LogTarget(Info, class, path) lt;
 840   if (lt.is_enabled()) {
 841     LogStream ls(lt);
 842     ls.print_cr("Checking module paths");
 843     ls.print("- expected : '");
 844     print_dumptime_classpath(ls, index_start, index_end, false, 0, nullptr, 0);
 845     ls.print_cr("'");
 846     ls.print("- actual   : '");
 847     runtime_css.print(&ls);
 848     ls.print_cr("'");
 849   }
 850 
 851   // Make sure all the dumptime module paths exist and are unchanged
 852   for (int i = index_start; i < index_end; i++) {
 853     const AOTClassLocation* cs = class_location_at(i);
 854     const char* dumptime_path = cs->path();
 855 
 856     assert(!cs->from_cpattr(), "not applicable for module path");
 857     log_info(class, path)("Checking '%s' %s", dumptime_path, cs->file_type_string());
 858 
 859     if (!cs->check(dumptime_path, has_aot_linked_classes)) {
 860       return false;
 861     }
 862   }
 863 
 864   // We allow runtime_css to be a superset of the module paths specified in dumptime. E.g.,
 865   // Dumptime:    A:C
 866   // Runtime:     A:B:C
 867   runtime_css.start();
 868   for (int i = index_start; i < index_end; i++) {
 869     const AOTClassLocation* cs = class_location_at(i);
 870     const char* dumptime_path = cs->path();
 871 
 872     while (true) {
 873       if (!runtime_css.has_next()) {
 874         log_warning(cds)("module path has fewer elements than expected");
 875         *has_extra_module_paths = true;
 876         return true;
 877       }
 878       // Both this->class_locations() and runtime_css are alphabetically sorted. Skip
 879       // items in runtime_css until we see dumptime_path.
 880       const char* runtime_path = runtime_css.get_next();
 881       if (!os::same_files(dumptime_path, runtime_path)) {
 882         *has_extra_module_paths = true;
 883         return true;
 884       } else {
 885         break;
 886       }
 887     }
 888   }
 889 
 890   if (runtime_css.has_next()) {
 891     *has_extra_module_paths = true;
 892   }
 893 
 894   return true;
 895 }
 896 
 897 void AOTClassLocationConfig::print_dumptime_classpath(LogStream& ls, int index_start, int index_end,
 898                                                       bool do_substitute, size_t remove_prefix_len,
 899                                                       const char* prepend, size_t prepend_len) const {
 900   const char* sep = "";
 901   for (int i = index_start; i < index_end; i++) {
 902     ResourceMark rm;
 903     const AOTClassLocation* cs = class_location_at(i);
 904     const char* path = cs->path();
 905     if (!cs->from_cpattr()) {
 906       ls.print("%s", sep);
 907       if (do_substitute) {
 908         path = substitute(path, remove_prefix_len, prepend, prepend_len);
 909       }
 910       ls.print("%s", path);
 911       sep = os::path_separator();
 912     }
 913   }
 914 }
 915 
 916 // Returned path is resource-allocated
 917 const char* AOTClassLocationConfig::substitute(const char* path,         // start with this path (which was recorded from dump time)
 918                                                size_t remove_prefix_len, // remove this number of chars from the beginning
 919                                                const char* prepend,      // prepend this string
 920                                                size_t prepend_len) {     // length of the prepended string
 921   size_t len = strlen(path);
 922   assert(len > remove_prefix_len, "sanity");
 923   assert(prepend_len == strlen(prepend), "sanity");
 924   len -= remove_prefix_len;
 925   len += prepend_len;
 926 
 927   char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
 928   int n = os::snprintf(buf, len + 1, "%s%s", prepend, path + remove_prefix_len);
 929   assert(size_t(n) == len, "sanity");
 930 
 931   return buf;
 932 }
 933 
 934 // For performance, we avoid using LCP match if there's at least one
 935 // AOTClassLocation can be matched exactly: this means all other AOTClassLocations must be
 936 // matched exactly.
 937 bool AOTClassLocationConfig::need_lcp_match(AllClassLocationStreams& all_css) const {
 938   if (app_cp_end_index() == boot_cp_start_index()) {
 939     // No need to use lcp-match when there are no boot/app paths.
 940     // TODO: LCP-match not yet supported for modules.
 941     return false;
 942   }
 943 
 944   if (need_lcp_match_helper(boot_cp_start_index(), boot_cp_end_index(), all_css.boot_cp()) &&
 945       need_lcp_match_helper(app_cp_start_index(), app_cp_end_index(), all_css.app_cp())) {
 946     return true;
 947   } else {
 948     return false;
 949   }
 950 }
 951 
 952 bool AOTClassLocationConfig::need_lcp_match_helper(int start, int end, ClassLocationStream& css) const {
 953   int i = start;
 954   for (css.start(); i < end && css.has_next(); ) {
 955     const AOTClassLocation* cs = class_location_at(i++);
 956     const char* runtime_path = css.get_next();
 957     if (cs->must_exist() && os::same_files(cs->path(), runtime_path)) {
 958       // Most likely, we will come to here at the first iteration.
 959       return false;
 960     }
 961   }
 962   return true;
 963 }
 964 
 965 bool AOTClassLocationConfig::validate(bool has_aot_linked_classes, bool* has_extra_module_paths) const {
 966   ResourceMark rm;
 967   AllClassLocationStreams all_css;
 968 
 969   const char* jrt = ClassLoader::get_jrt_entry()->name();
 970   bool success = class_location_at(0)->check(jrt, has_aot_linked_classes);
 971   log_info(class, path)("Modules image %s validation: %s", jrt, success ? "passed" : "failed");
 972   if (!success) {
 973     return false;
 974   }
 975   if (class_locations()->length() == 1) {
 976     if ((module_path_start_index() >= module_path_end_index()) && Arguments::get_property("jdk.module.path") != nullptr) {
 977       *has_extra_module_paths = true;
 978     } else {
 979       *has_extra_module_paths = false;
 980     }
 981   } else {
 982     bool use_lcp_match = need_lcp_match(all_css);
 983     const char* runtime_lcp;
 984     size_t runtime_lcp_len;
 985 
 986     log_info(class, path)("Longest common prefix substitution in boot/app classpath matching: %s",
 987                           use_lcp_match ? "yes" : "no");
 988     if (use_lcp_match) {
 989       runtime_lcp = find_lcp(all_css.boot_and_app_cp(), runtime_lcp_len);
 990       log_info(class, path)("Longest common prefix: %s (%zu chars)", runtime_lcp, runtime_lcp_len);
 991     } else {
 992       runtime_lcp = nullptr;
 993       runtime_lcp_len = 0;
 994     }
 995 
 996     success = check_classpaths(true, has_aot_linked_classes, boot_cp_start_index(), boot_cp_end_index(), all_css.boot_cp(),
 997                                use_lcp_match, runtime_lcp, runtime_lcp_len);
 998     log_info(class, path)("Archived boot classpath validation: %s", success ? "passed" : "failed");
 999 
1000     if (success && need_to_check_app_classpath()) {
1001       success = check_classpaths(false, has_aot_linked_classes, app_cp_start_index(), app_cp_end_index(), all_css.app_cp(),
1002                                  use_lcp_match, runtime_lcp, runtime_lcp_len);
1003       log_info(class, path)("Archived app classpath validation: %s", success ? "passed" : "failed");
1004     }
1005 
1006     if (success) {
1007       success = check_module_paths(has_aot_linked_classes, module_path_start_index(), module_path_end_index(),
1008                                    all_css.module_path(), has_extra_module_paths);
1009       log_info(class, path)("Archived module path validation: %s%s", success ? "passed" : "failed",
1010                             (*has_extra_module_paths) ? " (extra module paths found)" : "");
1011     }
1012 
1013     if (runtime_lcp_len > 0) {
1014       os::free((void*)runtime_lcp);
1015     }
1016   }
1017 
1018   if (success) {
1019     _runtime_instance = this;
1020   } else {
1021     const char* mismatch_msg = "shared class paths mismatch";
1022     const char* hint_msg = log_is_enabled(Info, class, path) ?
1023         "" : " (hint: enable -Xlog:class+path=info to diagnose the failure)";
1024     if (RequireSharedSpaces && !PrintSharedArchiveAndExit) {
1025       if (CDSConfig::is_dumping_final_static_archive()) {
1026         log_error(cds)("class path and/or module path are not compatible with the "
1027                        "ones specified when the AOTConfiguration file was recorded%s", hint_msg);
1028         vm_exit_during_initialization("Unable to use create AOT cache.", nullptr);
1029       } else {
1030         log_error(cds)("%s%s", mismatch_msg, hint_msg);
1031         MetaspaceShared::unrecoverable_loading_error();
1032       }
1033     } else {
1034       log_warning(cds)("%s%s", mismatch_msg, hint_msg);
1035     }
1036   }
1037   return success;
1038 }