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