1 /*
  2  * Copyright (c) 2003, 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 "classfile/classLoaderData.inline.hpp"
 26 #include "classfile/placeholders.hpp"
 27 #include "logging/log.hpp"
 28 #include "logging/logTag.hpp"
 29 #include "logging/logStream.hpp"
 30 #include "memory/resourceArea.hpp"
 31 #include "oops/symbolHandle.hpp"
 32 #include "runtime/javaThread.hpp"
 33 #include "runtime/mutexLocker.hpp"
 34 #include "utilities/resourceHash.hpp"
 35 
 36 class PlaceholderKey {
 37   SymbolHandle _name;
 38   ClassLoaderData* _loader_data;
 39  public:
 40   PlaceholderKey(Symbol* name, ClassLoaderData* l) : _name(name), _loader_data(l) {}
 41 
 42   static bool equals(PlaceholderKey const& k1, PlaceholderKey const& k2) {
 43     return (k1._name == k2._name && k1._loader_data == k2._loader_data);
 44   }
 45   static unsigned hash(PlaceholderKey const& k) {
 46     return (unsigned) k._name->identity_hash() ^ (int)((intptr_t)k._loader_data >> 3);
 47   }
 48   void print_on(outputStream* st) const;
 49 };
 50 
 51 const int _placeholder_table_size = 503;   // Does this really have to be prime?
 52 using InternalPlaceholderTable = ResourceHashtable<PlaceholderKey, PlaceholderEntry, _placeholder_table_size, AnyObj::C_HEAP, mtClass,
 53                   PlaceholderKey::hash, PlaceholderKey::equals>;
 54 static InternalPlaceholderTable* _placeholders;
 55 
 56 // SeenThread objects represent list of threads that are
 57 // currently performing a load action on a class.
 58 // For class circularity, set before loading a superclass.
 59 // For bootclasssearchpath, set before calling load_instance_class.
 60 // Defining must be single threaded on a class/classloader basis
 61 // For DEFINE_CLASS, the head of the queue owns the
 62 // define token and the rest of the threads wait to return the
 63 // result the first thread gets.
 64 class SeenThread: public CHeapObj<mtInternal> {
 65 private:
 66    JavaThread* _thread;
 67    SeenThread* _stnext;
 68    SeenThread* _stprev;
 69 public:
 70    SeenThread(JavaThread* thread) {
 71        _thread = thread;
 72        _stnext = nullptr;
 73        _stprev = nullptr;
 74    }
 75    JavaThread* thread()          const { return _thread;}
 76    void set_thread(JavaThread* thread) { _thread = thread; }
 77 
 78    SeenThread* next()        const { return _stnext;}
 79    void set_next(SeenThread* seen) { _stnext = seen; }
 80    void set_prev(SeenThread* seen) { _stprev = seen; }
 81 
 82   static void print_action_queue(SeenThread* seen, outputStream* st) {
 83     while (seen != nullptr) {
 84       seen->thread()->print_value_on(st);
 85       st->print(", ");
 86       seen = seen->next();
 87     }
 88   }
 89 };
 90 
 91 SeenThread* PlaceholderEntry::actionToQueue(PlaceholderTable::classloadAction action) {
 92   SeenThread* queuehead = nullptr;
 93   switch (action) {
 94     case PlaceholderTable::LOAD_INSTANCE:
 95        queuehead = _loadInstanceThreadQ;
 96        break;
 97     case PlaceholderTable::DETECT_CIRCULARITY:
 98        queuehead = _circularityThreadQ;
 99        break;
100     case PlaceholderTable::DEFINE_CLASS:
101        queuehead = _defineThreadQ;
102        break;
103     default: Unimplemented();
104   }
105   return queuehead;
106 }
107 
108 void PlaceholderEntry::set_threadQ(SeenThread* seenthread, PlaceholderTable::classloadAction action) {
109   switch (action) {
110     case PlaceholderTable::LOAD_INSTANCE:
111        _loadInstanceThreadQ = seenthread;
112        break;
113     case PlaceholderTable::DETECT_CIRCULARITY:
114        _circularityThreadQ = seenthread;
115        break;
116     case PlaceholderTable::DEFINE_CLASS:
117        _defineThreadQ = seenthread;
118        break;
119     default: Unimplemented();
120   }
121   return;
122 }
123 
124 // Doubly-linked list of Threads per action for class/classloader pair
125 // Class circularity support: links in thread before loading superclass
126 // bootstrap loader support:  links in a thread before load_instance_class
127 // definers: use as queue of define requestors, including owner of
128 // define token. Appends for debugging of requestor order
129 void PlaceholderEntry::add_seen_thread(JavaThread* thread, PlaceholderTable::classloadAction action) {
130   assert_lock_strong(SystemDictionary_lock);
131   SeenThread* threadEntry = new SeenThread(thread);
132   SeenThread* seen = actionToQueue(action);
133 
134   if (seen == nullptr) {
135     set_threadQ(threadEntry, action);
136     return;
137   }
138   SeenThread* next;
139   while ((next = seen->next()) != nullptr) {
140     seen = next;
141   }
142   seen->set_next(threadEntry);
143   threadEntry->set_prev(seen);
144   return;
145 }
146 
147 bool PlaceholderEntry::check_seen_thread(JavaThread* thread, PlaceholderTable::classloadAction action) {
148   assert_lock_strong(SystemDictionary_lock);
149   SeenThread* threadQ = actionToQueue(action);
150   SeenThread* seen = threadQ;
151   while (seen) {
152     if (thread == seen->thread()) {
153       return true;
154     }
155     seen = seen->next();
156   }
157   return false;
158 }
159 
160 // returns true if seenthreadQ is now empty
161 // Note, caller must ensure probe still exists while holding
162 // SystemDictionary_lock
163 // ignores if cleanup has already been done
164 // if found, deletes SeenThread
165 bool PlaceholderEntry::remove_seen_thread(JavaThread* thread, PlaceholderTable::classloadAction action) {
166   assert_lock_strong(SystemDictionary_lock);
167   SeenThread* threadQ = actionToQueue(action);
168   SeenThread* seen = threadQ;
169   SeenThread* prev = nullptr;
170   while (seen) {
171     if (thread == seen->thread()) {
172       if (prev) {
173         prev->set_next(seen->next());
174       } else {
175         set_threadQ(seen->next(), action);
176       }
177       if (seen->next()) {
178         seen->next()->set_prev(prev);
179       }
180       delete seen;
181       break;
182     }
183     prev = seen;
184     seen = seen->next();
185   }
186   return (actionToQueue(action) == nullptr);
187 }
188 
189 
190 void PlaceholderEntry::set_next_klass_name(Symbol* next_klass_name) {
191   assert_locked_or_safepoint(SystemDictionary_lock);
192   assert(_next_klass_name == nullptr || _next_klass_name->refcount() > 1, "must be referenced also by the loader");
193   _next_klass_name = next_klass_name;
194 }
195 
196 // Placeholder objects represent classes currently being loaded.
197 // All threads examining the placeholder table must hold the
198 // SystemDictionary_lock, so we don't need special precautions
199 // on store ordering here.
200 static PlaceholderEntry* add_entry(Symbol* class_name, ClassLoaderData* loader_data,
201                                    Symbol* next_klass_name){
202   assert_locked_or_safepoint(SystemDictionary_lock);
203   assert(class_name != nullptr, "adding nullptr obj");
204 
205   PlaceholderEntry entry;
206   entry.set_next_klass_name(next_klass_name);
207   PlaceholderKey key(class_name, loader_data);
208   bool created;
209   PlaceholderEntry* table_copy = _placeholders->put_if_absent(key, entry, &created);
210   assert(created, "better be absent");
211   return table_copy;
212 }
213 
214 // Remove a placeholder object.
215 static void remove_entry(Symbol* class_name, ClassLoaderData* loader_data) {
216   assert_locked_or_safepoint(SystemDictionary_lock);
217 
218   PlaceholderKey key(class_name, loader_data);
219   _placeholders->remove(key);
220 }
221 
222 
223 PlaceholderEntry* PlaceholderTable::get_entry(Symbol* class_name, ClassLoaderData* loader_data) {
224   assert_locked_or_safepoint(SystemDictionary_lock);
225   PlaceholderKey key(class_name, loader_data);
226   return _placeholders->get(key);
227 }
228 
229 static const char* action_to_string(PlaceholderTable::classloadAction action) {
230   switch (action) {
231   case PlaceholderTable::LOAD_INSTANCE: return "LOAD_INSTANCE";
232   case PlaceholderTable::DETECT_CIRCULARITY:    return "DETECT_CIRCULARITY";
233   case PlaceholderTable::DEFINE_CLASS:  return "DEFINE_CLASS";
234  }
235  return "";
236 }
237 
238 inline void log(Symbol* name, PlaceholderEntry* entry, const char* function, PlaceholderTable::classloadAction action) {
239   if (log_is_enabled(Debug, class, load, placeholders)) {
240     LogTarget(Debug, class, load, placeholders) lt;
241     ResourceMark rm;
242     LogStream ls(lt);
243     ls.print("entry %s : %s %s ", name->as_C_string(), function, action_to_string(action));
244     entry->print_on(&ls);
245   }
246 }
247 
248 // find_and_add returns probe pointer - old or new
249 // If no entry exists, add a placeholder entry
250 // If entry exists, reuse entry
251 // For both, push SeenThread for classloadAction
252 // If DETECT_CIRCULARITY, this is used for circularity detection for instanceklass loading.
253 PlaceholderEntry* PlaceholderTable::find_and_add(Symbol* name,
254                                                  ClassLoaderData* loader_data,
255                                                  classloadAction action,
256                                                  Symbol* next_klass_name,
257                                                  JavaThread* thread) {
258   assert(action != DETECT_CIRCULARITY || next_klass_name != nullptr,
259          "must have a class name for the next step in the class resolution recursion");
260   PlaceholderEntry* probe = get_entry(name, loader_data);
261   if (probe == nullptr) {
262     // Nothing found, add place holder
263     probe = add_entry(name, loader_data, next_klass_name);
264   } else {
265     if (action == DETECT_CIRCULARITY) {
266       probe->set_next_klass_name(next_klass_name);
267     }
268   }
269   probe->add_seen_thread(thread, action);
270   log(name, probe, "find_and_add", action);
271   return probe;
272 }
273 
274 void PlaceholderTable::initialize(){
275   _placeholders = new (mtClass) InternalPlaceholderTable();
276 }
277 
278 
279 // placeholder is used to track class loading internal states
280 // superthreadQ tracks class circularity, while loading superclass/superinterface
281 // loadInstanceThreadQ tracks load_instance_class calls
282 // definer() tracks the single thread that owns define token
283 // defineThreadQ tracks waiters on defining thread's results
284 // 1st claimant creates placeholder
285 // find_and_add adds SeenThread entry for appropriate queue
286 // All claimants remove SeenThread after completing action
287 // On removal: if definer and all queues empty, remove entry
288 // Note: you can be in both placeholders and systemDictionary
289 // Therefore - must always check SD first
290 void PlaceholderTable::find_and_remove(Symbol* name, ClassLoaderData* loader_data,
291                                        classloadAction action,
292                                        JavaThread* thread) {
293   assert_locked_or_safepoint(SystemDictionary_lock);
294   PlaceholderEntry* probe = get_entry(name, loader_data);
295   assert(probe != nullptr, "must find an entry");
296   log(name, probe, "find_and_remove", action);
297   probe->remove_seen_thread(thread, action);
298   if (probe->circularityThreadQ() == nullptr) {
299     probe->set_next_klass_name(nullptr);
300   }
301   // If no other threads using this entry, and this thread is not using this entry for other states
302   if ((probe->circularityThreadQ() == nullptr) && (probe->loadInstanceThreadQ() == nullptr)
303       && (probe->defineThreadQ() == nullptr) && (probe->definer() == nullptr)) {
304     remove_entry(name, loader_data);
305   }
306 }
307 
308 void PlaceholderKey::print_on(outputStream* st) const {
309   _name->print_value_on(st);
310   st->print(", loader ");
311   _loader_data->print_value_on(st);
312 }
313 
314 void PlaceholderEntry::print_on(outputStream* st) const {
315   if (next_klass_name() != nullptr) {
316     st->print(", next_klass_name ");
317     next_klass_name()->print_value_on(st);
318   }
319   if (definer() != nullptr) {
320     st->print(", definer ");
321     definer()->print_value_on(st);
322   }
323   if (instance_klass() != nullptr) {
324     st->print(", InstanceKlass ");
325     instance_klass()->print_value_on(st);
326   }
327   st->cr();
328   st->print("loadInstanceThreadQ threads:");
329   SeenThread::print_action_queue(loadInstanceThreadQ(), st);
330   st->cr();
331   st->print("circularityThreadQ threads:");
332   SeenThread::print_action_queue(circularityThreadQ(), st);
333   st->cr();
334   st->print("defineThreadQ threads:");
335   SeenThread::print_action_queue(defineThreadQ(), st);
336   st->cr();
337 }
338 
339 void PlaceholderTable::print_on(outputStream* st) {
340   auto printer = [&] (PlaceholderKey& key, PlaceholderEntry& entry) {
341       st->print("placeholder ");
342       key.print_on(st);
343       entry.print_on(st);
344       return true;
345   };
346   st->print_cr("Placeholder table (table_size=%d, placeholders=%d)",
347                 _placeholders->table_size(), _placeholders->number_of_entries());
348   _placeholders->iterate(printer);
349 }
350 
351 void PlaceholderTable::print() { return print_on(tty); }