dictionary.cpp revision 1472:c18cbe5936b8
1/*
2 * Copyright (c) 2003, 2009, 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 "incls/_precompiled.incl"
26# include "incls/_dictionary.cpp.incl"
27
28
29DictionaryEntry*  Dictionary::_current_class_entry = NULL;
30int               Dictionary::_current_class_index =    0;
31
32
33Dictionary::Dictionary(int table_size)
34  : TwoOopHashtable(table_size, sizeof(DictionaryEntry)) {
35  _current_class_index = 0;
36  _current_class_entry = NULL;
37};
38
39
40
41Dictionary::Dictionary(int table_size, HashtableBucket* t,
42                       int number_of_entries)
43  : TwoOopHashtable(table_size, sizeof(DictionaryEntry), t, number_of_entries) {
44  _current_class_index = 0;
45  _current_class_entry = NULL;
46};
47
48
49DictionaryEntry* Dictionary::new_entry(unsigned int hash, klassOop klass,
50                                       oop loader) {
51  DictionaryEntry* entry;
52  entry = (DictionaryEntry*)Hashtable::new_entry(hash, klass);
53  entry->set_loader(loader);
54  entry->set_pd_set(NULL);
55  return entry;
56}
57
58
59DictionaryEntry* Dictionary::new_entry() {
60  DictionaryEntry* entry = (DictionaryEntry*)Hashtable::new_entry(0L, NULL);
61  entry->set_loader(NULL);
62  entry->set_pd_set(NULL);
63  return entry;
64}
65
66
67void Dictionary::free_entry(DictionaryEntry* entry) {
68  // avoid recursion when deleting linked list
69  while (entry->pd_set() != NULL) {
70    ProtectionDomainEntry* to_delete = entry->pd_set();
71    entry->set_pd_set(to_delete->next());
72    delete to_delete;
73  }
74  Hashtable::free_entry(entry);
75}
76
77
78bool DictionaryEntry::contains_protection_domain(oop protection_domain) const {
79#ifdef ASSERT
80  if (protection_domain == instanceKlass::cast(klass())->protection_domain()) {
81    // Ensure this doesn't show up in the pd_set (invariant)
82    bool in_pd_set = false;
83    for (ProtectionDomainEntry* current = _pd_set;
84                                current != NULL;
85                                current = current->next()) {
86      if (current->protection_domain() == protection_domain) {
87        in_pd_set = true;
88        break;
89      }
90    }
91    if (in_pd_set) {
92      assert(false, "A klass's protection domain should not show up "
93                    "in its sys. dict. PD set");
94    }
95  }
96#endif /* ASSERT */
97
98  if (protection_domain == instanceKlass::cast(klass())->protection_domain()) {
99    // Succeeds trivially
100    return true;
101  }
102
103  for (ProtectionDomainEntry* current = _pd_set;
104                              current != NULL;
105                              current = current->next()) {
106    if (current->protection_domain() == protection_domain) return true;
107  }
108  return false;
109}
110
111
112void DictionaryEntry::add_protection_domain(oop protection_domain) {
113  assert_locked_or_safepoint(SystemDictionary_lock);
114  if (!contains_protection_domain(protection_domain)) {
115    ProtectionDomainEntry* new_head =
116                new ProtectionDomainEntry(protection_domain, _pd_set);
117    // Warning: Preserve store ordering.  The SystemDictionary is read
118    //          without locks.  The new ProtectionDomainEntry must be
119    //          complete before other threads can be allowed to see it
120    //          via a store to _pd_set.
121    OrderAccess::release_store_ptr(&_pd_set, new_head);
122  }
123  if (TraceProtectionDomainVerification && WizardMode) {
124    print();
125  }
126}
127
128
129bool Dictionary::do_unloading(BoolObjectClosure* is_alive) {
130  assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
131  bool class_was_unloaded = false;
132  int  index = 0; // Defined here for portability! Do not move
133
134  // Remove unloadable entries and classes from system dictionary
135  // The placeholder array has been handled in always_strong_oops_do.
136  DictionaryEntry* probe = NULL;
137  for (index = 0; index < table_size(); index++) {
138    for (DictionaryEntry** p = bucket_addr(index); *p != NULL; ) {
139      probe = *p;
140      klassOop e = probe->klass();
141      oop class_loader = probe->loader();
142
143      instanceKlass* ik = instanceKlass::cast(e);
144      if (ik->previous_versions() != NULL) {
145        // This klass has previous versions so see what we can cleanup
146        // while it is safe to do so.
147
148        int gc_count = 0;    // leave debugging breadcrumbs
149        int live_count = 0;
150
151        // RC_TRACE macro has an embedded ResourceMark
152        RC_TRACE(0x00000200, ("unload: %s: previous version length=%d",
153          ik->external_name(), ik->previous_versions()->length()));
154
155        for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
156          // check the previous versions array for GC'ed weak refs
157          PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
158          jobject cp_ref = pv_node->prev_constant_pool();
159          assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
160          if (cp_ref == NULL) {
161            delete pv_node;
162            ik->previous_versions()->remove_at(i);
163            // Since we are traversing the array backwards, we don't have to
164            // do anything special with the index.
165            continue;  // robustness
166          }
167
168          constantPoolOop pvcp = (constantPoolOop)JNIHandles::resolve(cp_ref);
169          if (pvcp == NULL) {
170            // this entry has been GC'ed so remove it
171            delete pv_node;
172            ik->previous_versions()->remove_at(i);
173            // Since we are traversing the array backwards, we don't have to
174            // do anything special with the index.
175            gc_count++;
176            continue;
177          } else {
178            RC_TRACE(0x00000200, ("unload: previous version @%d is alive", i));
179            if (is_alive->do_object_b(pvcp)) {
180              live_count++;
181            } else {
182              guarantee(false, "sanity check");
183            }
184          }
185
186          GrowableArray<jweak>* method_refs = pv_node->prev_EMCP_methods();
187          if (method_refs != NULL) {
188            RC_TRACE(0x00000200, ("unload: previous methods length=%d",
189              method_refs->length()));
190            for (int j = method_refs->length() - 1; j >= 0; j--) {
191              jweak method_ref = method_refs->at(j);
192              assert(method_ref != NULL, "weak method ref was unexpectedly cleared");
193              if (method_ref == NULL) {
194                method_refs->remove_at(j);
195                // Since we are traversing the array backwards, we don't have to
196                // do anything special with the index.
197                continue;  // robustness
198              }
199
200              methodOop method = (methodOop)JNIHandles::resolve(method_ref);
201              if (method == NULL) {
202                // this method entry has been GC'ed so remove it
203                JNIHandles::destroy_weak_global(method_ref);
204                method_refs->remove_at(j);
205              } else {
206                // RC_TRACE macro has an embedded ResourceMark
207                RC_TRACE(0x00000200,
208                  ("unload: %s(%s): prev method @%d in version @%d is alive",
209                  method->name()->as_C_string(),
210                  method->signature()->as_C_string(), j, i));
211              }
212            }
213          }
214        }
215        assert(ik->previous_versions()->length() == live_count, "sanity check");
216        RC_TRACE(0x00000200,
217          ("unload: previous version stats: live=%d, GC'ed=%d", live_count,
218          gc_count));
219      }
220
221      // Non-unloadable classes were handled in always_strong_oops_do
222      if (!is_strongly_reachable(class_loader, e)) {
223        // Entry was not visited in phase1 (negated test from phase1)
224        assert(class_loader != NULL, "unloading entry with null class loader");
225        oop k_def_class_loader = ik->class_loader();
226
227        // Do we need to delete this system dictionary entry?
228        bool purge_entry = false;
229
230        // Do we need to delete this system dictionary entry?
231        if (!is_alive->do_object_b(class_loader)) {
232          // If the loader is not live this entry should always be
233          // removed (will never be looked up again). Note that this is
234          // not the same as unloading the referred class.
235          if (k_def_class_loader == class_loader) {
236            // This is the defining entry, so the referred class is about
237            // to be unloaded.
238            // Notify the debugger and clean up the class.
239            guarantee(!is_alive->do_object_b(e),
240                      "klass should not be live if defining loader is not");
241            class_was_unloaded = true;
242            // notify the debugger
243            if (JvmtiExport::should_post_class_unload()) {
244              JvmtiExport::post_class_unload(ik->as_klassOop());
245            }
246
247            // notify ClassLoadingService of class unload
248            ClassLoadingService::notify_class_unloaded(ik);
249
250            // Clean up C heap
251            ik->release_C_heap_structures();
252          }
253          // Also remove this system dictionary entry.
254          purge_entry = true;
255
256        } else {
257          // The loader in this entry is alive. If the klass is dead,
258          // the loader must be an initiating loader (rather than the
259          // defining loader). Remove this entry.
260          if (!is_alive->do_object_b(e)) {
261            guarantee(!is_alive->do_object_b(k_def_class_loader),
262                      "defining loader should not be live if klass is not");
263            // If we get here, the class_loader must not be the defining
264            // loader, it must be an initiating one.
265            assert(k_def_class_loader != class_loader,
266                   "cannot have live defining loader and unreachable klass");
267
268            // Loader is live, but class and its defining loader are dead.
269            // Remove the entry. The class is going away.
270            purge_entry = true;
271          }
272        }
273
274        if (purge_entry) {
275          *p = probe->next();
276          if (probe == _current_class_entry) {
277            _current_class_entry = NULL;
278          }
279          free_entry(probe);
280          continue;
281        }
282      }
283      p = probe->next_addr();
284    }
285  }
286  return class_was_unloaded;
287}
288
289
290void Dictionary::always_strong_classes_do(OopClosure* blk) {
291  // Follow all system classes and temporary placeholders in dictionary
292  for (int index = 0; index < table_size(); index++) {
293    for (DictionaryEntry *probe = bucket(index);
294                          probe != NULL;
295                          probe = probe->next()) {
296      oop e = probe->klass();
297      oop class_loader = probe->loader();
298      if (is_strongly_reachable(class_loader, e)) {
299        blk->do_oop((oop*)probe->klass_addr());
300        if (class_loader != NULL) {
301          blk->do_oop(probe->loader_addr());
302        }
303        probe->protection_domain_set_oops_do(blk);
304      }
305    }
306  }
307}
308
309
310//   Just the classes from defining class loaders
311void Dictionary::classes_do(void f(klassOop)) {
312  for (int index = 0; index < table_size(); index++) {
313    for (DictionaryEntry* probe = bucket(index);
314                          probe != NULL;
315                          probe = probe->next()) {
316      klassOop k = probe->klass();
317      if (probe->loader() == instanceKlass::cast(k)->class_loader()) {
318        f(k);
319      }
320    }
321  }
322}
323
324// Added for initialize_itable_for_klass to handle exceptions
325//   Just the classes from defining class loaders
326void Dictionary::classes_do(void f(klassOop, TRAPS), TRAPS) {
327  for (int index = 0; index < table_size(); index++) {
328    for (DictionaryEntry* probe = bucket(index);
329                          probe != NULL;
330                          probe = probe->next()) {
331      klassOop k = probe->klass();
332      if (probe->loader() == instanceKlass::cast(k)->class_loader()) {
333        f(k, CHECK);
334      }
335    }
336  }
337}
338
339
340//   All classes, and their class loaders
341//   (added for helpers that use HandleMarks and ResourceMarks)
342// Don't iterate over placeholders
343void Dictionary::classes_do(void f(klassOop, oop, TRAPS), TRAPS) {
344  for (int index = 0; index < table_size(); index++) {
345    for (DictionaryEntry* probe = bucket(index);
346                          probe != NULL;
347                          probe = probe->next()) {
348      klassOop k = probe->klass();
349      f(k, probe->loader(), CHECK);
350    }
351  }
352}
353
354
355//   All classes, and their class loaders
356// Don't iterate over placeholders
357void Dictionary::classes_do(void f(klassOop, oop)) {
358  for (int index = 0; index < table_size(); index++) {
359    for (DictionaryEntry* probe = bucket(index);
360                          probe != NULL;
361                          probe = probe->next()) {
362      klassOop k = probe->klass();
363      f(k, probe->loader());
364    }
365  }
366}
367
368
369void Dictionary::oops_do(OopClosure* f) {
370  for (int index = 0; index < table_size(); index++) {
371    for (DictionaryEntry* probe = bucket(index);
372                          probe != NULL;
373                          probe = probe->next()) {
374      f->do_oop((oop*)probe->klass_addr());
375      if (probe->loader() != NULL) {
376        f->do_oop(probe->loader_addr());
377      }
378      probe->protection_domain_set_oops_do(f);
379    }
380  }
381}
382
383
384void Dictionary::methods_do(void f(methodOop)) {
385  for (int index = 0; index < table_size(); index++) {
386    for (DictionaryEntry* probe = bucket(index);
387                          probe != NULL;
388                          probe = probe->next()) {
389      klassOop k = probe->klass();
390      if (probe->loader() == instanceKlass::cast(k)->class_loader()) {
391        // only take klass is we have the entry with the defining class loader
392        instanceKlass::cast(k)->methods_do(f);
393      }
394    }
395  }
396}
397
398
399klassOop Dictionary::try_get_next_class() {
400  while (true) {
401    if (_current_class_entry != NULL) {
402      klassOop k = _current_class_entry->klass();
403      _current_class_entry = _current_class_entry->next();
404      return k;
405    }
406    _current_class_index = (_current_class_index + 1) % table_size();
407    _current_class_entry = bucket(_current_class_index);
408  }
409  // never reached
410}
411
412
413// Add a loaded class to the system dictionary.
414// Readers of the SystemDictionary aren't always locked, so _buckets
415// is volatile. The store of the next field in the constructor is
416// also cast to volatile;  we do this to ensure store order is maintained
417// by the compilers.
418
419void Dictionary::add_klass(symbolHandle class_name, Handle class_loader,
420                           KlassHandle obj) {
421  assert_locked_or_safepoint(SystemDictionary_lock);
422  assert(obj() != NULL, "adding NULL obj");
423  assert(Klass::cast(obj())->name() == class_name(), "sanity check on name");
424
425  unsigned int hash = compute_hash(class_name, class_loader);
426  int index = hash_to_index(hash);
427  DictionaryEntry* entry = new_entry(hash, obj(), class_loader());
428  add_entry(index, entry);
429}
430
431
432// This routine does not lock the system dictionary.
433//
434// Since readers don't hold a lock, we must make sure that system
435// dictionary entries are only removed at a safepoint (when only one
436// thread is running), and are added to in a safe way (all links must
437// be updated in an MT-safe manner).
438//
439// Callers should be aware that an entry could be added just after
440// _buckets[index] is read here, so the caller will not see the new entry.
441DictionaryEntry* Dictionary::get_entry(int index, unsigned int hash,
442                                       symbolHandle class_name,
443                                       Handle class_loader) {
444  symbolOop name_ = class_name();
445  oop loader_ = class_loader();
446  debug_only(_lookup_count++);
447  for (DictionaryEntry* entry = bucket(index);
448                        entry != NULL;
449                        entry = entry->next()) {
450    if (entry->hash() == hash && entry->equals(name_, loader_)) {
451      return entry;
452    }
453    debug_only(_lookup_length++);
454  }
455  return NULL;
456}
457
458
459klassOop Dictionary::find(int index, unsigned int hash, symbolHandle name,
460                          Handle loader, Handle protection_domain, TRAPS) {
461  DictionaryEntry* entry = get_entry(index, hash, name, loader);
462  if (entry != NULL && entry->is_valid_protection_domain(protection_domain)) {
463    return entry->klass();
464  } else {
465    return NULL;
466  }
467}
468
469
470klassOop Dictionary::find_class(int index, unsigned int hash,
471                                symbolHandle name, Handle loader) {
472  assert_locked_or_safepoint(SystemDictionary_lock);
473  assert (index == index_for(name, loader), "incorrect index?");
474
475  DictionaryEntry* entry = get_entry(index, hash, name, loader);
476  return (entry != NULL) ? entry->klass() : (klassOop)NULL;
477}
478
479
480// Variant of find_class for shared classes.  No locking required, as
481// that table is static.
482
483klassOop Dictionary::find_shared_class(int index, unsigned int hash,
484                                       symbolHandle name) {
485  assert (index == index_for(name, Handle()), "incorrect index?");
486
487  DictionaryEntry* entry = get_entry(index, hash, name, Handle());
488  return (entry != NULL) ? entry->klass() : (klassOop)NULL;
489}
490
491
492void Dictionary::add_protection_domain(int index, unsigned int hash,
493                                       instanceKlassHandle klass,
494                                       Handle loader, Handle protection_domain,
495                                       TRAPS) {
496  symbolHandle klass_name(THREAD, klass->name());
497  DictionaryEntry* entry = get_entry(index, hash, klass_name, loader);
498
499  assert(entry != NULL,"entry must be present, we just created it");
500  assert(protection_domain() != NULL,
501         "real protection domain should be present");
502
503  entry->add_protection_domain(protection_domain());
504
505  assert(entry->contains_protection_domain(protection_domain()),
506         "now protection domain should be present");
507}
508
509
510bool Dictionary::is_valid_protection_domain(int index, unsigned int hash,
511                                            symbolHandle name,
512                                            Handle loader,
513                                            Handle protection_domain) {
514  DictionaryEntry* entry = get_entry(index, hash, name, loader);
515  return entry->is_valid_protection_domain(protection_domain);
516}
517
518
519void Dictionary::reorder_dictionary() {
520
521  // Copy all the dictionary entries into a single master list.
522
523  DictionaryEntry* master_list = NULL;
524  for (int i = 0; i < table_size(); ++i) {
525    DictionaryEntry* p = bucket(i);
526    while (p != NULL) {
527      DictionaryEntry* tmp;
528      tmp = p->next();
529      p->set_next(master_list);
530      master_list = p;
531      p = tmp;
532    }
533    set_entry(i, NULL);
534  }
535
536  // Add the dictionary entries back to the list in the correct buckets.
537  Thread *thread = Thread::current();
538
539  while (master_list != NULL) {
540    DictionaryEntry* p = master_list;
541    master_list = master_list->next();
542    p->set_next(NULL);
543    symbolHandle class_name (thread, instanceKlass::cast((klassOop)(p->klass()))->name());
544    unsigned int hash = compute_hash(class_name, Handle(thread, p->loader()));
545    int index = hash_to_index(hash);
546    p->set_hash(hash);
547    p->set_next(bucket(index));
548    set_entry(index, p);
549  }
550}
551
552SymbolPropertyTable::SymbolPropertyTable(int table_size)
553  : Hashtable(table_size, sizeof(SymbolPropertyEntry))
554{
555}
556SymbolPropertyTable::SymbolPropertyTable(int table_size, HashtableBucket* t,
557                                         int number_of_entries)
558  : Hashtable(table_size, sizeof(SymbolPropertyEntry), t, number_of_entries)
559{
560}
561
562
563SymbolPropertyEntry* SymbolPropertyTable::find_entry(int index, unsigned int hash,
564                                                     symbolHandle sym,
565                                                     intptr_t sym_mode) {
566  assert(index == index_for(sym, sym_mode), "incorrect index?");
567  for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
568    if (p->hash() == hash && p->symbol() == sym() && p->symbol_mode() == sym_mode) {
569      return p;
570    }
571  }
572  return NULL;
573}
574
575
576SymbolPropertyEntry* SymbolPropertyTable::add_entry(int index, unsigned int hash,
577                                                    symbolHandle sym, intptr_t sym_mode) {
578  assert_locked_or_safepoint(SystemDictionary_lock);
579  assert(index == index_for(sym, sym_mode), "incorrect index?");
580  assert(find_entry(index, hash, sym, sym_mode) == NULL, "no double entry");
581
582  SymbolPropertyEntry* p = new_entry(hash, sym(), sym_mode);
583  Hashtable::add_entry(index, p);
584  return p;
585}
586
587
588void SymbolPropertyTable::oops_do(OopClosure* f) {
589  for (int index = 0; index < table_size(); index++) {
590    for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
591      f->do_oop((oop*) p->symbol_addr());
592      if (p->property_oop() != NULL) {
593        f->do_oop(p->property_oop_addr());
594      }
595    }
596  }
597}
598
599void SymbolPropertyTable::methods_do(void f(methodOop)) {
600  for (int index = 0; index < table_size(); index++) {
601    for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
602      oop prop = p->property_oop();
603      if (prop != NULL && prop->is_method()) {
604        f((methodOop)prop);
605      }
606    }
607  }
608}
609
610
611// ----------------------------------------------------------------------------
612#ifndef PRODUCT
613
614void Dictionary::print() {
615  ResourceMark rm;
616  HandleMark   hm;
617
618  tty->print_cr("Java system dictionary (classes=%d)", number_of_entries());
619  tty->print_cr("^ indicates that initiating loader is different from "
620                "defining loader");
621
622  for (int index = 0; index < table_size(); index++) {
623    for (DictionaryEntry* probe = bucket(index);
624                          probe != NULL;
625                          probe = probe->next()) {
626      if (Verbose) tty->print("%4d: ", index);
627      klassOop e = probe->klass();
628      oop class_loader =  probe->loader();
629      bool is_defining_class =
630         (class_loader == instanceKlass::cast(e)->class_loader());
631      tty->print("%s%s", is_defining_class ? " " : "^",
632                   Klass::cast(e)->external_name());
633      if (class_loader != NULL) {
634        tty->print(", loader ");
635        class_loader->print_value();
636      }
637      tty->cr();
638    }
639  }
640}
641
642#endif
643
644void Dictionary::verify() {
645  guarantee(number_of_entries() >= 0, "Verify of system dictionary failed");
646  int element_count = 0;
647  for (int index = 0; index < table_size(); index++) {
648    for (DictionaryEntry* probe = bucket(index);
649                          probe != NULL;
650                          probe = probe->next()) {
651      klassOop e = probe->klass();
652      oop class_loader = probe->loader();
653      guarantee(Klass::cast(e)->oop_is_instance(),
654                              "Verify of system dictionary failed");
655      // class loader must be present;  a null class loader is the
656      // boostrap loader
657      guarantee(class_loader == NULL || class_loader->is_instance(),
658                "checking type of class_loader");
659      e->verify();
660      probe->verify_protection_domain_set();
661      element_count++;
662    }
663  }
664  guarantee(number_of_entries() == element_count,
665            "Verify of system dictionary failed");
666  debug_only(verify_lookup_length((double)number_of_entries() / table_size()));
667}
668