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 bool ClassLoaderExt::_has_app_classes = false;
 59 bool ClassLoaderExt::_has_platform_classes = false;
 60 bool ClassLoaderExt::_has_non_jar_in_classpath = false;
 61 
 62 void ClassLoaderExt::append_boot_classpath(ClassPathEntry* new_entry) {
 63   if (CDSConfig::is_using_archive()) {
 64     warning("Sharing is only supported for boot loader classes because bootstrap classpath has been appended");
 65     FileMapInfo::current_info()->set_has_platform_or_app_classes(false);
 66     if (DynamicArchive::is_mapped()) {
 67       FileMapInfo::dynamic_info()->set_has_platform_or_app_classes(false);
 68     }
 69   }
 70   ClassLoader::add_to_boot_append_entries(new_entry);
 71 }
 72 
 73 void ClassLoaderExt::setup_app_search_path(JavaThread* current) {
 74   assert(CDSConfig::is_dumping_archive(), "sanity");
 75   int start_index = ClassLoader::num_boot_classpath_entries();
 76   _app_class_paths_start_index = checked_cast<jshort>(start_index);
 77   char* app_class_path = os::strdup_check_oom(Arguments::get_appclasspath(), mtClass);
 78 
 79   if (strcmp(app_class_path, ".") == 0) {
 80     // This doesn't make any sense, even for AppCDS, so let's skip it. We
 81     // don't want to throw an error here because -cp "." is usually assigned
 82     // by the launcher when classpath is not specified.
 83     trace_class_path("app loader class path (skipped)=", app_class_path);
 84   } else {
 85     trace_class_path("app loader class path=", app_class_path);
 86     ClassLoader::setup_app_search_path(current, app_class_path);
 87   }
 88 
 89   os::free(app_class_path);
 90 }
 91 
 92 void ClassLoaderExt::process_module_table(JavaThread* current, ModuleEntryTable* met) {
 93   ResourceMark rm(current);
 94   GrowableArray<char*>* module_paths = new GrowableArray<char*>(5);
 95 
 96   class ModulePathsGatherer : public ModuleClosure {
 97     JavaThread* _current;
 98     GrowableArray<char*>* _module_paths;
 99    public:
100     ModulePathsGatherer(JavaThread* current, GrowableArray<char*>* module_paths) :
101       _current(current), _module_paths(module_paths) {}
102     void do_module(ModuleEntry* m) {
103       if (m->location() == nullptr) {
104         // This is a dynamic generated module (which we loaded from the static archive) for supporting
105         // dynamic proxies. We don't archive any other such modules.
106         // No need to include such modules in _module_path.
107         assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
108         assert(Modules::is_dynamic_proxy_module(m), "must be");
109         if (log_is_enabled(Info, cds, dynamic, proxy)) {
110           ResourceMark rm;
111           log_info(cds, dynamic, proxy)("Archived dynamic module: %s", m->name()->as_C_string());
112         }
113         return;
114       }
115       char* path = m->location()->as_C_string();
116       if (strncmp(path, "file:", 5) == 0) {
117         path = ClassLoader::skip_uri_protocol(path);
118         char* path_copy = NEW_RESOURCE_ARRAY(char, strlen(path) + 1);
119         strcpy(path_copy, path);
120         _module_paths->append(path_copy);
121       }
122     }
123   };
124 
125   ModulePathsGatherer gatherer(current, module_paths);
126   {
127     MutexLocker ml(Module_lock);
128     met->modules_do(&gatherer);
129   }
130 
131   for (int i = 0; i < module_paths->length(); i++) {
132     ClassLoader::setup_module_search_path(current, module_paths->at(i));
133   }
134 }
135 
136 void ClassLoaderExt::setup_module_paths(JavaThread* current) {
137   assert(CDSConfig::is_dumping_archive(), "sanity");
138   int start_index = ClassLoader::num_boot_classpath_entries() +
139                     ClassLoader::num_app_classpath_entries();
140   _app_module_paths_start_index = checked_cast<jshort>(start_index);
141   Handle system_class_loader (current, SystemDictionary::java_system_loader());
142   ModuleEntryTable* met = Modules::get_module_entry_table(system_class_loader);
143   process_module_table(current, met);
144 }
145 
146 char* ClassLoaderExt::read_manifest(JavaThread* current, ClassPathEntry* entry,
147                                     jint *manifest_size, bool clean_text) {
148   const char* name = "META-INF/MANIFEST.MF";
149   char* manifest;
150   jint size;
151 
152   assert(entry->is_jar_file(), "must be");
153   manifest = (char*) ((ClassPathZipEntry*)entry )->open_entry(current, name, &size, true);
154 
155   if (manifest == nullptr) { // No Manifest
156     *manifest_size = 0;
157     return nullptr;
158   }
159 
160 
161   if (clean_text) {
162     // See http://docs.oracle.com/javase/6/docs/technotes/guides/jar/jar.html#JAR%20Manifest
163     // (1): replace all CR/LF and CR with LF
164     StringUtils::replace_no_expand(manifest, "\r\n", "\n");
165 
166     // (2) remove all new-line continuation (remove all "\n " substrings)
167     StringUtils::replace_no_expand(manifest, "\n ", "");
168   }
169 
170   *manifest_size = (jint)strlen(manifest);
171   return manifest;
172 }
173 
174 char* ClassLoaderExt::get_class_path_attr(const char* jar_path, char* manifest, jint manifest_size) {
175   const char* tag = "Class-Path: ";
176   const int tag_len = (int)strlen(tag);
177   char* found = nullptr;
178   char* line_start = manifest;
179   char* end = manifest + manifest_size;
180 
181   assert(*end == 0, "must be nul-terminated");
182 
183   while (line_start < end) {
184     char* line_end = strchr(line_start, '\n');
185     if (line_end == nullptr) {
186       // JAR spec require the manifest file to be terminated by a new line.
187       break;
188     }
189     if (strncmp(tag, line_start, tag_len) == 0) {
190       if (found != nullptr) {
191         // Same behavior as jdk/src/share/classes/java/util/jar/Attributes.java
192         // If duplicated entries are found, the last one is used.
193         log_warning(cds)("Warning: Duplicate name in Manifest: %s.\n"
194                       "Ensure that the manifest does not have duplicate entries, and\n"
195                       "that blank lines separate individual sections in both your\n"
196                       "manifest and in the META-INF/MANIFEST.MF entry in the jar file:\n%s\n", tag, jar_path);
197       }
198       found = line_start + tag_len;
199       assert(found <= line_end, "sanity");
200       *line_end = '\0';
201     }
202     line_start = line_end + 1;
203   }
204   return found;
205 }
206 
207 void ClassLoaderExt::process_jar_manifest(JavaThread* current, ClassPathEntry* entry) {
208   ResourceMark rm(current);
209   jint manifest_size;
210   char* manifest = read_manifest(current, entry, &manifest_size);
211 
212   if (manifest == nullptr) {
213     return;
214   }
215 
216   if (strstr(manifest, "Extension-List:") != nullptr) {
217     vm_exit_during_cds_dumping(err_msg("-Xshare:dump does not support Extension-List in JAR manifest: %s", entry->name()));
218   }
219 
220   char* cp_attr = get_class_path_attr(entry->name(), manifest, manifest_size);
221 
222   if (cp_attr != nullptr && strlen(cp_attr) > 0) {
223     trace_class_path("found Class-Path: ", cp_attr);
224 
225     char sep = os::file_separator()[0];
226     const char* dir_name = entry->name();
227     const char* dir_tail = strrchr(dir_name, sep);
228     int dir_len;
229     if (dir_tail == nullptr) {
230       dir_len = 0;
231     } else {
232       dir_len = pointer_delta_as_int(dir_tail, dir_name) + 1;
233     }
234 
235     // Split the cp_attr by spaces, and add each file
236     char* file_start = cp_attr;
237     char* end = file_start + strlen(file_start);
238 
239     while (file_start < end) {
240       char* file_end = strchr(file_start, ' ');
241       if (file_end != nullptr) {
242         *file_end = 0;
243         file_end += 1;
244       } else {
245         file_end = end;
246       }
247 
248       size_t name_len = strlen(file_start);
249       if (name_len > 0) {
250         ResourceMark rm(current);
251         size_t libname_len = dir_len + name_len;
252         char* libname = NEW_RESOURCE_ARRAY(char, libname_len + 1);
253         int n = os::snprintf(libname, libname_len + 1, "%.*s%s", dir_len, dir_name, file_start);
254         assert((size_t)n == libname_len, "Unexpected number of characters in string");
255         if (ClassLoader::update_class_path_entry_list(current, libname, true, false, true /* from_class_path_attr */)) {
256           trace_class_path("library = ", libname);
257         } else {
258           trace_class_path("library (non-existent) = ", libname);
259           FileMapInfo::record_non_existent_class_path_entry(libname);
260         }
261       }
262 
263       file_start = file_end;
264     }
265   }
266 }
267 
268 void ClassLoaderExt::setup_search_paths(JavaThread* current) {
269   ClassLoaderExt::setup_app_search_path(current);
270 }
271 
272 void ClassLoaderExt::record_result(const s2 classpath_index, InstanceKlass* result, bool redefined) {
273   assert(CDSConfig::is_dumping_archive(), "sanity");
274 
275   // We need to remember where the class comes from during dumping.
276   oop loader = result->class_loader();
277   s2 classloader_type = ClassLoader::BOOT_LOADER;
278   if (SystemDictionary::is_system_class_loader(loader)) {
279     classloader_type = ClassLoader::APP_LOADER;
280     ClassLoaderExt::set_has_app_classes();
281   } else if (SystemDictionary::is_platform_class_loader(loader)) {
282     classloader_type = ClassLoader::PLATFORM_LOADER;
283     ClassLoaderExt::set_has_platform_classes();
284   }
285   if (classpath_index > ClassLoaderExt::max_used_path_index()) {
286     ClassLoaderExt::set_max_used_path_index(classpath_index);
287   }
288   result->set_shared_classpath_index(classpath_index);
289   result->set_shared_class_loader_type(classloader_type);
290 #if INCLUDE_CDS_JAVA_HEAP
291   if (CDSConfig::is_dumping_heap() && AllowArchivingWithJavaAgent && classloader_type == ClassLoader::BOOT_LOADER &&
292       classpath_index < 0 && redefined) {
293     // When dumping the heap (which happens only during static dump), classes for the built-in
294     // loaders are always loaded from known locations (jimage, classpath or modulepath),
295     // so classpath_index should always be >= 0.
296     // The only exception is when a java agent is used during dump time (for testing
297     // purposes only). If a class is transformed by the agent, the CodeSource of
298     // this class may point to an unknown location. This may break heap object archiving,
299     // which requires all the boot classes to be from known locations. This is an
300     // uncommon scenario (even in test cases). Let's simply disable heap object archiving.
301     ResourceMark rm;
302     log_warning(cds)("CDS heap objects cannot be written because class %s maybe modified by ClassFileLoadHook.",
303                      result->external_name());
304     HeapShared::disable_writing();
305   }
306 #endif // INCLUDE_CDS_JAVA_HEAP
307   if (CDSConfig::is_dumping_preimage_static_archive() || CDSConfig::is_dumping_dynamic_archive()) {
308     check_invalid_classpath_index(classpath_index, result);
309   }
310 }
311 
312 ClassPathEntry* ClassLoaderExt::get_class_path_entry(s2 classpath_index) {
313   if (classpath_index < 0) {
314     return nullptr;
315   }
316 
317   if (classpath_index == 0) {
318     assert(has_jrt_entry(), "CDS requires modules image");
319     return get_jrt_entry();
320   }
321 
322   // Iterate over -Xbootclasspath, if any;
323   int i = 0;
324   for (ClassPathEntry* cpe = first_append_entry(); cpe != nullptr; cpe = cpe->next()) {
325     i++;
326     if (i == classpath_index) {
327       return cpe;
328     }
329   }
330 
331   // Iterate over -cp, if any
332   for (ClassPathEntry* cpe = app_classpath_entries(); cpe != nullptr; cpe = cpe->next()) {
333     i++;
334     if (i == classpath_index) {
335       return cpe;
336     }
337   }
338 
339   // Iterate over --module-path, if any
340   for (ClassPathEntry* cpe = module_path_entries(); cpe != nullptr; cpe = cpe->next()) {
341     i++;
342     if (i == classpath_index) {
343       return cpe;
344     }
345   }
346 
347   return nullptr;
348 }
349 
350 // It's possible to use reflection+setAccessible to call into ClassLoader::defineClass() to
351 // pretend that a dynamically generated class comes from a JAR file in the classpath.
352 // Detect such classes and exclude them from the archive.
353 void ClassLoaderExt::check_invalid_classpath_index(s2 classpath_index, InstanceKlass* ik) {
354   ClassPathEntry *cpe = get_class_path_entry(classpath_index);
355   if (cpe != nullptr && cpe->is_jar_file()) {
356     ClassPathZipEntry *zip = (ClassPathZipEntry*)cpe;
357     JavaThread* current = JavaThread::current();
358     ResourceMark rm(current);
359     const char* const class_name = ik->name()->as_C_string();
360     const char* const file_name = file_name_for_class_name(class_name,
361                                                            ik->name()->utf8_length());
362     if (!zip->has_entry(current, file_name)) {
363       log_warning(cds)("class %s cannot be archived because it was not define from %s as claimed",
364                        class_name, zip->name());
365       ik->set_shared_classpath_index(-1);
366     }
367   }
368 }
--- EOF ---