1 /*
  2  * Copyright (c) 2003, 2021, 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 "runtime/mutexLocker.hpp"
 33 #include "runtime/thread.hpp"
 34 #include "utilities/hashtable.inline.hpp"
 35 
 36 // SeenThread objects represent list of threads that are
 37 // currently performing a load action on a class.
 38 // For class circularity, set before loading a superclass.
 39 // For bootclasssearchpath, set before calling load_instance_class.
 40 // Defining must be single threaded on a class/classloader basis
 41 // For DEFINE_CLASS, the head of the queue owns the
 42 // define token and the rest of the threads wait to return the
 43 // result the first thread gets.
 44 // For INLINE_FIELD, set when loading inline type fields for
 45 // class circularity checking.
 46 class SeenThread: public CHeapObj<mtInternal> {
 47 private:
 48    JavaThread* _thread;
 49    SeenThread* _stnext;
 50    SeenThread* _stprev;
 51 public:
 52    SeenThread(JavaThread* thread) {
 53        _thread = thread;
 54        _stnext = NULL;
 55        _stprev = NULL;
 56    }
 57    JavaThread* thread()          const { return _thread;}
 58    void set_thread(JavaThread* thread) { _thread = thread; }
 59 
 60    SeenThread* next()        const { return _stnext;}
 61    void set_next(SeenThread* seen) { _stnext = seen; }
 62    void set_prev(SeenThread* seen) { _stprev = seen; }
 63 
 64   void print_action_queue(outputStream* st) {
 65     SeenThread* seen = this;
 66     while (seen != NULL) {
 67       seen->thread()->print_value_on(st);
 68       st->print(", ");
 69       seen = seen->next();
 70     }
 71   }
 72 };
 73 
 74 SeenThread* PlaceholderEntry::actionToQueue(PlaceholderTable::classloadAction action) {
 75   SeenThread* queuehead = NULL;
 76   switch (action) {
 77     case PlaceholderTable::LOAD_INSTANCE:
 78        queuehead = _loadInstanceThreadQ;
 79        break;
 80     case PlaceholderTable::LOAD_SUPER:
 81        queuehead = _superThreadQ;
 82        break;
 83     case PlaceholderTable::DEFINE_CLASS:
 84        queuehead = _defineThreadQ;
 85        break;
 86     case PlaceholderTable::INLINE_TYPE_FIELD:
 87        queuehead = _inlineTypeFieldQ;
 88        break;
 89     default: Unimplemented();
 90   }
 91   return queuehead;
 92 }
 93 
 94 void PlaceholderEntry::set_threadQ(SeenThread* seenthread, PlaceholderTable::classloadAction action) {
 95   switch (action) {
 96     case PlaceholderTable::LOAD_INSTANCE:
 97        _loadInstanceThreadQ = seenthread;
 98        break;
 99     case PlaceholderTable::LOAD_SUPER:
100        _superThreadQ = seenthread;
101        break;
102     case PlaceholderTable::DEFINE_CLASS:
103        _defineThreadQ = seenthread;
104        break;
105     case PlaceholderTable::INLINE_TYPE_FIELD:
106        _inlineTypeFieldQ = seenthread;
107        break;
108     default: Unimplemented();
109   }
110   return;
111 }
112 
113 // Doubly-linked list of Threads per action for class/classloader pair
114 // Class circularity support: links in thread before loading superclass
115 // bootstrap loader support:  links in a thread before load_instance_class
116 // definers: use as queue of define requestors, including owner of
117 // define token. Appends for debugging of requestor order
118 void PlaceholderEntry::add_seen_thread(JavaThread* thread, PlaceholderTable::classloadAction action) {
119   assert_lock_strong(SystemDictionary_lock);
120   SeenThread* threadEntry = new SeenThread(thread);
121   SeenThread* seen = actionToQueue(action);
122 
123   assert(action != PlaceholderTable::LOAD_INSTANCE || seen == NULL,
124          "Only one LOAD_INSTANCE allowed at a time");
125 
126   if (seen == NULL) {
127     set_threadQ(threadEntry, action);
128     return;
129   }
130   SeenThread* next;
131   while ((next = seen->next()) != NULL) {
132     seen = next;
133   }
134   seen->set_next(threadEntry);
135   threadEntry->set_prev(seen);
136   return;
137 }
138 
139 bool PlaceholderEntry::check_seen_thread(JavaThread* thread, PlaceholderTable::classloadAction action) {
140   assert_lock_strong(SystemDictionary_lock);
141   SeenThread* threadQ = actionToQueue(action);
142   SeenThread* seen = threadQ;
143   while (seen) {
144     if (thread == seen->thread()) {
145       return true;
146     }
147     seen = seen->next();
148   }
149   return false;
150 }
151 
152 // returns true if seenthreadQ is now empty
153 // Note, caller must ensure probe still exists while holding
154 // SystemDictionary_lock
155 // ignores if cleanup has already been done
156 // if found, deletes SeenThread
157 bool PlaceholderEntry::remove_seen_thread(JavaThread* thread, PlaceholderTable::classloadAction action) {
158   assert_lock_strong(SystemDictionary_lock);
159   SeenThread* threadQ = actionToQueue(action);
160   SeenThread* seen = threadQ;
161   SeenThread* prev = NULL;
162   while (seen) {
163     if (thread == seen->thread()) {
164       if (prev) {
165         prev->set_next(seen->next());
166       } else {
167         set_threadQ(seen->next(), action);
168       }
169       if (seen->next()) {
170         seen->next()->set_prev(prev);
171       }
172       delete seen;
173       break;
174     }
175     prev = seen;
176     seen = seen->next();
177   }
178   return (actionToQueue(action) == NULL);
179 }
180 
181 
182 // Placeholder methods
183 
184 PlaceholderEntry* PlaceholderTable::new_entry(int hash, Symbol* name,
185                                               ClassLoaderData* loader_data,
186                                               Symbol* supername) {
187   PlaceholderEntry* entry = (PlaceholderEntry*)Hashtable<Symbol*, mtClass>::new_entry(hash, name);
188   // Hashtable with Symbol* literal must increment and decrement refcount.
189   name->increment_refcount();
190   entry->set_loader_data(loader_data);
191   entry->set_supername(supername);
192   entry->set_superThreadQ(NULL);
193   entry->set_loadInstanceThreadQ(NULL);
194   entry->set_defineThreadQ(NULL);
195   entry->set_inlineTypeFieldQ(NULL);
196   entry->set_definer(NULL);
197   entry->set_instance_klass(NULL);
198   return entry;
199 }
200 
201 void PlaceholderTable::free_entry(PlaceholderEntry* entry) {
202   // decrement Symbol refcount here because Hashtable doesn't.
203   entry->literal()->decrement_refcount();
204   if (entry->supername() != NULL) entry->supername()->decrement_refcount();
205   BasicHashtable<mtClass>::free_entry(entry);
206 }
207 
208 
209 // Placeholder objects represent classes currently being loaded.
210 // All threads examining the placeholder table must hold the
211 // SystemDictionary_lock, so we don't need special precautions
212 // on store ordering here.
213 PlaceholderEntry* PlaceholderTable::add_entry(unsigned int hash,
214                                               Symbol* class_name, ClassLoaderData* loader_data,
215                                               Symbol* supername){
216   assert_locked_or_safepoint(SystemDictionary_lock);
217   assert(class_name != NULL, "adding NULL obj");
218 
219   // Both readers and writers are locked so it's safe to just
220   // create the placeholder and insert it in the list without a membar.
221   PlaceholderEntry* entry = new_entry(hash, class_name, loader_data, supername);
222   int index = hash_to_index(hash);
223   Hashtable<Symbol*, mtClass>::add_entry(index, entry);
224   return entry;
225 }
226 
227 
228 // Remove a placeholder object.
229 void PlaceholderTable::remove_entry(unsigned int hash,
230                                     Symbol* class_name,
231                                     ClassLoaderData* loader_data) {
232   assert_locked_or_safepoint(SystemDictionary_lock);
233   int index = hash_to_index(hash);
234   PlaceholderEntry** p = bucket_addr(index);
235   while (*p != NULL) {
236     PlaceholderEntry *probe = *p;
237     if (probe->hash() == hash && probe->equals(class_name, loader_data)) {
238       // Delete entry
239       *p = probe->next();
240       free_entry(probe);
241       return;
242     }
243     p = probe->next_addr();
244   }
245 }
246 
247 PlaceholderEntry* PlaceholderTable::get_entry(unsigned int hash,
248                                               Symbol* class_name,
249                                               ClassLoaderData* loader_data) {
250   assert_locked_or_safepoint(SystemDictionary_lock);
251 
252   int index = hash_to_index(hash);
253   for (PlaceholderEntry *place_probe = bucket(index);
254                          place_probe != NULL;
255                          place_probe = place_probe->next()) {
256     if (place_probe->hash() == hash &&
257         place_probe->equals(class_name, loader_data)) {
258       return place_probe;
259     }
260   }
261   return NULL;
262 }
263 
264 Symbol* PlaceholderTable::find_entry(unsigned int hash,
265                                      Symbol* class_name,
266                                      ClassLoaderData* loader_data) {
267   PlaceholderEntry* probe = get_entry(hash, class_name, loader_data);
268   return (probe != NULL ? probe->klassname() : NULL);
269 }
270 
271 static const char* action_to_string(PlaceholderTable::classloadAction action) {
272   switch (action) {
273   case PlaceholderTable::LOAD_INSTANCE: return "LOAD_INSTANCE";
274   case PlaceholderTable::LOAD_SUPER:    return "LOAD_SUPER";
275   case PlaceholderTable::DEFINE_CLASS:  return "DEFINE_CLASS";
276   case PlaceholderTable::INLINE_TYPE_FIELD: return "INLINE_TYPE_FIELD";
277  }
278  return "";
279 }
280 
281 inline void log(PlaceholderEntry* entry, const char* function, PlaceholderTable::classloadAction action) {
282   if (log_is_enabled(Debug, class, load, placeholders)) {
283     LogTarget(Debug, class, load, placeholders) lt;
284     ResourceMark rm;
285     LogStream ls(lt);
286     ls.print("%s %s ", function, action_to_string(action));
287     entry->print_entry(&ls);
288   }
289 }
290 
291 // find_and_add returns probe pointer - old or new
292 // If no entry exists, add a placeholder entry
293 // If entry exists, reuse entry
294 // For both, push SeenThread for classloadAction
295 // If LOAD_SUPER, this is used for circularity detection for instanceklass loading.
296 PlaceholderEntry* PlaceholderTable::find_and_add(unsigned int hash,
297                                                  Symbol* name,
298                                                  ClassLoaderData* loader_data,
299                                                  classloadAction action,
300                                                  Symbol* supername,
301                                                  JavaThread* thread) {
302   assert(action != LOAD_SUPER || supername != NULL, "must have a super class name");
303   PlaceholderEntry* probe = get_entry(hash, name, loader_data);
304   if (probe == NULL) {
305     // Nothing found, add place holder
306     probe = add_entry(hash, name, loader_data, supername);
307   } else {
308     if (action == LOAD_SUPER) {
309       probe->set_supername(supername);
310     }
311   }
312   probe->add_seen_thread(thread, action);
313   log(probe, "find_and_add", action);
314   return probe;
315 }
316 
317 
318 // placeholder is used to track class loading internal states
319 // placeholder existence now for loading superclass/superinterface
320 // superthreadQ tracks class circularity, while loading superclass/superinterface
321 // loadInstanceThreadQ tracks load_instance_class calls
322 // definer() tracks the single thread that owns define token
323 // defineThreadQ tracks waiters on defining thread's results
324 // 1st claimant creates placeholder
325 // find_and_add adds SeenThread entry for appropriate queue
326 // All claimants remove SeenThread after completing action
327 // On removal: if definer and all queues empty, remove entry
328 // Note: you can be in both placeholders and systemDictionary
329 // Therefore - must always check SD first
330 // Ignores the case where entry is not found
331 void PlaceholderTable::find_and_remove(unsigned int hash,
332                                        Symbol* name, ClassLoaderData* loader_data,
333                                        classloadAction action,
334                                        JavaThread* thread) {
335     assert_locked_or_safepoint(SystemDictionary_lock);
336     PlaceholderEntry *probe = get_entry(hash, name, loader_data);
337     if (probe != NULL) {
338        log(probe, "find_and_remove", action);
339        probe->remove_seen_thread(thread, action);
340        // If no other threads using this entry, and this thread is not using this entry for other states
341        if ((probe->superThreadQ() == NULL) && (probe->loadInstanceThreadQ() == NULL)
342           && (probe->defineThreadQ() == NULL) && (probe->definer() == NULL)
343           && (probe->inlineTypeFieldQ() == NULL)) {
344          remove_entry(hash, name, loader_data);
345        }
346     }
347   }
348 
349 PlaceholderTable::PlaceholderTable(int table_size)
350     : Hashtable<Symbol*, mtClass>(table_size, sizeof(PlaceholderEntry)) {
351 }
352 
353 void PlaceholderEntry::verify() const {
354   guarantee(loader_data() != NULL, "Must have been setup.");
355   guarantee(loader_data()->class_loader() == NULL || loader_data()->class_loader()->is_instance(),
356             "checking type of _loader");
357   guarantee(instance_klass() == NULL
358             || instance_klass()->is_instance_klass(),
359             "checking type of instance_klass result");
360 }
361 
362 void PlaceholderTable::verify() {
363   verify_table<PlaceholderEntry>("Placeholder Table");
364 }
365 
366 
367 // Note, doesn't append a cr
368 // Can't call this print_on because HashtableEntry doesn't initialize its vptr
369 // and print_on is a virtual function so the vptr call crashes.
370 void PlaceholderEntry::print_entry(outputStream* st) const {
371   klassname()->print_value_on(st);
372   if (loader_data() != NULL) {
373     st->print(", loader ");
374     loader_data()->print_value_on(st);
375   }
376   if (supername() != NULL) {
377     st->print(", supername ");
378     supername()->print_value_on(st);
379   }
380   if (definer() != NULL) {
381     st->print(", definer ");
382     definer()->print_value_on(st);
383   }
384   if (instance_klass() != NULL) {
385     st->print(", InstanceKlass ");
386     instance_klass()->print_value_on(st);
387   }
388   st->cr();
389   st->print("loadInstanceThreadQ threads:");
390   loadInstanceThreadQ()->print_action_queue(st);
391   st->cr();
392   st->print("superThreadQ threads:");
393   superThreadQ()->print_action_queue(st);
394   st->cr();
395   st->print("defineThreadQ threads:");
396   defineThreadQ()->print_action_queue(st);
397   st->cr();
398   st->print("inlineTypeFieldQ threads:");
399   inlineTypeFieldQ()->print_action_queue(st);
400   st->cr();
401 }
402 
403 void PlaceholderTable::print_on(outputStream* st) const {
404   st->print_cr("Placeholder table (table_size=%d, placeholders=%d)",
405                 table_size(), number_of_entries());
406   for (int pindex = 0; pindex < table_size(); pindex++) {
407     for (PlaceholderEntry* probe = bucket(pindex);
408                            probe != NULL;
409                            probe = probe->next()) {
410       st->print("%4d: placeholder ", pindex);
411       probe->print_entry(st);
412     }
413   }
414 }
415 
416 void PlaceholderTable::print() const { return print_on(tty); }