1 /*
   2  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2018 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/classLoaderDataGraph.hpp"
  30 #include "classfile/classLoaderHierarchyDCmd.hpp"
  31 #include "memory/allocation.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "runtime/safepoint.hpp"
  34 #include "oops/reflectionAccessorImplKlassHelper.hpp"
  35 #include "utilities/globalDefinitions.hpp"
  36 #include "utilities/ostream.hpp"
  37 
  38 
  39 ClassLoaderHierarchyDCmd::ClassLoaderHierarchyDCmd(outputStream* output, bool heap)
  40   : DCmdWithParser(output, heap),
  41    _show_classes("show-classes", "Print loaded classes.", "BOOLEAN", false, "false"),
  42   _verbose("verbose", "Print detailed information.", "BOOLEAN", false, "false"),
  43   _fold("fold", "Show loaders of the same name and class as one.", "BOOLEAN", true, "true") {
  44   _dcmdparser.add_dcmd_option(&_show_classes);
  45   _dcmdparser.add_dcmd_option(&_verbose);
  46   _dcmdparser.add_dcmd_option(&_fold);
  47 }
  48 
  49 
  50 int ClassLoaderHierarchyDCmd::num_arguments() {
  51   ResourceMark rm;
  52   ClassLoaderHierarchyDCmd* dcmd = new ClassLoaderHierarchyDCmd(NULL, false);
  53   if (dcmd != NULL) {
  54     DCmdMark mark(dcmd);
  55     return dcmd->_dcmdparser.num_arguments();
  56   } else {
  57     return 0;
  58   }
  59 }
  60 
  61 // Helper class for drawing the branches to the left of a node.
  62 class BranchTracker : public StackObj {
  63   //       "<x>"
  64   //       " |---<y>"
  65   //       " |    |
  66   //       " |   <z>"
  67   //       " |    |---<z1>
  68   //       " |    |---<z2>
  69   //       ^^^^^^^ ^^^
  70   //        A       B
  71 
  72   // Some terms for the graphics:
  73   // - branch: vertical connection between a node's ancestor to a later sibling.
  74   // - branchwork: (A) the string to print as a prefix at the start of each line, contains all branches.
  75   // - twig (B): Length of the dashed line connecting a node to its branch.
  76   // - branch spacing: how many spaces between branches are printed.
  77 
  78 public:
  79 
  80   enum { max_depth = 64, twig_len = 2, branch_spacing = 5 };
  81 
  82 private:
  83 
  84   char _branches[max_depth];
  85   int _pos;
  86 
  87 public:
  88   BranchTracker()
  89     : _pos(0) {}
  90 
  91   void push(bool has_branch) {
  92     if (_pos < max_depth) {
  93       _branches[_pos] = has_branch ? '|' : ' ';
  94     }
  95     _pos ++; // beyond max depth, omit branch drawing but do count on.
  96   }
  97 
  98   void pop() {
  99     assert(_pos > 0, "must be");
 100     _pos --;
 101   }
 102 
 103   void print(outputStream* st) {
 104     for (int i = 0; i < _pos; i ++) {
 105       st->print("%c%.*s", _branches[i], branch_spacing, "          ");
 106     }
 107   }
 108 
 109   class Mark {
 110     BranchTracker& _tr;
 111   public:
 112     Mark(BranchTracker& tr, bool has_branch_here)
 113       : _tr(tr)  { _tr.push(has_branch_here); }
 114     ~Mark() { _tr.pop(); }
 115   };
 116 
 117 }; // end: BranchTracker
 118 
 119 struct LoadedClassInfo : public ResourceObj {
 120 public:
 121   LoadedClassInfo* _next;
 122   Klass* const _klass;
 123   const ClassLoaderData* const _cld;
 124 
 125   LoadedClassInfo(Klass* klass, const ClassLoaderData* cld)
 126     : _klass(klass), _cld(cld) {}
 127 
 128 };
 129 
 130 class LoaderTreeNode : public ResourceObj {
 131 
 132   // We walk the CLDG and, for each CLD which is findable, add
 133   // a tree node.
 134   // To add a node we need its parent node; if the parent node does not yet
 135   // exist - because we have not yet encountered the CLD for the parent loader -
 136   // we add a preliminary empty LoaderTreeNode for it. This preliminary node
 137   // just contains the loader oop and nothing else. Once we encounter the CLD of
 138   // this parent loader, we fill in all the other details.
 139 
 140   const oop _loader_oop;
 141   const ClassLoaderData* _cld;
 142 
 143   LoaderTreeNode* _child;
 144   LoaderTreeNode* _next;
 145 
 146   LoadedClassInfo* _classes;
 147   int _num_classes;
 148 
 149   LoadedClassInfo* _anon_classes;
 150   int _num_anon_classes;
 151 
 152   // In default view, similar tree nodes (same loader class, same name or no name)
 153   // are folded into each other to make the output more readable.
 154   // _num_folded contains the number of nodes which have been folded into this
 155   // one.
 156   int _num_folded;
 157 
 158   void print_with_childs(outputStream* st, BranchTracker& branchtracker,
 159       bool print_classes, bool verbose) const {
 160 
 161     ResourceMark rm;
 162 
 163     if (_cld == NULL) {
 164       // Not sure how this could happen: we added a preliminary node for a parent but then never encountered
 165       // its CLD?
 166       return;
 167     }
 168 
 169     // Retrieve information.
 170     const Klass* const loader_klass = _cld->class_loader_klass();
 171     const Symbol* const loader_name = _cld->name();
 172 
 173     branchtracker.print(st);
 174 
 175     // e.g. "+--- jdk.internal.reflect.DelegatingClassLoader"
 176     st->print("+%.*s", BranchTracker::twig_len, "----------");
 177     if (_cld->is_the_null_class_loader_data()) {
 178       st->print(" <bootstrap>");
 179     } else {
 180       if (loader_name != NULL) {
 181         st->print(" \"%s\",", loader_name->as_C_string());
 182       }
 183       st->print(" %s", loader_klass != NULL ? loader_klass->external_name() : "??");
 184       if (_num_folded > 0) {
 185         st->print(" (+ %d more)", _num_folded);
 186       }
 187     }
 188     st->cr();
 189 
 190     // Output following this node (node details and child nodes) - up to the next sibling node
 191     // needs to be prefixed with "|" if there is a follow up sibling.
 192     const bool have_sibling = _next != NULL;
 193     BranchTracker::Mark trm(branchtracker, have_sibling);
 194 
 195     {
 196       // optional node details following this node needs to be prefixed with "|"
 197       // if there are follow up child nodes.
 198       const bool have_child = _child != NULL;
 199       BranchTracker::Mark trm(branchtracker, have_child);
 200 
 201       // Empty line
 202       branchtracker.print(st);
 203       st->cr();
 204 
 205       const int indentation = 18;
 206 
 207       if (verbose) {
 208         branchtracker.print(st);
 209         st->print_cr("%*s " PTR_FORMAT, indentation, "Loader Oop:", p2i(_loader_oop));
 210         branchtracker.print(st);
 211         st->print_cr("%*s " PTR_FORMAT, indentation, "Loader Data:", p2i(_cld));
 212         branchtracker.print(st);
 213         st->print_cr("%*s " PTR_FORMAT, indentation, "Loader Klass:", p2i(loader_klass));
 214 
 215         // Empty line
 216         branchtracker.print(st);
 217         st->cr();
 218       }
 219 
 220       if (print_classes) {
 221         if (_classes != NULL) {
 222           for (LoadedClassInfo* lci = _classes; lci; lci = lci->_next) {
 223             // Nonfindable and unsafe anonymous classes should live in the primary CLD of its loader
 224             assert(lci->_cld == _cld, "must be");
 225 
 226             branchtracker.print(st);
 227             if (lci == _classes) { // first iteration
 228               st->print("%*s ", indentation, "Classes:");
 229             } else {
 230               st->print("%*s ", indentation, "");
 231             }
 232             st->print("%s", lci->_klass->external_name());
 233 
 234             // Special treatment for generated core reflection accessor classes: print invocation target.
 235             if (ReflectionAccessorImplKlassHelper::is_generated_accessor(lci->_klass)) {
 236               st->print(" (invokes: ");
 237               ReflectionAccessorImplKlassHelper::print_invocation_target(st, lci->_klass);
 238               st->print(")");
 239             }
 240 
 241             st->cr();
 242           }
 243           branchtracker.print(st);
 244           st->print("%*s ", indentation, "");
 245           st->print_cr("(%u class%s)", _num_classes, (_num_classes == 1) ? "" : "es");
 246 
 247           // Empty line
 248           branchtracker.print(st);
 249           st->cr();
 250         }
 251 
 252         if (_anon_classes != NULL) {
 253           for (LoadedClassInfo* lci = _anon_classes; lci; lci = lci->_next) {
 254             branchtracker.print(st);
 255             if (lci == _anon_classes) { // first iteration
 256               st->print("%*s ", indentation, "Unsafe Anonymous Classes:");
 257             } else {
 258               st->print("%*s ", indentation, "");
 259             }
 260             st->print("%s", lci->_klass->external_name());
 261             // For nonfindable and unsafe anonymous classes, also print CLD if verbose. Should be a different one than the primary CLD.
 262             assert(lci->_cld != _cld, "must be");
 263             if (verbose) {
 264               st->print("  (Loader Data: " PTR_FORMAT ")", p2i(lci->_cld));
 265             }
 266             st->cr();
 267           }
 268           branchtracker.print(st);
 269           st->print("%*s ", indentation, "");
 270           st->print_cr("(%u unsafe anonymous class%s)", _num_anon_classes, (_num_anon_classes == 1) ? "" : "es");
 271 
 272           // Empty line
 273           branchtracker.print(st);
 274           st->cr();
 275         }
 276 
 277       } // end: print_classes
 278 
 279     } // Pop branchtracker mark
 280 
 281     // Print children, recursively
 282     LoaderTreeNode* c = _child;
 283     while (c != NULL) {
 284       c->print_with_childs(st, branchtracker, print_classes, verbose);
 285       c = c->_next;
 286     }
 287 
 288   }
 289 
 290   // Helper: Attempt to fold this node into the target node. If success, returns true.
 291   // Folding can be done if both nodes are leaf nodes and they refer to the same loader class
 292   // and they have the same name or no name (note: leaf check is done by caller).
 293   bool can_fold_into(LoaderTreeNode* target_node) const {
 294     assert(is_leaf() && target_node->is_leaf(), "must be leaf");
 295     return _cld->class_loader_klass() == target_node->_cld->class_loader_klass() &&
 296            _cld->name() == target_node->_cld->name();
 297   }
 298 
 299 public:
 300 
 301   LoaderTreeNode(const oop loader_oop)
 302     : _loader_oop(loader_oop), _cld(NULL), _child(NULL), _next(NULL),
 303       _classes(NULL), _num_classes(0), _anon_classes(NULL), _num_anon_classes(0),
 304       _num_folded(0)
 305     {}
 306 
 307   void set_cld(const ClassLoaderData* cld) {
 308     _cld = cld;
 309   }
 310 
 311   void add_child(LoaderTreeNode* info) {
 312     info->_next = _child;
 313     _child = info;
 314   }
 315 
 316   void add_sibling(LoaderTreeNode* info) {
 317     assert(info->_next == NULL, "must be");
 318     info->_next = _next;
 319     _next = info;
 320   }
 321 
 322   void add_classes(LoadedClassInfo* first_class, int num_classes, bool is_nonfindable) {
 323     LoadedClassInfo** p_list_to_add_to = is_nonfindable ? &_anon_classes : &_classes;
 324     // Search tail.
 325     while ((*p_list_to_add_to) != NULL) {
 326       p_list_to_add_to = &(*p_list_to_add_to)->_next;
 327     }
 328     *p_list_to_add_to = first_class;
 329     if (is_nonfindable) {
 330       _num_anon_classes += num_classes;
 331     } else {
 332       _num_classes += num_classes;
 333     }
 334   }
 335 
 336   const ClassLoaderData* cld() const {
 337     return _cld;
 338   }
 339 
 340   const oop loader_oop() const {
 341     return _loader_oop;
 342   }
 343 
 344   LoaderTreeNode* find(const oop loader_oop) {
 345     LoaderTreeNode* result = NULL;
 346     if (_loader_oop == loader_oop) {
 347       result = this;
 348     } else {
 349       LoaderTreeNode* c = _child;
 350       while (c != NULL && result == NULL) {
 351         result = c->find(loader_oop);
 352         c = c->_next;
 353       }
 354     }
 355     return result;
 356   }
 357 
 358   bool is_leaf() const { return _child == NULL; }
 359 
 360   // Attempt to fold similar nodes among this node's children. We only fold leaf nodes
 361   // (no child class loaders).
 362   // For non-leaf nodes (class loaders with child class loaders), do this recursivly.
 363   void fold_children() {
 364     LoaderTreeNode* node = _child;
 365     LoaderTreeNode* prev = NULL;
 366     while (node != NULL) {
 367       LoaderTreeNode* matching_node = NULL;
 368       if (node->is_leaf()) {
 369         // Look among the preceeding node siblings for a match.
 370         for (LoaderTreeNode* node2 = _child; node2 != node && matching_node == NULL;
 371             node2 = node2->_next) {
 372           if (node2->is_leaf() && node->can_fold_into(node2)) {
 373             matching_node = node2;
 374           }
 375         }
 376       } else {
 377         node->fold_children();
 378       }
 379       if (matching_node != NULL) {
 380         // Increase fold count for the matching node and remove folded node from the child list.
 381         matching_node->_num_folded ++;
 382         assert(prev != NULL, "Sanity"); // can never happen since we do not fold the first node.
 383         prev->_next = node->_next;
 384       } else {
 385         prev = node;
 386       }
 387       node = node->_next;
 388     }
 389   }
 390 
 391   void print_with_childs(outputStream* st, bool print_classes, bool print_add_info) const {
 392     BranchTracker bwt;
 393     print_with_childs(st, bwt, print_classes, print_add_info);
 394   }
 395 
 396 };
 397 
 398 class LoadedClassCollectClosure : public KlassClosure {
 399 public:
 400   LoadedClassInfo* _list;
 401   const ClassLoaderData* _cld;
 402   int _num_classes;
 403   LoadedClassCollectClosure(const ClassLoaderData* cld)
 404     : _list(NULL), _cld(cld), _num_classes(0) {}
 405   void do_klass(Klass* k) {
 406     LoadedClassInfo* lki = new LoadedClassInfo(k, _cld);
 407     lki->_next = _list;
 408     _list = lki;
 409     _num_classes ++;
 410   }
 411 };
 412 
 413 class LoaderInfoScanClosure : public CLDClosure {
 414 
 415   const bool _print_classes;
 416   const bool _verbose;
 417   LoaderTreeNode* _root;
 418 
 419   static void fill_in_classes(LoaderTreeNode* info, const ClassLoaderData* cld) {
 420     assert(info != NULL && cld != NULL, "must be");
 421     LoadedClassCollectClosure lccc(cld);
 422     const_cast<ClassLoaderData*>(cld)->classes_do(&lccc);
 423     if (lccc._num_classes > 0) {
 424       info->add_classes(lccc._list, lccc._num_classes, cld->is_shortlived());
 425     }
 426   }
 427 
 428   LoaderTreeNode* find_node_or_add_empty_node(oop loader_oop) {
 429 
 430     assert(_root != NULL, "root node must exist");
 431 
 432     if (loader_oop == NULL) {
 433       return _root;
 434     }
 435 
 436     // Check if a node for this oop already exists.
 437     LoaderTreeNode* info = _root->find(loader_oop);
 438 
 439     if (info == NULL) {
 440       // It does not. Create a node.
 441       info = new LoaderTreeNode(loader_oop);
 442 
 443       // Add it to tree.
 444       LoaderTreeNode* parent_info = NULL;
 445 
 446       // Recursively add parent nodes if needed.
 447       const oop parent_oop = java_lang_ClassLoader::parent(loader_oop);
 448       if (parent_oop == NULL) {
 449         parent_info = _root;
 450       } else {
 451         parent_info = find_node_or_add_empty_node(parent_oop);
 452       }
 453       assert(parent_info != NULL, "must be");
 454 
 455       parent_info->add_child(info);
 456     }
 457     return info;
 458   }
 459 
 460 
 461 public:
 462   LoaderInfoScanClosure(bool print_classes, bool verbose)
 463     : _print_classes(print_classes), _verbose(verbose), _root(NULL) {
 464     _root = new LoaderTreeNode(NULL);
 465   }
 466 
 467   void print_results(outputStream* st) const {
 468     _root->print_with_childs(st, _print_classes, _verbose);
 469   }
 470 
 471   void do_cld (ClassLoaderData* cld) {
 472 
 473     // We do not display unloading loaders, for now.
 474     if (!cld->is_alive()) {
 475       return;
 476     }
 477 
 478     const oop loader_oop = cld->class_loader();
 479 
 480     LoaderTreeNode* info = find_node_or_add_empty_node(loader_oop);
 481     assert(info != NULL, "must be");
 482 
 483     // Update CLD in node, but only if this is the primary CLD for this loader.
 484     if (cld->is_shortlived() == false) {
 485       assert(info->cld() == NULL, "there should be only one primary CLD per loader");
 486       info->set_cld(cld);
 487     }
 488 
 489     // Add classes.
 490     fill_in_classes(info, cld);
 491   }
 492 
 493   void fold() {
 494     _root->fold_children();
 495   }
 496 
 497 };
 498 
 499 
 500 class ClassLoaderHierarchyVMOperation : public VM_Operation {
 501   outputStream* const _out;
 502   const bool _show_classes;
 503   const bool _verbose;
 504   const bool _fold;
 505 public:
 506   ClassLoaderHierarchyVMOperation(outputStream* out, bool show_classes, bool verbose, bool fold) :
 507     _out(out), _show_classes(show_classes), _verbose(verbose), _fold(fold)
 508   {}
 509 
 510   VMOp_Type type() const {
 511     return VMOp_ClassLoaderHierarchyOperation;
 512   }
 513 
 514   void doit() {
 515     assert(SafepointSynchronize::is_at_safepoint(), "must be a safepoint");
 516     ResourceMark rm;
 517     LoaderInfoScanClosure cl (_show_classes, _verbose);
 518     ClassLoaderDataGraph::loaded_cld_do(&cl);
 519     // In non-verbose and non-show-classes mode, attempt to fold the tree.
 520     if (_fold) {
 521       if (!_verbose && !_show_classes) {
 522         cl.fold();
 523       }
 524     }
 525     cl.print_results(_out);
 526   }
 527 };
 528 
 529 // This command needs to be executed at a safepoint.
 530 void ClassLoaderHierarchyDCmd::execute(DCmdSource source, TRAPS) {
 531   ClassLoaderHierarchyVMOperation op(output(), _show_classes.value(), _verbose.value(), _fold.value());
 532   VMThread::execute(&op);
 533 }