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