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/classLoaderHierarchyDCmd.hpp"
  30 #include "memory/allocation.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "runtime/safepoint.hpp"
  33 #include "oops/reflectionAccessorImplKlassHelper.hpp"
  34 #include "utilities/globalDefinitions.hpp"
  35 #include "utilities/ostream.hpp"
  36 
  37 
  38 ClassLoaderHierarchyDCmd::ClassLoaderHierarchyDCmd(outputStream* output, bool heap)
  39   : DCmdWithParser(output, heap)
  40   , _show_classes("show-classes", "Print loaded classes.", "BOOLEAN", false, "false")
  41   , _verbose("verbose", "Print detailed information.", "BOOLEAN", false, "false") {
  42   _dcmdparser.add_dcmd_option(&_show_classes);
  43   _dcmdparser.add_dcmd_option(&_verbose);
  44 }
  45 
  46 
  47 int ClassLoaderHierarchyDCmd::num_arguments() {
  48   ResourceMark rm;
  49   ClassLoaderHierarchyDCmd* dcmd = new ClassLoaderHierarchyDCmd(NULL, false);
  50   if (dcmd != NULL) {
  51     DCmdMark mark(dcmd);
  52     return dcmd->_dcmdparser.num_arguments();
  53   } else {
  54     return 0;
  55   }
  56 }
  57 
  58 // Helper class for drawing the branches to the left of a node.
  59 class BranchTracker : public StackObj {
  60   //       "<x>"
  61   //       " |---<y>"
  62   //       " |    |
  63   //       " |   <z>"
  64   //       " |    |---<z1>
  65   //       " |    |---<z2>
  66   //       ^^^^^^^ ^^^
  67   //        A       B
  68 
  69   // Some terms for the graphics:
  70   // - branch: vertical connection between a node's ancestor to a later sibling.
  71   // - branchwork: (A) the string to print as a prefix at the start of each line, contains all branches.
  72   // - twig (B): Length of the dashed line connecting a node to its branch.
  73   // - branch spacing: how many spaces between branches are printed.
  74 
  75 public:
  76 
  77   enum { max_depth = 64, twig_len = 2, branch_spacing = 5 };
  78 
  79 private:
  80 
  81   char _branches[max_depth];
  82   int _pos;
  83 
  84 public:
  85   BranchTracker()
  86     : _pos(0) {}
  87 
  88   void push(bool has_branch) {
  89     if (_pos < max_depth) {
  90       _branches[_pos] = has_branch ? '|' : ' ';
  91     }
  92     _pos ++; // beyond max depth, omit branch drawing but do count on.
  93   }
  94 
  95   void pop() {
  96     assert(_pos > 0, "must be");
  97     _pos --;
  98   }
  99 
 100   void print(outputStream* st) {
 101     for (int i = 0; i < _pos; i ++) {
 102       st->print("%c%.*s", _branches[i], branch_spacing, "          ");
 103     }
 104   }
 105 
 106   class Mark {
 107     BranchTracker& _tr;
 108   public:
 109     Mark(BranchTracker& tr, bool has_branch_here)
 110       : _tr(tr)  { _tr.push(has_branch_here); }
 111     ~Mark() { _tr.pop(); }
 112   };
 113 
 114 }; // end: BranchTracker
 115 
 116 struct LoadedClassInfo : public ResourceObj {
 117 public:
 118   LoadedClassInfo* _next;
 119   Klass* const _klass;
 120   const ClassLoaderData* const _cld;
 121 
 122   LoadedClassInfo(Klass* klass, const ClassLoaderData* cld)
 123     : _klass(klass), _cld(cld) {}
 124 
 125 };
 126 
 127 class LoaderTreeNode : public ResourceObj {
 128 
 129   // We walk the CLDG and, for each CLD which is non-anonymous, add
 130   // a tree node. To add a node we need its parent node; if it itself
 131   // does not exist yet, we add a preliminary node for it. This preliminary
 132   // node just contains its loader oop; later, when encountering its CLD in
 133   // our CLDG walk, we complete the missing information in this node.
 134 
 135   const oop _loader_oop;
 136   const ClassLoaderData* _cld;
 137 
 138   LoaderTreeNode* _child;
 139   LoaderTreeNode* _next;
 140 
 141   LoadedClassInfo* _classes;
 142   int _num_classes;
 143 
 144   LoadedClassInfo* _anon_classes;
 145   int _num_anon_classes;
 146 
 147   void print_with_childs(outputStream* st, BranchTracker& branchtracker,
 148       bool print_classes, bool verbose) const {
 149 
 150     ResourceMark rm;
 151 
 152     if (_cld == NULL) {
 153       // Not sure how this could happen: we added a preliminary node for a parent but then never encountered
 154       // its CLD?
 155       return;
 156     }
 157 
 158     // Retrieve information.
 159     const Klass* const loader_klass = _cld->class_loader_klass();
 160 
 161     branchtracker.print(st);
 162 
 163     // e.g. "+-- jdk.internal.reflect.DelegatingClassLoader @<id>, jdk.internal.reflect.DelegatingClassLoader {0x<address of loader oop>}"
 164     st->print("+%.*s", BranchTracker::twig_len, "----------");
 165     st->print(" %s,", _cld->loader_name_and_id());
 166     if (!_cld->is_the_null_class_loader_data()) {
 167       st->print(" %s", loader_klass != NULL ? loader_klass->external_name() : "??");
 168       st->print(" {" PTR_FORMAT "}", p2i(_loader_oop));
 169     }
 170     st->cr();
 171 
 172     // Output following this node (node details and child nodes) - up to the next sibling node
 173     // needs to be prefixed with "|" if there is a follow up sibling.
 174     const bool have_sibling = _next != NULL;
 175     BranchTracker::Mark trm(branchtracker, have_sibling);
 176 
 177     {
 178       // optional node details following this node needs to be prefixed with "|"
 179       // if there are follow up child nodes.
 180       const bool have_child = _child != NULL;
 181       BranchTracker::Mark trm(branchtracker, have_child);
 182 
 183       // Empty line
 184       branchtracker.print(st);
 185       st->cr();
 186 
 187       const int indentation = 18;
 188 
 189       if (verbose) {
 190         branchtracker.print(st);
 191         st->print_cr("%*s " PTR_FORMAT, indentation, "Loader Data:", p2i(_cld));
 192         branchtracker.print(st);
 193         st->print_cr("%*s " PTR_FORMAT, indentation, "Loader Klass:", p2i(loader_klass));
 194 
 195         // Empty line
 196         branchtracker.print(st);
 197         st->cr();
 198       }
 199 
 200       if (print_classes) {
 201         if (_classes != NULL) {
 202           for (LoadedClassInfo* lci = _classes; lci; lci = lci->_next) {
 203             // Non-anonymous classes should live in the primary CLD of its loader
 204             assert(lci->_cld == _cld, "must be");
 205 
 206             branchtracker.print(st);
 207             if (lci == _classes) { // first iteration
 208               st->print("%*s ", indentation, "Classes:");
 209             } else {
 210               st->print("%*s ", indentation, "");
 211             }
 212             st->print("%s", lci->_klass->external_name());
 213 
 214             // Special treatment for generated core reflection accessor classes: print invocation target.
 215             if (ReflectionAccessorImplKlassHelper::is_generated_accessor(lci->_klass)) {
 216               st->print(" (invokes: ");
 217               ReflectionAccessorImplKlassHelper::print_invocation_target(st, lci->_klass);
 218               st->print(")");
 219             }
 220 
 221             st->cr();
 222           }
 223           branchtracker.print(st);
 224           st->print("%*s ", indentation, "");
 225           st->print_cr("(%u class%s)", _num_classes, (_num_classes == 1) ? "" : "es");
 226 
 227           // Empty line
 228           branchtracker.print(st);
 229           st->cr();
 230         }
 231 
 232         if (_anon_classes != NULL) {
 233           for (LoadedClassInfo* lci = _anon_classes; lci; lci = lci->_next) {
 234             branchtracker.print(st);
 235             if (lci == _anon_classes) { // first iteration
 236               st->print("%*s ", indentation, "Anonymous Classes:");
 237             } else {
 238               st->print("%*s ", indentation, "");
 239             }
 240             st->print("%s", lci->_klass->external_name());
 241             // For anonymous classes, also print CLD if verbose. Should be a different one than the primary CLD.
 242             assert(lci->_cld != _cld, "must be");
 243             if (verbose) {
 244               st->print("  (CLD: " PTR_FORMAT ")", p2i(lci->_cld));
 245             }
 246             st->cr();
 247           }
 248           branchtracker.print(st);
 249           st->print("%*s ", indentation, "");
 250           st->print_cr("(%u anonymous class%s)", _num_anon_classes, (_num_anon_classes == 1) ? "" : "es");
 251 
 252           // Empty line
 253           branchtracker.print(st);
 254           st->cr();
 255         }
 256 
 257       } // end: print_classes
 258 
 259     } // Pop branchtracker mark
 260 
 261     // Print children, recursively
 262     LoaderTreeNode* c = _child;
 263     while (c != NULL) {
 264       c->print_with_childs(st, branchtracker, print_classes, verbose);
 265       c = c->_next;
 266     }
 267 
 268   }
 269 
 270 public:
 271 
 272   LoaderTreeNode(const oop loader_oop)
 273     : _loader_oop(loader_oop), _cld(NULL)
 274     , _child(NULL), _next(NULL)
 275     , _classes(NULL), _anon_classes(NULL)
 276     , _num_classes(0), _num_anon_classes(0) {}
 277 
 278   void set_cld(const ClassLoaderData* cld) {
 279     _cld = cld;
 280   }
 281 
 282   void add_child(LoaderTreeNode* info) {
 283     info->_next = _child;
 284     _child = info;
 285   }
 286 
 287   void add_sibling(LoaderTreeNode* info) {
 288     assert(info->_next == NULL, "must be");
 289     info->_next = _next;
 290     _next = info;
 291   }
 292 
 293   void add_classes(LoadedClassInfo* first_class, int num_classes, bool anonymous) {
 294     LoadedClassInfo** p_list_to_add_to = anonymous ? &_anon_classes : &_classes;
 295     // Search tail.
 296     while ((*p_list_to_add_to) != NULL) {
 297       p_list_to_add_to = &(*p_list_to_add_to)->_next;
 298     }
 299     *p_list_to_add_to = first_class;
 300     if (anonymous) {
 301       _num_anon_classes += num_classes;
 302     } else {
 303       _num_classes += num_classes;
 304     }
 305   }
 306 
 307   const ClassLoaderData* cld() const {
 308     return _cld;
 309   }
 310 
 311   const oop loader_oop() const {
 312     return _loader_oop;
 313   }
 314 
 315   LoaderTreeNode* find(const oop loader_oop) {
 316     LoaderTreeNode* result = NULL;
 317     if (_loader_oop == loader_oop) {
 318       result = this;
 319     } else {
 320       LoaderTreeNode* c = _child;
 321       while (c != NULL && result == NULL) {
 322         result = c->find(loader_oop);
 323         c = c->_next;
 324       }
 325     }
 326     return result;
 327   }
 328 
 329   void print_with_childs(outputStream* st, bool print_classes, bool print_add_info) const {
 330     BranchTracker bwt;
 331     print_with_childs(st, bwt, print_classes, print_add_info);
 332   }
 333 
 334 };
 335 
 336 class LoadedClassCollectClosure : public KlassClosure {
 337 public:
 338   LoadedClassInfo* _list;
 339   const ClassLoaderData* _cld;
 340   int _num_classes;
 341   LoadedClassCollectClosure(const ClassLoaderData* cld)
 342     : _list(NULL), _cld(cld), _num_classes(0) {}
 343   void do_klass(Klass* k) {
 344     LoadedClassInfo* lki = new LoadedClassInfo(k, _cld);
 345     lki->_next = _list;
 346     _list = lki;
 347     _num_classes ++;
 348   }
 349 };
 350 
 351 class LoaderInfoScanClosure : public CLDClosure {
 352 
 353   const bool _print_classes;
 354   const bool _verbose;
 355   LoaderTreeNode* _root;
 356 
 357   static void fill_in_classes(LoaderTreeNode* info, const ClassLoaderData* cld) {
 358     assert(info != NULL && cld != NULL, "must be");
 359     LoadedClassCollectClosure lccc(cld);
 360     const_cast<ClassLoaderData*>(cld)->classes_do(&lccc);
 361     if (lccc._num_classes > 0) {
 362       info->add_classes(lccc._list, lccc._num_classes, cld->is_anonymous());
 363     }
 364   }
 365 
 366   LoaderTreeNode* find_node_or_add_empty_node(oop loader_oop) {
 367 
 368     assert(_root != NULL, "root node must exist");
 369 
 370     if (loader_oop == NULL) {
 371       return _root;
 372     }
 373 
 374     // Check if a node for this oop already exists.
 375     LoaderTreeNode* info = _root->find(loader_oop);
 376 
 377     if (info == NULL) {
 378       // It does not. Create a node.
 379       info = new LoaderTreeNode(loader_oop);
 380 
 381       // Add it to tree.
 382       LoaderTreeNode* parent_info = NULL;
 383 
 384       // Recursively add parent nodes if needed.
 385       const oop parent_oop = java_lang_ClassLoader::parent(loader_oop);
 386       if (parent_oop == NULL) {
 387         parent_info = _root;
 388       } else {
 389         parent_info = find_node_or_add_empty_node(parent_oop);
 390       }
 391       assert(parent_info != NULL, "must be");
 392 
 393       parent_info->add_child(info);
 394     }
 395     return info;
 396   }
 397 
 398 
 399 public:
 400   LoaderInfoScanClosure(bool print_classes, bool verbose)
 401     : _print_classes(print_classes), _verbose(verbose), _root(NULL) {
 402     _root = new LoaderTreeNode(NULL);
 403   }
 404 
 405   void print_results(outputStream* st) const {
 406     _root->print_with_childs(st, _print_classes, _verbose);
 407   }
 408 
 409   void do_cld (ClassLoaderData* cld) {
 410 
 411     // We do not display unloading loaders, for now.
 412     if (cld->is_unloading()) {
 413       return;
 414     }
 415 
 416     const oop loader_oop = cld->class_loader();
 417 
 418     LoaderTreeNode* info = find_node_or_add_empty_node(loader_oop);
 419     assert(info != NULL, "must be");
 420 
 421     // Update CLD in node, but only if this is the primary CLD for this loader.
 422     if (cld->is_anonymous() == false) {
 423       assert(info->cld() == NULL, "there should be only one primary CLD per loader");
 424       info->set_cld(cld);
 425     }
 426 
 427     // Add classes.
 428     fill_in_classes(info, cld);
 429   }
 430 
 431 };
 432 
 433 
 434 class ClassLoaderHierarchyVMOperation : public VM_Operation {
 435   outputStream* const _out;
 436   const bool _show_classes;
 437   const bool _verbose;
 438 public:
 439   ClassLoaderHierarchyVMOperation(outputStream* out, bool show_classes, bool verbose) :
 440     _out(out), _show_classes(show_classes), _verbose(verbose)
 441   {}
 442 
 443   VMOp_Type type() const {
 444     return VMOp_ClassLoaderHierarchyOperation;
 445   }
 446 
 447   void doit() {
 448     assert(SafepointSynchronize::is_at_safepoint(), "must be a safepoint");
 449     ResourceMark rm;
 450     LoaderInfoScanClosure cl (_show_classes, _verbose);
 451     ClassLoaderDataGraph::cld_do(&cl);
 452     cl.print_results(_out);
 453   }
 454 };
 455 
 456 // This command needs to be executed at a safepoint.
 457 void ClassLoaderHierarchyDCmd::execute(DCmdSource source, TRAPS) {
 458   ClassLoaderHierarchyVMOperation op(output(), _show_classes.value(), _verbose.value());
 459   VMThread::execute(&op);
 460 }