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/aotConstantPoolResolver.hpp"
26 #include "cds/cds_globals.hpp"
27 #include "cds/classListParser.hpp"
28 #include "cds/classListWriter.hpp"
29 #include "cds/lambdaFormInvokers.inline.hpp"
30 #include "classfile/classFileStream.hpp"
31 #include "classfile/classLoader.hpp"
32 #include "classfile/classLoaderData.hpp"
33 #include "classfile/classLoaderDataGraph.hpp"
34 #include "classfile/moduleEntry.hpp"
35 #include "classfile/symbolTable.hpp"
36 #include "classfile/systemDictionaryShared.hpp"
37 #include "memory/resourceArea.hpp"
38 #include "oops/constantPool.inline.hpp"
39 #include "oops/instanceKlass.hpp"
40 #include "runtime/javaCalls.hpp"
41 #include "runtime/mutexLocker.hpp"
42
43 fileStream* ClassListWriter::_classlist_file = nullptr;
44
45 void ClassListWriter::init() {
46 // For -XX:DumpLoadedClassList=<file> option
47 if (DumpLoadedClassList != nullptr) {
48 const char* list_name = make_log_name(DumpLoadedClassList, nullptr);
49 _classlist_file = new(mtInternal)
50 fileStream(list_name);
51 _classlist_file->print_cr("# NOTE: Do not modify this file.");
52 _classlist_file->print_cr("#");
53 _classlist_file->print_cr("# This file is generated via the -XX:DumpLoadedClassList=<class_list_file> option");
54 _classlist_file->print_cr("# and is used at CDS archive dump time (see -Xshare:dump).");
55 _classlist_file->print_cr("#");
56 FREE_C_HEAP_ARRAY(char, list_name);
57 }
58 }
59
60 void ClassListWriter::write(const InstanceKlass* k, const ClassFileStream* cfs) {
61 assert(is_enabled(), "must be");
62
63 if (!ClassLoader::has_jrt_entry()) {
64 log_warning(aot)("DumpLoadedClassList and CDS are not supported in exploded build");
65 DumpLoadedClassList = nullptr;
66 return;
67 }
68
69 ClassListWriter w;
70 write_to_stream(k, w.stream(), cfs);
71 }
72
73 class ClassListWriter::IDTable : public HashTable<
74 const InstanceKlass*, int,
75 15889, // prime number
76 AnyObj::C_HEAP> {};
77
78 ClassListWriter::IDTable* ClassListWriter::_id_table = nullptr;
79 int ClassListWriter::_total_ids = 0;
80
81 int ClassListWriter::get_id(const InstanceKlass* k) {
82 assert_locked();
83 if (_id_table == nullptr) {
84 _id_table = new (mtClass)IDTable();
85 }
86 bool created;
87 int* v = _id_table->put_if_absent(k, &created);
88 if (created) {
89 *v = _total_ids++;
90 }
91 return *v;
92 }
93
94 bool ClassListWriter::has_id(const InstanceKlass* k) {
95 assert_locked();
96 if (_id_table != nullptr) {
97 return _id_table->get(k) != nullptr;
98 } else {
99 return false;
100 }
101 }
102
103 void ClassListWriter::handle_class_unloading(const InstanceKlass* klass) {
104 assert_locked();
105 if (_id_table != nullptr) {
106 _id_table->remove(klass);
107 }
108 }
109
110 void ClassListWriter::write_to_stream(const InstanceKlass* k, outputStream* stream, const ClassFileStream* cfs) {
111 assert_locked();
112
113 ClassLoaderData* loader_data = k->class_loader_data();
114 bool is_builtin_loader = SystemDictionaryShared::is_builtin_loader(loader_data);
115 if (!is_builtin_loader) {
116 // class may be loaded from shared archive
117 if (!k->in_aot_cache()) {
118 if (cfs == nullptr || cfs->source() == nullptr) {
119 // CDS static dump only handles unregistered class with known source.
120 return;
121 }
122 if (strncmp(cfs->source(), "file:", 5) != 0) {
123 return;
124 }
125 } else {
126 // Shared unregistered classes are skipped since their real source are not recorded in shared space.
127 return;
128 }
129 if (!SystemDictionaryShared::add_unregistered_class(Thread::current(), (InstanceKlass*)k)) {
130 return;
131 }
132 }
133
134 if (cfs != nullptr && cfs->source() != nullptr) {
135 if (strcmp(cfs->source(), "_ClassSpecializer_generateConcreteSpeciesCode") == 0) {
136 return;
137 }
138
139 if (strncmp(cfs->source(), "__", 2) == 0) {
140 // generated class: __dynamic_proxy__, __JVM_LookupDefineClass__, etc
141 return;
142 }
143 }
144
145 {
146 InstanceKlass* super = k->super();
147 if (super != nullptr && !has_id(super)) {
148 return;
149 }
150
151 Array<InstanceKlass*>* interfaces = k->local_interfaces();
152 int len = interfaces->length();
153 for (int i = 0; i < len; i++) {
154 InstanceKlass* intf = interfaces->at(i);
155 if (!has_id(intf)) {
156 return;
157 }
158 }
159 }
160
161 if (k->is_hidden()) {
162 return;
163 }
164
165 if (k->module()->is_patched()) {
166 return;
167 }
168
169 ResourceMark rm;
170 stream->print("%s id: %d", k->name()->as_C_string(), get_id(k));
171 if (!is_builtin_loader) {
172 InstanceKlass* super = k->super();
173 assert(super != nullptr, "must be");
174 stream->print(" super: %d", get_id(super));
175
176 Array<InstanceKlass*>* interfaces = k->local_interfaces();
177 int len = interfaces->length();
178 if (len > 0) {
179 stream->print(" interfaces:");
180 for (int i = 0; i < len; i++) {
181 InstanceKlass* intf = interfaces->at(i);
182 stream->print(" %d", get_id(intf));
183 }
184 }
185
186 // NB: the string following "source: " is not really a proper file name, but rather
187 // a truncated URI referring to a file. It must be decoded after reading.
188 #ifdef _WINDOWS
189 // "file:/C:/dir/foo.jar" -> "C:/dir/foo.jar"
190 stream->print(" source: %s", cfs->source() + 6);
191 #else
192 // "file:/dir/foo.jar" -> "/dir/foo.jar"
193 stream->print(" source: %s", cfs->source() + 5);
194 #endif
195 }
196
197 stream->cr();
198 stream->flush();
199 }
200
201 void ClassListWriter::delete_classlist() {
202 if (_classlist_file != nullptr) {
203 delete _classlist_file;
204 }
205 }
206
207 class ClassListWriter::WriteResolveConstantsCLDClosure : public CLDClosure {
208 public:
209 void do_cld(ClassLoaderData* cld) {
210 for (Klass* klass = cld->klasses(); klass != nullptr; klass = klass->next_link()) {
211 if (klass->is_instance_klass()) {
212 InstanceKlass* ik = InstanceKlass::cast(klass);
213 write_resolved_constants_for(ik);
214 write_array_info_for(ik); // FIXME: piggybacking on WriteResolveConstantsCLDClosure is misleading
215 }
216 }
217 }
218 };
219
220 void ClassListWriter::write_array_info_for(InstanceKlass* ik) {
221 ObjArrayKlass* oak = ik->array_klasses();
222 if (oak != nullptr) {
223 while (oak->higher_dimension() != nullptr) {
224 oak = oak->higher_dimension();
225 }
226 ResourceMark rm;
227 outputStream* stream = _classlist_file;
228 stream->print_cr("%s %s %d", ClassListParser::ARRAY_TAG, ik->name()->as_C_string(), oak->dimension());
229 }
230 }
231
232 void ClassListWriter::write_resolved_constants() {
233 if (!is_enabled()) {
234 return;
235 }
236 MutexLocker lock(ClassLoaderDataGraph_lock);
237 MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag);
238
239 WriteResolveConstantsCLDClosure closure;
240 ClassLoaderDataGraph::loaded_cld_do(&closure);
241 }
242
243 void ClassListWriter::write_reflection_data() {
244 if (!is_enabled()) {
245 return;
246 }
247 auto collector = [&] (const InstanceKlass* ik, int id) {
248 write_reflection_data_for(const_cast<InstanceKlass*>(ik));
249 };
250 _id_table->iterate_all(collector);
251 }
252
253 void ClassListWriter::write_reflection_data_for(InstanceKlass* ik) {
254 ResourceMark rm;
255 outputStream* stream = _classlist_file;
256 if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data()) || ik->is_hidden()) {
257 return; // ignore
258 }
259 if (java_lang_Class::has_reflection_data(ik->java_mirror())) {
260 EXCEPTION_MARK;
261 int rd_flags = AOTConstantPoolResolver::class_reflection_data_flags(ik, THREAD);
262 if (!HAS_PENDING_EXCEPTION) {
263 // We can't hold the lock when doing the upcall inside class_reflection_data_flags()
264 MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag);
265 stream->print_cr("%s %s %d", ClassListParser::CLASS_REFLECTION_DATA_TAG, ik->name()->as_C_string(), rd_flags);
266 }
267 }
268 }
269
270 void ClassListWriter::write_resolved_constants_for(InstanceKlass* ik) {
271 if (!SystemDictionaryShared::is_builtin_loader(ik->class_loader_data()) ||
272 ik->is_hidden()) {
273 return;
274 }
275 if (LambdaFormInvokers::may_be_regenerated_class(ik->name())) {
276 return;
277 }
278 if (ik->name()->equals("jdk/internal/module/SystemModules$all")) {
279 // This class is regenerated during JDK build process, so the classlist
280 // may not match the version that's in the real jdk image.
281 return;
282 }
283
284 if (!has_id(ik)) { // do not resolve CP for classes loaded by custom loaders.
285 return;
286 }
287
288 ResourceMark rm;
289 ConstantPool* cp = ik->constants();
290 GrowableArray<bool> list(cp->length(), cp->length(), false);
291 bool print = false;
292
293 for (int cp_index = 1; cp_index < cp->length(); cp_index++) { // Index 0 is unused
294 switch (cp->tag_at(cp_index).value()) {
295 case JVM_CONSTANT_Class:
296 {
297 Klass* k = cp->resolved_klass_at(cp_index);
298 if (k->is_instance_klass()) {
299 list.at_put(cp_index, true);
300 print = true;
301 }
302 }
303 break;
304 }
305 }
306
307 if (cp->cache() != nullptr) {
308 Array<ResolvedIndyEntry>* indy_entries = cp->cache()->resolved_indy_entries();
309 if (indy_entries != nullptr) {
310 for (int i = 0; i < indy_entries->length(); i++) {
311 ResolvedIndyEntry* rie = indy_entries->adr_at(i);
312 int cp_index = rie->constant_pool_index();
313 if (rie->is_resolved()) {
314 list.at_put(cp_index, true);
315 print = true;
316 }
317 }
318 }
319
320 Array<ResolvedFieldEntry>* field_entries = cp->cache()->resolved_field_entries();
321 if (field_entries != nullptr) {
322 for (int i = 0; i < field_entries->length(); i++) {
323 ResolvedFieldEntry* rfe = field_entries->adr_at(i);
324 if (rfe->is_resolved(Bytecodes::_getfield) ||
325 rfe->is_resolved(Bytecodes::_putfield)) {
326 list.at_put(rfe->constant_pool_index(), true);
327 print = true;
328 }
329 }
330 }
331
332 Array<ResolvedMethodEntry>* method_entries = cp->cache()->resolved_method_entries();
333 if (method_entries != nullptr) {
334 for (int i = 0; i < method_entries->length(); i++) {
335 ResolvedMethodEntry* rme = method_entries->adr_at(i);
336 if (rme->is_resolved(Bytecodes::_invokevirtual) ||
337 rme->is_resolved(Bytecodes::_invokespecial) ||
338 rme->is_resolved(Bytecodes::_invokeinterface) ||
339 rme->is_resolved(Bytecodes::_invokestatic) ||
340 rme->is_resolved(Bytecodes::_invokehandle)) {
341 list.at_put(rme->constant_pool_index(), true);
342 print = true;
343 }
344 }
345 }
346 }
347
348 if (print) {
349 outputStream* stream = _classlist_file;
350 stream->print("@cp %s", ik->name()->as_C_string());
351 for (int i = 0; i < list.length(); i++) {
352 if (list.at(i)) {
353 constantTag cp_tag = cp->tag_at(i).value();
354 assert(cp_tag.value() == JVM_CONSTANT_Class ||
355 cp_tag.value() == JVM_CONSTANT_Fieldref ||
356 cp_tag.value() == JVM_CONSTANT_Methodref||
357 cp_tag.value() == JVM_CONSTANT_InterfaceMethodref ||
358 cp_tag.value() == JVM_CONSTANT_InvokeDynamic, "sanity");
359 stream->print(" %d", i);
360 }
361 }
362 stream->cr();
363 }
364 }
365
366 void ClassListWriter::write_loader_negative_lookup_cache_for(oop loader, const char* loader_type) {
367 TempNewSymbol method = SymbolTable::new_symbol("negativeLookupCacheContents");
368 TempNewSymbol signature = SymbolTable::new_symbol("()Ljava/lang/String;");
369
370 EXCEPTION_MARK;
371 HandleMark hm(THREAD);
372
373 JavaValue result(T_OBJECT);
374 JavaCalls::call_virtual(&result,
375 Handle(THREAD, loader),
376 loader->klass(),
377 method,
378 signature,
379 CHECK);
380
381 if (HAS_PENDING_EXCEPTION) {
382 log_warning(cds)("Error during BuiltinClassLoader::negativeLookupCacheContents() call for %s loader", loader_type);
383 CLEAR_PENDING_EXCEPTION;
384 return;
385 } else if (result.get_oop() == nullptr) {
386 return;
387 }
388
389 ResourceMark rm;
390 const char* cache_contents = java_lang_String::as_utf8_string(result.get_oop());
391 log_debug(cds)("%s loader negative cache: %s", loader_type, cache_contents);
392
393 outputStream* stream = _classlist_file;
394 const size_t buffer_size = strlen(ClassListParser::LOADER_NEGATIVE_CACHE_TAG) + 1 /* for space*/
395 + strlen(loader_type) + 1 /* for space */ + strlen(cache_contents) + 1 /* for null character */;
396 char* buffer = NEW_C_HEAP_ARRAY(char, buffer_size, mtInternal);
397 _classlist_file->set_scratch_buffer(buffer, buffer_size);
398 MutexLocker lock2(ClassListFile_lock, Mutex::_no_safepoint_check_flag);
399 stream->print("%s %s %s", ClassListParser::LOADER_NEGATIVE_CACHE_TAG, loader_type, cache_contents);
400 stream->cr();
401 _classlist_file->set_scratch_buffer(nullptr, 0);
402 }
403
404 void ClassListWriter::write_loader_negative_lookup_cache() {
405 if (!is_enabled()) {
406 return;
407 }
408
409 write_loader_negative_lookup_cache_for(SystemDictionary::java_platform_loader(), "platform");
410 write_loader_negative_lookup_cache_for(SystemDictionary::java_system_loader(), "app");
411 }