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/cds_globals.hpp"
 27 #include "cds/cdsConfig.hpp"
 28 #include "cds/dynamicArchive.hpp"
 29 #include "cds/filemap.hpp"
 30 #include "cds/heapShared.hpp"
 31 #include "classfile/classFileParser.hpp"
 32 #include "classfile/classLoader.inline.hpp"
 33 #include "classfile/classLoaderExt.hpp"
 34 #include "classfile/classLoaderData.inline.hpp"
 35 #include "classfile/classLoadInfo.hpp"
 36 #include "classfile/klassFactory.hpp"
 37 #include "classfile/modules.hpp"
 38 #include "classfile/systemDictionary.hpp"
 39 #include "classfile/vmSymbols.hpp"
 40 #include "gc/shared/collectedHeap.hpp"
 41 #include "logging/log.hpp"
 42 #include "memory/allocation.inline.hpp"
 43 #include "memory/resourceArea.hpp"
 44 #include "oops/instanceKlass.hpp"
 45 #include "oops/klass.inline.hpp"
 46 #include "oops/oop.inline.hpp"
 47 #include "oops/symbol.hpp"
 48 #include "runtime/arguments.hpp"
 49 #include "runtime/handles.inline.hpp"
 50 #include "runtime/java.hpp"
 51 #include "runtime/os.hpp"
 52 #include "utilities/checkedCast.hpp"
 53 #include "utilities/stringUtils.hpp"
 54 
 55 jshort ClassLoaderExt::_app_class_paths_start_index = ClassLoaderExt::max_classpath_index;
 56 jshort ClassLoaderExt::_app_module_paths_start_index = ClassLoaderExt::max_classpath_index;
 57 jshort ClassLoaderExt::_max_used_path_index = 0;
 58 int ClassLoaderExt::_num_module_paths = 0;
 59 bool ClassLoaderExt::_has_app_classes = false;
 60 bool ClassLoaderExt::_has_platform_classes = false;
 61 bool ClassLoaderExt::_has_non_jar_in_classpath = false;
 62 int ClassLoaderExt::_app_class_exclusion_start_path_index = INT_MAX;
 63 
 64 void ClassLoaderExt::append_boot_classpath(ClassPathEntry* new_entry) {
 65   if (CDSConfig::is_using_archive()) {
 66     warning("Sharing is only supported for boot loader classes because bootstrap classpath has been appended");
 67     FileMapInfo::current_info()->set_has_platform_or_app_classes(false);
 68     if (DynamicArchive::is_mapped()) {
 69       FileMapInfo::dynamic_info()->set_has_platform_or_app_classes(false);
 70     }
 71   }
 72   ClassLoader::add_to_boot_append_entries(new_entry);
 73 }
 74 
 75 void ClassLoaderExt::setup_app_search_path(JavaThread* current) {
 76   assert(CDSConfig::is_dumping_archive(), "sanity");
 77   int start_index = ClassLoader::num_boot_classpath_entries();
 78   _app_class_paths_start_index = checked_cast<jshort>(start_index);
 79   char* app_class_path = os::strdup_check_oom(Arguments::get_appclasspath(), mtClass);
 80 
 81   if (strcmp(app_class_path, ".") == 0) {
 82     // This doesn't make any sense, even for AppCDS, so let's skip it. We
 83     // don't want to throw an error here because -cp "." is usually assigned
 84     // by the launcher when classpath is not specified.
 85     trace_class_path("app loader class path (skipped)=", app_class_path);
 86   } else {
 87     trace_class_path("app loader class path=", app_class_path);
 88     ClassLoader::setup_app_search_path(current, app_class_path);
 89   }
 90 
 91   os::free(app_class_path);
 92 }
 93 
 94 int ClassLoaderExt::compare_module_names(const char** p1, const char** p2) {
 95   return strcmp(*p1, *p2);
 96 }
 97 
 98 void ClassLoaderExt::process_module_table(JavaThread* current, ModuleEntryTable* met) {
 99   ResourceMark rm(current);
100   GrowableArray<const char*>* module_paths = new GrowableArray<const char*>(5);
101 
102   class ModulePathsGatherer : public ModuleClosure {
103     JavaThread* _current;
104     GrowableArray<const char*>* _module_paths;
105    public:
106     ModulePathsGatherer(JavaThread* current, GrowableArray<const char*>* module_paths) :
107       _current(current), _module_paths(module_paths) {}
108     void do_module(ModuleEntry* m) {
109       if (m->location() == nullptr) {
110         // This is a dynamic generated module (which we loaded from the static archive) for supporting
111         // dynamic proxies. We don't archive any other such modules.
112         // No need to include such modules in _module_path.
113         assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
114         assert(Modules::is_dynamic_proxy_module(m), "must be");
115         if (log_is_enabled(Info, cds, dynamic, proxy)) {
116           ResourceMark rm;
117           log_info(cds, dynamic, proxy)("Archived dynamic module: %s", m->name()->as_C_string());
118         }
119         return;
120       }
121       char* uri = m->location()->as_C_string();
122       if (strncmp(uri, "file:", 5) == 0) {
123         char* path = ClassLoader::uri_to_path(uri);
124         extract_jar_files_from_path(path, _module_paths);
125       }
126     }
127   };
128 
129   ModulePathsGatherer gatherer(current, module_paths);
130   {
131     MutexLocker ml(Module_lock);
132     met->modules_do(&gatherer);
133   }
134 
135   // Sort the module paths before storing into CDS archive for simpler
136   // checking at runtime.
137   module_paths->sort(compare_module_names);
138 
139   for (int i = 0; i < module_paths->length(); i++) {
140     ClassLoader::setup_module_search_path(current, module_paths->at(i));
141   }
142 }
143 
144 void ClassLoaderExt::setup_module_paths(JavaThread* current) {
145   assert(CDSConfig::is_dumping_archive(), "sanity");
146   int start_index = ClassLoader::num_boot_classpath_entries() +
147                     ClassLoader::num_app_classpath_entries();
148   _app_module_paths_start_index = checked_cast<jshort>(start_index);
149   Handle system_class_loader (current, SystemDictionary::java_system_loader());
150   ModuleEntryTable* met = Modules::get_module_entry_table(system_class_loader);
151   process_module_table(current, met);
152 }
153 
154 bool ClassLoaderExt::has_jar_suffix(const char* filename) {
155   // In jdk.internal.module.ModulePath.readModule(), it checks for the ".jar" suffix.
156   // Performing the same check here.
157   const char* dot = strrchr(filename, '.');
158   if (dot != nullptr && strcmp(dot + 1, "jar") == 0) {
159     return true;
160   }
161   return false;
162 }
163 
164 void ClassLoaderExt::extract_jar_files_from_path(const char* path, GrowableArray<const char*>* module_paths) {
165   DIR* dirp = os::opendir(path);
166   if (dirp == nullptr && errno == ENOTDIR && has_jar_suffix(path)) {
167     module_paths->append(path);
168   } else {
169     if (dirp != nullptr) {
170       struct dirent* dentry;
171       while ((dentry = os::readdir(dirp)) != nullptr) {
172         const char* file_name = dentry->d_name;
173         if (has_jar_suffix(file_name)) {
174           size_t full_name_len = strlen(path) + strlen(file_name) + strlen(os::file_separator()) + 1;
175           char* full_name = NEW_RESOURCE_ARRAY(char, full_name_len);
176           int n = os::snprintf(full_name, full_name_len, "%s%s%s", path, os::file_separator(), file_name);
177           assert((size_t)n == full_name_len - 1, "Unexpected number of characters in string");
178           module_paths->append(full_name);
179         }
180       }
181       os::closedir(dirp);
182     }
183   }
184 }
185 
186 char* ClassLoaderExt::read_manifest(JavaThread* current, ClassPathEntry* entry,
187                                     jint *manifest_size, bool clean_text) {
188   const char* name = "META-INF/MANIFEST.MF";
189   char* manifest;
190   jint size;
191 
192   assert(entry->is_jar_file(), "must be");
193   manifest = (char*) ((ClassPathZipEntry*)entry )->open_entry(current, name, &size, true);
194 
195   if (manifest == nullptr) { // No Manifest
196     *manifest_size = 0;
197     return nullptr;
198   }
199 
200 
201   if (clean_text) {
202     // See http://docs.oracle.com/javase/6/docs/technotes/guides/jar/jar.html#JAR%20Manifest
203     // (1): replace all CR/LF and CR with LF
204     StringUtils::replace_no_expand(manifest, "\r\n", "\n");
205 
206     // (2) remove all new-line continuation (remove all "\n " substrings)
207     StringUtils::replace_no_expand(manifest, "\n ", "");
208   }
209 
210   *manifest_size = (jint)strlen(manifest);
211   return manifest;
212 }
213 
214 char* ClassLoaderExt::get_class_path_attr(const char* jar_path, char* manifest, jint manifest_size) {
215   const char* tag = "Class-Path: ";
216   const int tag_len = (int)strlen(tag);
217   char* found = nullptr;
218   char* line_start = manifest;
219   char* end = manifest + manifest_size;
220 
221   assert(*end == 0, "must be nul-terminated");
222 
223   while (line_start < end) {
224     char* line_end = strchr(line_start, '\n');
225     if (line_end == nullptr) {
226       // JAR spec require the manifest file to be terminated by a new line.
227       break;
228     }
229     if (strncmp(tag, line_start, tag_len) == 0) {
230       if (found != nullptr) {
231         // Same behavior as jdk/src/share/classes/java/util/jar/Attributes.java
232         // If duplicated entries are found, the last one is used.
233         log_warning(cds)("Warning: Duplicate name in Manifest: %s.\n"
234                       "Ensure that the manifest does not have duplicate entries, and\n"
235                       "that blank lines separate individual sections in both your\n"
236                       "manifest and in the META-INF/MANIFEST.MF entry in the jar file:\n%s\n", tag, jar_path);
237       }
238       found = line_start + tag_len;
239       assert(found <= line_end, "sanity");
240       *line_end = '\0';
241     }
242     line_start = line_end + 1;
243   }
244   return found;
245 }
246 
247 void ClassLoaderExt::process_jar_manifest(JavaThread* current, ClassPathEntry* entry) {
248   ResourceMark rm(current);
249   jint manifest_size;
250   char* manifest = read_manifest(current, entry, &manifest_size);
251 
252   if (manifest == nullptr) {
253     return;
254   }
255 
256   if (strstr(manifest, "Extension-List:") != nullptr) {
257     vm_exit_during_cds_dumping(err_msg("-Xshare:dump does not support Extension-List in JAR manifest: %s", entry->name()));
258   }
259 
260   char* cp_attr = get_class_path_attr(entry->name(), manifest, manifest_size);
261 
262   if (cp_attr != nullptr && strlen(cp_attr) > 0) {
263     trace_class_path("found Class-Path: ", cp_attr);
264 
265     char sep = os::file_separator()[0];
266     const char* dir_name = entry->name();
267     const char* dir_tail = strrchr(dir_name, sep);
268 #ifdef _WINDOWS
269     // On Windows, we also support forward slash as the file separator when locating entries in the classpath entry.
270     const char* dir_tail2 = strrchr(dir_name, '/');
271     if (dir_tail == nullptr) {
272       dir_tail = dir_tail2;
273     } else if (dir_tail2 != nullptr && dir_tail2 > dir_tail) {
274       dir_tail = dir_tail2;
275     }
276 #endif
277     int dir_len;
278     if (dir_tail == nullptr) {
279       dir_len = 0;
280     } else {
281       dir_len = pointer_delta_as_int(dir_tail, dir_name) + 1;
282     }
283 
284     // Split the cp_attr by spaces, and add each file
285     char* file_start = cp_attr;
286     char* end = file_start + strlen(file_start);
287 
288     while (file_start < end) {
289       char* file_end = strchr(file_start, ' ');
290       if (file_end != nullptr) {
291         *file_end = 0;
292         file_end += 1;
293       } else {
294         file_end = end;
295       }
296 
297       size_t name_len = strlen(file_start);
298       if (name_len > 0) {
299         ResourceMark rm(current);
300         size_t libname_len = dir_len + name_len;
301         char* libname = NEW_RESOURCE_ARRAY(char, libname_len + 1);
302         int n = os::snprintf(libname, libname_len + 1, "%.*s%s", dir_len, dir_name, file_start);
303         assert((size_t)n == libname_len, "Unexpected number of characters in string");
304         if (ClassLoader::update_class_path_entry_list(current, libname, true, false, true /* from_class_path_attr */)) {
305           trace_class_path("library = ", libname);
306         } else {
307           trace_class_path("library (non-existent) = ", libname);
308           FileMapInfo::record_non_existent_class_path_entry(libname);
309         }
310       }
311 
312       file_start = file_end;
313     }
314   }
315 }
316 
317 void ClassLoaderExt::setup_search_paths(JavaThread* current) {
318   ClassLoaderExt::setup_app_search_path(current);
319 }
320 
321 void ClassLoaderExt::record_result(const s2 classpath_index, InstanceKlass* result, bool redefined) {
322   assert(CDSConfig::is_dumping_archive(), "sanity");
323 
324   // We need to remember where the class comes from during dumping.
325   oop loader = result->class_loader();
326   s2 classloader_type = ClassLoader::BOOT_LOADER;
327   if (SystemDictionary::is_system_class_loader(loader)) {
328     classloader_type = ClassLoader::APP_LOADER;
329     ClassLoaderExt::set_has_app_classes();
330   } else if (SystemDictionary::is_platform_class_loader(loader)) {
331     classloader_type = ClassLoader::PLATFORM_LOADER;
332     ClassLoaderExt::set_has_platform_classes();
333   }
334   if (classpath_index > ClassLoaderExt::max_used_path_index()) {
335     ClassLoaderExt::set_max_used_path_index(classpath_index);
336   }
337   result->set_shared_classpath_index(classpath_index);
338   result->set_shared_class_loader_type(classloader_type);
339 #if INCLUDE_CDS_JAVA_HEAP
340   if (CDSConfig::is_dumping_heap() && AllowArchivingWithJavaAgent && classloader_type == ClassLoader::BOOT_LOADER &&
341       classpath_index < 0 && redefined) {
342     // When dumping the heap (which happens only during static dump), classes for the built-in
343     // loaders are always loaded from known locations (jimage, classpath or modulepath),
344     // so classpath_index should always be >= 0.
345     // The only exception is when a java agent is used during dump time (for testing
346     // purposes only). If a class is transformed by the agent, the CodeSource of
347     // this class may point to an unknown location. This may break heap object archiving,
348     // which requires all the boot classes to be from known locations. This is an
349     // uncommon scenario (even in test cases). Let's simply disable heap object archiving.
350     ResourceMark rm;
351     log_warning(cds)("CDS heap objects cannot be written because class %s maybe modified by ClassFileLoadHook.",
352                      result->external_name());
353     HeapShared::disable_writing();
354   }
355 #endif // INCLUDE_CDS_JAVA_HEAP
356   if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_dynamic_archive()) {
357     check_invalid_classpath_index(classpath_index, result);
358   }
359 }
360 
361 ClassPathEntry* ClassLoaderExt::get_class_path_entry(s2 classpath_index) {
362   if (classpath_index < 0) {
363     return nullptr;
364   }
365 
366   if (classpath_index == 0) {
367     assert(has_jrt_entry(), "CDS requires modules image");
368     return get_jrt_entry();
369   }
370 
371   // Iterate over -Xbootclasspath, if any;
372   int i = 0;
373   for (ClassPathEntry* cpe = first_append_entry(); cpe != nullptr; cpe = cpe->next()) {
374     i++;
375     if (i == classpath_index) {
376       return cpe;
377     }
378   }
379 
380   // Iterate over -cp, if any
381   for (ClassPathEntry* cpe = app_classpath_entries(); cpe != nullptr; cpe = cpe->next()) {
382     i++;
383     if (i == classpath_index) {
384       return cpe;
385     }
386   }
387 
388   // Iterate over --module-path, if any
389   for (ClassPathEntry* cpe = module_path_entries(); cpe != nullptr; cpe = cpe->next()) {
390     i++;
391     if (i == classpath_index) {
392       return cpe;
393     }
394   }
395 
396   return nullptr;
397 }
398 
399 // It's possible to use reflection+setAccessible to call into ClassLoader::defineClass() to
400 // pretend that a dynamically generated class comes from a JAR file in the classpath.
401 // Detect such classes and exclude them from the archive.
402 void ClassLoaderExt::check_invalid_classpath_index(s2 classpath_index, InstanceKlass* ik) {
403   ClassPathEntry *cpe = get_class_path_entry(classpath_index);
404   if (cpe != nullptr && cpe->is_jar_file()) {
405     ClassPathZipEntry *zip = (ClassPathZipEntry*)cpe;
406     JavaThread* current = JavaThread::current();
407     ResourceMark rm(current);
408     const char* const class_name = ik->name()->as_C_string();
409     const char* const file_name = file_name_for_class_name(class_name,
410                                                            ik->name()->utf8_length());
411     if (!zip->has_entry(current, file_name)) {
412       log_warning(cds)("class %s cannot be archived because it was not define from %s as claimed",
413                        class_name, zip->name());
414       ik->set_shared_classpath_index(-1);
415     }
416   }
417 }
418 
419 // -XX:CacheOnlyClassesIn=
420 bool ClassLoaderExt::should_be_excluded(InstanceKlass* k) {
421   int path_index = k->shared_classpath_index();
422   if (path_index >= _app_class_exclusion_start_path_index  && path_index < _app_module_paths_start_index) {
423     return true;
424   } else {
425     return false;
426   }
427 }
428