1 /*
  2  * Copyright (c) 2021, 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/cds_globals.hpp"
 26 #include "cds/classListWriter.hpp"
 27 #include "cds/lambdaFormInvokers.inline.hpp"
 28 #include "classfile/classFileStream.hpp"
 29 #include "classfile/classLoader.hpp"
 30 #include "classfile/classLoaderData.hpp"
 31 #include "classfile/classLoaderDataGraph.hpp"
 32 #include "classfile/moduleEntry.hpp"
 33 #include "classfile/systemDictionaryShared.hpp"
 34 #include "memory/resourceArea.hpp"
 35 #include "oops/constantPool.inline.hpp"
 36 #include "oops/instanceKlass.hpp"
 37 #include "runtime/mutexLocker.hpp"
 38 
 39 fileStream* ClassListWriter::_classlist_file = nullptr;
 40 
 41 void ClassListWriter::init() {
 42   // For -XX:DumpLoadedClassList=<file> option
 43   if (DumpLoadedClassList != nullptr) {
 44     const char* list_name = make_log_name(DumpLoadedClassList, nullptr);
 45     _classlist_file = new(mtInternal)
 46                          fileStream(list_name);
 47     _classlist_file->print_cr("# NOTE: Do not modify this file.");
 48     _classlist_file->print_cr("#");
 49     _classlist_file->print_cr("# This file is generated via the -XX:DumpLoadedClassList=<class_list_file> option");
 50     _classlist_file->print_cr("# and is used at CDS archive dump time (see -Xshare:dump).");
 51     _classlist_file->print_cr("#");
 52     FREE_C_HEAP_ARRAY(char, list_name);
 53   }
 54 }
 55 
 56 void ClassListWriter::write(const InstanceKlass* k, const ClassFileStream* cfs) {
 57   assert(is_enabled(), "must be");
 58 
 59   if (!ClassLoader::has_jrt_entry()) {
 60     log_warning(cds)("DumpLoadedClassList and CDS are not supported in exploded build");
 61     DumpLoadedClassList = nullptr;
 62     return;
 63   }
 64 
 65   ClassListWriter w;
 66   write_to_stream(k, w.stream(), cfs);
 67 }
 68 
 69 class ClassListWriter::IDTable : public ResourceHashtable<
 70   const InstanceKlass*, int,
 71   15889, // prime number
 72   AnyObj::C_HEAP> {};
 73 
 74 ClassListWriter::IDTable* ClassListWriter::_id_table = nullptr;
 75 int ClassListWriter::_total_ids = 0;
 76 
 77 int ClassListWriter::get_id(const InstanceKlass* k) {
 78   assert_locked();
 79   if (_id_table == nullptr) {
 80     _id_table = new (mtClass)IDTable();
 81   }
 82   bool created;
 83   int* v = _id_table->put_if_absent(k, &created);
 84   if (created) {
 85     *v = _total_ids++;
 86   }
 87   return *v;
 88 }
 89 
 90 bool ClassListWriter::has_id(const InstanceKlass* k) {
 91   assert_locked();
 92   if (_id_table != nullptr) {
 93     return _id_table->get(k) != nullptr;
 94   } else {
 95     return false;
 96   }
 97 }
 98 
 99 void ClassListWriter::handle_class_unloading(const InstanceKlass* klass) {
100   assert_locked();
101   if (_id_table != nullptr) {
102     _id_table->remove(klass);
103   }
104 }
105 
106 void ClassListWriter::write_to_stream(const InstanceKlass* k, outputStream* stream, const ClassFileStream* cfs) {
107   assert_locked();
108 
109   ClassLoaderData* loader_data = k->class_loader_data();
110   bool is_builtin_loader = SystemDictionaryShared::is_builtin_loader(loader_data);
111   if (!is_builtin_loader) {
112     // class may be loaded from shared archive
113     if (!k->is_shared()) {
114       if (cfs == nullptr || cfs->source() == nullptr) {
115         // CDS static dump only handles unregistered class with known source.
116         return;
117       }
118       if (strncmp(cfs->source(), "file:", 5) != 0) {
119         return;
120       }
121     } else {
122       // Shared unregistered classes are skipped since their real source are not recorded in shared space.
123       return;
124     }
125     if (!SystemDictionaryShared::add_unregistered_class(Thread::current(), (InstanceKlass*)k)) {
126       return;
127     }
128   }
129 
130   if (cfs != nullptr && cfs->source() != nullptr) {
131     if (strcmp(cfs->source(), "_ClassSpecializer_generateConcreteSpeciesCode") == 0) {
132       return;
133     }
134 
135     if (strncmp(cfs->source(), "__", 2) == 0) {
136       // generated class: __dynamic_proxy__, __JVM_LookupDefineClass__, etc
137       return;
138     }
139   }
140 
141   {
142     InstanceKlass* super = k->java_super();
143     if (super != nullptr && !has_id(super)) {
144       return;
145     }
146 
147     Array<InstanceKlass*>* interfaces = k->local_interfaces();
148     int len = interfaces->length();
149     for (int i = 0; i < len; i++) {
150       InstanceKlass* intf = interfaces->at(i);
151       if (!has_id(intf)) {
152         return;
153       }
154     }
155   }
156 
157   if (k->is_hidden()) {
158     return;
159   }
160 
161   if (k->module()->is_patched()) {
162     return;
163   }
164 
165   ResourceMark rm;
166   stream->print("%s id: %d", k->name()->as_C_string(), get_id(k));
167   if (!is_builtin_loader) {
168     InstanceKlass* super = k->java_super();
169     assert(super != nullptr, "must be");
170     stream->print(" super: %d", get_id(super));
171 
172     Array<InstanceKlass*>* interfaces = k->local_interfaces();
173     int len = interfaces->length();
174     if (len > 0) {
175       stream->print(" interfaces:");
176       for (int i = 0; i < len; i++) {
177         InstanceKlass* intf = interfaces->at(i);
178         stream->print(" %d", get_id(intf));
179       }
180     }
181 
182     // NB: the string following "source: " is not really a proper file name, but rather
183     // a truncated URI referring to a file. It must be decoded after reading.
184 #ifdef _WINDOWS
185     // "file:/C:/dir/foo.jar" -> "C:/dir/foo.jar"
186     stream->print(" source: %s", cfs->source() + 6);
187 #else
188     // "file:/dir/foo.jar" -> "/dir/foo.jar"
189     stream->print(" source: %s", cfs->source() + 5);
190 #endif
191   }
192 
193   stream->cr();
194   stream->flush();
195 }
196 
197 void ClassListWriter::delete_classlist() {
198   if (_classlist_file != nullptr) {
199     delete _classlist_file;
200   }
201 }
202 
203 class ClassListWriter::WriteResolveConstantsCLDClosure : public CLDClosure {
204 public:
205   void do_cld(ClassLoaderData* cld) {
206     for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
207       if (klass->is_instance_klass()) {
208         InstanceKlass* ik = InstanceKlass::cast(klass);
209         write_resolved_constants_for(ik);
210       }
211     }
212   }
213 };
214 
215 void ClassListWriter::write_resolved_constants() {
216   if (!is_enabled()) {
217     return;
218   }
219   MutexLocker lock(ClassLoaderDataGraph_lock);
220   MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag);
221 
222   WriteResolveConstantsCLDClosure closure;
223   ClassLoaderDataGraph::loaded_cld_do(&closure);
224 }
225 
226 void ClassListWriter::write_resolved_constants_for(InstanceKlass* ik) {
227   if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data()) ||
228       ik->is_hidden()) {
229     return;
230   }
231   if (LambdaFormInvokers::may_be_regenerated_class(ik->name())) {
232     return;
233   }
234   if (ik->name()->equals("jdk/internal/module/SystemModules$all")) {
235     // This class is regenerated during JDK build process, so the classlist
236     // may not match the version that's in the real jdk image.
237     return;
238   }
239 
240   if (!has_id(ik)) { // do not resolve CP for classes loaded by custom loaders.
241     return;
242   }
243 
244   ResourceMark rm;
245   ConstantPool* cp = ik->constants();
246   GrowableArray<bool> list(cp->length(), cp->length(), false);
247   bool print = false;
248 
249   for (int cp_index = 1; cp_index < cp->length(); cp_index++) { // Index 0 is unused
250     switch (cp->tag_at(cp_index).value()) {
251     case JVM_CONSTANT_Class:
252       {
253         Klass* k = cp->resolved_klass_at(cp_index);
254         if (k->is_instance_klass()) {
255           list.at_put(cp_index, true);
256           print = true;
257         }
258       }
259       break;
260     }
261   }
262 
263   if (cp->cache() != nullptr) {
264     Array<ResolvedIndyEntry>* indy_entries = cp->cache()->resolved_indy_entries();
265     if (indy_entries != nullptr) {
266       for (int i = 0; i < indy_entries->length(); i++) {
267         ResolvedIndyEntry* rie = indy_entries->adr_at(i);
268         int cp_index = rie->constant_pool_index();
269         if (rie->is_resolved()) {
270           list.at_put(cp_index, true);
271           print = true;
272         }
273       }
274     }
275 
276     Array<ResolvedFieldEntry>* field_entries = cp->cache()->resolved_field_entries();
277     if (field_entries != nullptr) {
278       for (int i = 0; i < field_entries->length(); i++) {
279         ResolvedFieldEntry* rfe = field_entries->adr_at(i);
280         if (rfe->is_resolved(Bytecodes::_getfield) ||
281             rfe->is_resolved(Bytecodes::_putfield)) {
282           list.at_put(rfe->constant_pool_index(), true);
283           print = true;
284         }
285       }
286     }
287 
288     Array<ResolvedMethodEntry>* method_entries = cp->cache()->resolved_method_entries();
289     if (method_entries != nullptr) {
290       for (int i = 0; i < method_entries->length(); i++) {
291         ResolvedMethodEntry* rme = method_entries->adr_at(i);
292         if (rme->is_resolved(Bytecodes::_invokevirtual) ||
293             rme->is_resolved(Bytecodes::_invokespecial) ||
294             rme->is_resolved(Bytecodes::_invokeinterface) ||
295             rme->is_resolved(Bytecodes::_invokehandle)) {
296           list.at_put(rme->constant_pool_index(), true);
297           print = true;
298         }
299       }
300     }
301   }
302 
303   if (print) {
304     outputStream* stream = _classlist_file;
305     stream->print("@cp %s", ik->name()->as_C_string());
306     for (int i = 0; i < list.length(); i++) {
307       if (list.at(i)) {
308         constantTag cp_tag = cp->tag_at(i).value();
309         assert(cp_tag.value() == JVM_CONSTANT_Class ||
310                cp_tag.value() == JVM_CONSTANT_Fieldref ||
311                cp_tag.value() == JVM_CONSTANT_Methodref||
312                cp_tag.value() == JVM_CONSTANT_InterfaceMethodref ||
313                cp_tag.value() == JVM_CONSTANT_InvokeDynamic, "sanity");
314         stream->print(" %d", i);
315       }
316     }
317     stream->cr();
318   }
319 }