1 /*
   2  * Copyright (c) 2003, 2017, 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/loaderConstraints.hpp"
  28 #include "logging/log.hpp"
  29 #include "logging/logStream.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/oop.inline.hpp"
  32 #include "runtime/handles.inline.hpp"
  33 #include "runtime/safepoint.hpp"
  34 #include "utilities/hashtable.inline.hpp"
  35 
  36 void LoaderConstraintEntry::set_loader(int i, oop p) {
  37   set_loader_data(i, ClassLoaderData::class_loader_data(p));
  38 }
  39 
  40 LoaderConstraintTable::LoaderConstraintTable(int nof_buckets)
  41   : Hashtable<InstanceKlass*, mtClass>(nof_buckets, sizeof(LoaderConstraintEntry)) {};
  42 
  43 
  44 LoaderConstraintEntry* LoaderConstraintTable::new_entry(
  45                                  unsigned int hash, Symbol* name,
  46                                  InstanceKlass* klass, int num_loaders,
  47                                  int max_loaders) {
  48   LoaderConstraintEntry* entry;
  49   entry = (LoaderConstraintEntry*)Hashtable<InstanceKlass*, mtClass>::new_entry(hash, klass);
  50   entry->set_name(name);
  51   entry->set_num_loaders(num_loaders);
  52   entry->set_max_loaders(max_loaders);
  53   return entry;
  54 }
  55 
  56 void LoaderConstraintTable::free_entry(LoaderConstraintEntry *entry) {
  57   // decrement name refcount before freeing
  58   entry->name()->decrement_refcount();
  59   Hashtable<InstanceKlass*, mtClass>::free_entry(entry);
  60 }
  61 
  62 // The loaderConstraintTable must always be accessed with the
  63 // SystemDictionary lock held. This is true even for readers as
  64 // entries in the table could be being dynamically resized.
  65 
  66 LoaderConstraintEntry** LoaderConstraintTable::find_loader_constraint(
  67                                     Symbol* name, Handle loader) {
  68 
  69   unsigned int hash = compute_hash(name);
  70   int index = hash_to_index(hash);
  71   LoaderConstraintEntry** pp = bucket_addr(index);
  72   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(loader());
  73 
  74   while (*pp) {
  75     LoaderConstraintEntry* p = *pp;
  76     if (p->hash() == hash) {
  77       if (p->name() == name) {
  78         for (int i = p->num_loaders() - 1; i >= 0; i--) {
  79           if (p->loader_data(i) == loader_data) {
  80             return pp;
  81           }
  82         }
  83       }
  84     }
  85     pp = p->next_addr();
  86   }
  87   return pp;
  88 }
  89 
  90 
  91 void LoaderConstraintTable::purge_loader_constraints() {
  92   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
  93   LogTarget(Info, class, loader, constraints) lt;
  94   // Remove unloaded entries from constraint table
  95   for (int index = 0; index < table_size(); index++) {
  96     LoaderConstraintEntry** p = bucket_addr(index);
  97     while(*p) {
  98       LoaderConstraintEntry* probe = *p;
  99       InstanceKlass* klass = probe->klass();
 100       // Remove klass that is no longer alive
 101       if (klass != NULL &&
 102           klass->class_loader_data()->is_unloading()) {
 103         probe->set_klass(NULL);
 104         if (lt.is_enabled()) {
 105           ResourceMark rm;
 106           LogStream ls(lt);
 107           ls.print_cr("purging class object from constraint for name %s,"
 108                      " loader list:",
 109                      probe->name()->as_C_string());
 110           for (int i = 0; i < probe->num_loaders(); i++) {
 111             ls.print_cr("    [%d]: %s", i,
 112                           probe->loader_data(i)->loader_name());
 113           }
 114         }
 115       }
 116       // Remove entries no longer alive from loader array
 117       int n = 0;
 118       while (n < probe->num_loaders()) {
 119         if (probe->loader_data(n)->is_unloading()) {
 120             if (lt.is_enabled()) {
 121               ResourceMark rm;
 122               LogStream ls(lt);
 123               ls.print_cr("purging loader %s from constraint for name %s",
 124                             probe->loader_data(n)->loader_name(),
 125                             probe->name()->as_C_string()
 126                             );
 127             }
 128 
 129             // Compact array
 130             int num = probe->num_loaders() - 1;
 131             probe->set_num_loaders(num);
 132           probe->set_loader_data(n, probe->loader_data(num));
 133           probe->set_loader_data(num, NULL);
 134 
 135             if (lt.is_enabled()) {
 136               ResourceMark rm;
 137               LogStream ls(lt);
 138               ls.print_cr("new loader list:");
 139               for (int i = 0; i < probe->num_loaders(); i++) {
 140                 ls.print_cr("    [%d]: %s", i,
 141                               probe->loader_data(i)->loader_name());
 142               }
 143             }
 144 
 145             continue;  // current element replaced, so restart without
 146                        // incrementing n
 147           }
 148         n++;
 149       }
 150       // Check whether entry should be purged
 151       if (probe->num_loaders() < 2) {
 152             if (lt.is_enabled()) {
 153               ResourceMark rm;
 154               LogStream(lt).print_cr("purging complete constraint for name %s",
 155                          probe->name()->as_C_string());
 156             }
 157 
 158         // Purge entry
 159         *p = probe->next();
 160         FREE_C_HEAP_ARRAY(oop, probe->loaders());
 161         free_entry(probe);
 162       } else {
 163 #ifdef ASSERT
 164         if (probe->klass() != NULL) {
 165           ClassLoaderData* loader_data =
 166             probe->klass()->class_loader_data();
 167           assert(!loader_data->is_unloading(), "klass should be live");
 168         }
 169 #endif
 170         // Go to next entry
 171         p = probe->next_addr();
 172       }
 173     }
 174   }
 175 }
 176 
 177 void log_ldr_constraint_msg(Symbol* class_name, const char* reason,
 178                         Handle class_loader1, Handle class_loader2) {
 179   LogTarget(Info, class, loader, constraints) lt;
 180   if (lt.is_enabled()) {
 181     ResourceMark rm;
 182     lt.print("Failed to add constraint for name: %s, loader[0]: %s,"
 183                 " loader[1]: %s, Reason: %s",
 184                   class_name->as_C_string(),
 185                   SystemDictionary::loader_name(class_loader1()),
 186                   SystemDictionary::loader_name(class_loader2()),
 187                   reason);
 188   }
 189 }
 190 
 191 bool LoaderConstraintTable::add_entry(Symbol* class_name,
 192                                       InstanceKlass* klass1, Handle class_loader1,
 193                                       InstanceKlass* klass2, Handle class_loader2) {
 194   LogTarget(Info, class, loader, constraints) lt;
 195   if (klass1 != NULL && klass2 != NULL) {
 196     if (klass1 == klass2) {
 197       // Same type already loaded in both places.  There is no need for any constraint.
 198       return true;
 199     } else {
 200       log_ldr_constraint_msg(class_name,
 201                              "The class objects presented by loader[0] and loader[1] "
 202                              "are different",
 203                              class_loader1, class_loader2);
 204       return false;
 205     }
 206   }
 207 
 208   InstanceKlass* klass = klass1 != NULL ? klass1 : klass2;
 209   LoaderConstraintEntry** pp1 = find_loader_constraint(class_name, class_loader1);
 210   if (*pp1 != NULL && (*pp1)->klass() != NULL) {
 211     if (klass != NULL) {
 212       if (klass != (*pp1)->klass()) {
 213         log_ldr_constraint_msg(class_name,
 214                                "The class object presented by loader[0] does not match "
 215                                "the stored class object in the constraint",
 216                                class_loader1, class_loader2);
 217         return false;
 218       }
 219     } else {
 220       klass = (*pp1)->klass();
 221     }
 222   }
 223 
 224   LoaderConstraintEntry** pp2 = find_loader_constraint(class_name, class_loader2);
 225   if (*pp2 != NULL && (*pp2)->klass() != NULL) {
 226     if (klass != NULL) {
 227       if (klass != (*pp2)->klass()) {
 228         log_ldr_constraint_msg(class_name,
 229                                "The class object presented by loader[1] does not match "
 230                                "the stored class object in the constraint",
 231                                class_loader1, class_loader2);
 232         return false;
 233       }
 234     } else {
 235       klass = (*pp2)->klass();
 236     }
 237   }
 238 
 239   if (*pp1 == NULL && *pp2 == NULL) {
 240     unsigned int hash = compute_hash(class_name);
 241     int index = hash_to_index(hash);
 242     LoaderConstraintEntry* p;
 243     p = new_entry(hash, class_name, klass, 2, 2);
 244     p->set_loaders(NEW_C_HEAP_ARRAY(ClassLoaderData*, 2, mtClass));
 245     p->set_loader(0, class_loader1());
 246     p->set_loader(1, class_loader2());
 247     p->set_klass(klass);
 248     p->set_next(bucket(index));
 249     set_entry(index, p);
 250     if (lt.is_enabled()) {
 251       ResourceMark rm;
 252       LogStream ls(lt);
 253       ls.print_cr("adding new constraint for name: %s, loader[0]: %s,"
 254                     " loader[1]: %s",
 255                     class_name->as_C_string(),
 256                     SystemDictionary::loader_name(class_loader1()),
 257                     SystemDictionary::loader_name(class_loader2())
 258                     );
 259     }
 260   } else if (*pp1 == *pp2) {
 261     /* constraint already imposed */
 262     if ((*pp1)->klass() == NULL) {
 263       (*pp1)->set_klass(klass);
 264       if (lt.is_enabled()) {
 265         ResourceMark rm;
 266         LogStream ls(lt);
 267         ls.print_cr("setting class object in existing constraint for"
 268                       " name: %s and loader %s",
 269                       class_name->as_C_string(),
 270                       SystemDictionary::loader_name(class_loader1())
 271                       );
 272       }
 273     } else {
 274       assert((*pp1)->klass() == klass, "loader constraints corrupted");
 275     }
 276   } else if (*pp1 == NULL) {
 277     extend_loader_constraint(*pp2, class_loader1, klass);
 278   } else if (*pp2 == NULL) {
 279     extend_loader_constraint(*pp1, class_loader2, klass);
 280   } else {
 281     merge_loader_constraints(pp1, pp2, klass);
 282   }
 283 
 284   return true;
 285 }
 286 
 287 
 288 // return true if the constraint was updated, false if the constraint is
 289 // violated
 290 bool LoaderConstraintTable::check_or_update(InstanceKlass* k,
 291                                             Handle loader,
 292                                             Symbol* name) {
 293   LogTarget(Info, class, loader, constraints) lt;
 294   LoaderConstraintEntry* p = *(find_loader_constraint(name, loader));
 295   if (p && p->klass() != NULL && p->klass() != k) {
 296     if (lt.is_enabled()) {
 297       ResourceMark rm;
 298       LogStream ls(lt);
 299       ls.print_cr("constraint check failed for name %s, loader %s: "
 300                  "the presented class object differs from that stored",
 301                  name->as_C_string(),
 302                  SystemDictionary::loader_name(loader()));
 303     }
 304     return false;
 305   } else {
 306     if (p && p->klass() == NULL) {
 307       p->set_klass(k);
 308       if (lt.is_enabled()) {
 309         ResourceMark rm;
 310         LogStream ls(lt);
 311         ls.print_cr("updating constraint for name %s, loader %s, "
 312                    "by setting class object",
 313                    name->as_C_string(),
 314                    SystemDictionary::loader_name(loader()));
 315       }
 316     }
 317     return true;
 318   }
 319 }
 320 
 321 InstanceKlass* LoaderConstraintTable::find_constrained_klass(Symbol* name,
 322                                                        Handle loader) {
 323   LoaderConstraintEntry *p = *(find_loader_constraint(name, loader));
 324   if (p != NULL && p->klass() != NULL) {
 325     assert(p->klass()->is_instance_klass(), "sanity");
 326     if (p->klass()->is_loaded()) {
 327       // Only return fully loaded classes.  Classes found through the
 328       // constraints might still be in the process of loading.
 329       return NULL;
 330     }
 331     return p->klass();
 332   }
 333 
 334   // No constraints, or else no klass loaded yet.
 335   return NULL;
 336 }
 337 
 338 void LoaderConstraintTable::ensure_loader_constraint_capacity(
 339                                                      LoaderConstraintEntry *p,
 340                                                     int nfree) {
 341     if (p->max_loaders() - p->num_loaders() < nfree) {
 342         int n = nfree + p->num_loaders();
 343         ClassLoaderData** new_loaders = NEW_C_HEAP_ARRAY(ClassLoaderData*, n, mtClass);
 344         memcpy(new_loaders, p->loaders(), sizeof(ClassLoaderData*) * p->num_loaders());
 345         p->set_max_loaders(n);
 346         FREE_C_HEAP_ARRAY(ClassLoaderData*, p->loaders());
 347         p->set_loaders(new_loaders);
 348     }
 349 }
 350 
 351 
 352 void LoaderConstraintTable::extend_loader_constraint(LoaderConstraintEntry* p,
 353                                                      Handle loader,
 354                                                      InstanceKlass* klass) {
 355   ensure_loader_constraint_capacity(p, 1);
 356   int num = p->num_loaders();
 357   p->set_loader(num, loader());
 358   p->set_num_loaders(num + 1);
 359   LogTarget(Info, class, loader, constraints) lt;
 360   if (lt.is_enabled()) {
 361     ResourceMark rm;
 362     LogStream ls(lt);
 363     ls.print_cr("extending constraint for name %s by adding loader[%d]: %s %s",
 364                p->name()->as_C_string(),
 365                num,
 366                SystemDictionary::loader_name(loader()),
 367                (p->klass() == NULL ? " and setting class object" : "")
 368                );
 369   }
 370   if (p->klass() == NULL) {
 371     p->set_klass(klass);
 372   } else {
 373     assert(klass == NULL || p->klass() == klass, "constraints corrupted");
 374   }
 375 }
 376 
 377 
 378 void LoaderConstraintTable::merge_loader_constraints(
 379                                                    LoaderConstraintEntry** pp1,
 380                                                    LoaderConstraintEntry** pp2,
 381                                                    InstanceKlass* klass) {
 382   // make sure *pp1 has higher capacity
 383   if ((*pp1)->max_loaders() < (*pp2)->max_loaders()) {
 384     LoaderConstraintEntry** tmp = pp2;
 385     pp2 = pp1;
 386     pp1 = tmp;
 387   }
 388 
 389   LoaderConstraintEntry* p1 = *pp1;
 390   LoaderConstraintEntry* p2 = *pp2;
 391 
 392   ensure_loader_constraint_capacity(p1, p2->num_loaders());
 393 
 394   for (int i = 0; i < p2->num_loaders(); i++) {
 395     int num = p1->num_loaders();
 396     p1->set_loader_data(num, p2->loader_data(i));
 397     p1->set_num_loaders(num + 1);
 398   }
 399 
 400   LogTarget(Info, class, loader, constraints) lt;
 401   if (lt.is_enabled()) {
 402     ResourceMark rm;
 403     LogStream ls(lt);
 404     ls.print_cr("merged constraints for name %s, new loader list:",
 405                   p1->name()->as_C_string()
 406                   );
 407 
 408     for (int i = 0; i < p1->num_loaders(); i++) {
 409       ls.print_cr("    [%d]: %s", i,
 410                     p1->loader_data(i)->loader_name());
 411     }
 412     if (p1->klass() == NULL) {
 413       ls.print_cr("... and setting class object");
 414     }
 415   }
 416 
 417   // p1->klass() will hold NULL if klass, p2->klass(), and old
 418   // p1->klass() are all NULL.  In addition, all three must have
 419   // matching non-NULL values, otherwise either the constraints would
 420   // have been violated, or the constraints had been corrupted (and an
 421   // assertion would fail).
 422   if (p2->klass() != NULL) {
 423     assert(p2->klass() == klass, "constraints corrupted");
 424   }
 425   if (p1->klass() == NULL) {
 426     p1->set_klass(klass);
 427   } else {
 428     assert(p1->klass() == klass, "constraints corrupted");
 429   }
 430 
 431   *pp2 = p2->next();
 432   FREE_C_HEAP_ARRAY(oop, p2->loaders());
 433   free_entry(p2);
 434   return;
 435 }
 436 
 437 
 438 void LoaderConstraintTable::verify(Dictionary* dictionary,
 439                                    PlaceholderTable* placeholders) {
 440   Thread *thread = Thread::current();
 441   for (int cindex = 0; cindex < _loader_constraint_size; cindex++) {
 442     for (LoaderConstraintEntry* probe = bucket(cindex);
 443                                 probe != NULL;
 444                                 probe = probe->next()) {
 445       if (probe->klass() != NULL) {
 446         InstanceKlass* ik = probe->klass();
 447         guarantee(ik->name() == probe->name(), "name should match");
 448         Symbol* name = ik->name();
 449         ClassLoaderData* loader_data = ik->class_loader_data();
 450         unsigned int d_hash = dictionary->compute_hash(name, loader_data);
 451         int d_index = dictionary->hash_to_index(d_hash);
 452         InstanceKlass* k = dictionary->find_class(d_index, d_hash, name, loader_data);
 453         if (k != NULL) {
 454           // We found the class in the system dictionary, so we should
 455           // make sure that the Klass* matches what we already have.
 456           guarantee(k == probe->klass(), "klass should be in dictionary");
 457         } else {
 458           // If we don't find the class in the system dictionary, it
 459           // has to be in the placeholders table.
 460           unsigned int p_hash = placeholders->compute_hash(name, loader_data);
 461           int p_index = placeholders->hash_to_index(p_hash);
 462           PlaceholderEntry* entry = placeholders->get_entry(p_index, p_hash,
 463                                                             name, loader_data);
 464 
 465           // The InstanceKlass might not be on the entry, so the only
 466           // thing we can check here is whether we were successful in
 467           // finding the class in the placeholders table.
 468           guarantee(entry != NULL, "klass should be in the placeholders");
 469         }
 470       }
 471       for (int n = 0; n< probe->num_loaders(); n++) {
 472         assert(ClassLoaderDataGraph::contains_loader_data(probe->loader_data(n)), "The loader is missing");
 473       }
 474     }
 475   }
 476 }
 477 
 478 #ifndef PRODUCT
 479 
 480 // Called with the system dictionary lock held
 481 void LoaderConstraintTable::print() {
 482   ResourceMark rm;
 483   assert_locked_or_safepoint(SystemDictionary_lock);
 484   tty->print_cr("Java loader constraints (entries=%d)", _loader_constraint_size);
 485   for (int cindex = 0; cindex < _loader_constraint_size; cindex++) {
 486     for (LoaderConstraintEntry* probe = bucket(cindex);
 487                                 probe != NULL;
 488                                 probe = probe->next()) {
 489       tty->print("%4d: ", cindex);
 490       probe->name()->print();
 491       tty->print(" , loaders:");
 492       for (int n = 0; n < probe->num_loaders(); n++) {
 493         probe->loader_data(n)->print_value();
 494         tty->print(", ");
 495       }
 496       tty->cr();
 497     }
 498   }
 499 }
 500 #endif