1 /*
   2  * Copyright (c) 2012, 2015, 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 package sun.hotspot;
  26 
  27 import java.lang.management.MemoryUsage;
  28 import java.lang.reflect.Executable;
  29 import java.util.Arrays;
  30 import java.util.List;
  31 import java.util.function.BiFunction;
  32 import java.util.function.Function;
  33 import java.security.BasicPermission;
  34 import java.util.Objects;
  35 import jdk.internal.HotSpotIntrinsicCandidate;
  36 
  37 import sun.hotspot.parser.DiagnosticCommand;
  38 
  39 public class WhiteBox {
  40   @SuppressWarnings("serial")
  41   public static class WhiteBoxPermission extends BasicPermission {
  42     public WhiteBoxPermission(String s) {
  43       super(s);
  44     }
  45   }
  46 
  47   private WhiteBox() {}
  48   private static final WhiteBox instance = new WhiteBox();
  49   private static native void registerNatives();
  50 
  51   /**
  52    * Returns the singleton WhiteBox instance.
  53    *
  54    * The returned WhiteBox object should be carefully guarded
  55    * by the caller, since it can be used to read and write data
  56    * at arbitrary memory addresses. It must never be passed to
  57    * untrusted code.
  58    */
  59   public synchronized static WhiteBox getWhiteBox() {
  60     SecurityManager sm = System.getSecurityManager();
  61     if (sm != null) {
  62       sm.checkPermission(new WhiteBoxPermission("getInstance"));
  63     }
  64     return instance;
  65   }
  66 
  67   static {
  68     registerNatives();
  69   }
  70 
  71   // Get the maximum heap size supporting COOPs
  72   public native long getCompressedOopsMaxHeapSize();
  73   // Arguments
  74   public native void printHeapSizes();
  75 
  76   // Memory
  77   private native long getObjectAddress0(Object o);
  78   public           long getObjectAddress(Object o) {
  79     Objects.requireNonNull(o);
  80     return getObjectAddress0(o);
  81   }
  82 
  83   public native int  getHeapOopSize();
  84   public native int  getVMPageSize();
  85   public native long getVMAllocationGranularity();
  86   public native long getVMLargePageSize();
  87   public native long getHeapSpaceAlignment();
  88 
  89   private native boolean isObjectInOldGen0(Object o);
  90   public         boolean isObjectInOldGen(Object o) {
  91     Objects.requireNonNull(o);
  92     return isObjectInOldGen0(o);
  93   }
  94 
  95   private native long getObjectSize0(Object o);
  96   public         long getObjectSize(Object o) {
  97     Objects.requireNonNull(o);
  98     return getObjectSize0(o);
  99   }
 100 
 101   // Runtime
 102   // Make sure class name is in the correct format
 103   public boolean isClassAlive(String name) {
 104     return isClassAlive0(name.replace('.', '/'));
 105   }
 106   private native boolean isClassAlive0(String name);
 107 
 108   private native boolean isMonitorInflated0(Object obj);
 109   public         boolean isMonitorInflated(Object obj) {
 110     Objects.requireNonNull(obj);
 111     return isMonitorInflated0(obj);
 112   }
 113 
 114   public native void forceSafepoint();
 115 
 116   private native long getConstantPool0(Class<?> aClass);
 117   public         long getConstantPool(Class<?> aClass) {
 118     Objects.requireNonNull(aClass);
 119     return getConstantPool0(aClass);
 120   }
 121 
 122   // JVMTI
 123   private native void addToBootstrapClassLoaderSearch0(String segment);
 124   public         void addToBootstrapClassLoaderSearch(String segment){
 125     Objects.requireNonNull(segment);
 126     addToBootstrapClassLoaderSearch0(segment);
 127   }
 128 
 129   private native void addToSystemClassLoaderSearch0(String segment);
 130   public         void addToSystemClassLoaderSearch(String segment) {
 131     Objects.requireNonNull(segment);
 132     addToSystemClassLoaderSearch0(segment);
 133   }
 134 
 135   // G1
 136   public native boolean g1InConcurrentMark();
 137   private native boolean g1IsHumongous0(Object o);
 138   public         boolean g1IsHumongous(Object o) {
 139     Objects.requireNonNull(o);
 140     return g1IsHumongous0(o);
 141   }
 142 
 143   private native boolean g1BelongsToHumongousRegion0(long adr);
 144   public         boolean g1BelongsToHumongousRegion(long adr) {
 145     if (adr == 0) {
 146       throw new IllegalArgumentException("adr argument should not be null");
 147     }
 148     return g1BelongsToHumongousRegion0(adr);
 149   }
 150 
 151 
 152   private native boolean g1BelongsToFreeRegion0(long adr);
 153   public         boolean g1BelongsToFreeRegion(long adr) {
 154     if (adr == 0) {
 155       throw new IllegalArgumentException("adr argument should not be null");
 156     }
 157     return g1BelongsToFreeRegion0(adr);
 158   }
 159 
 160   public native long    g1NumMaxRegions();
 161   public native long    g1NumFreeRegions();
 162   public native int     g1RegionSize();
 163   public native MemoryUsage g1AuxiliaryMemoryUsage();
 164   private  native Object[]    parseCommandLine0(String commandline, char delim, DiagnosticCommand[] args);
 165   public          Object[]    parseCommandLine(String commandline, char delim, DiagnosticCommand[] args) {
 166     Objects.requireNonNull(args);
 167     return parseCommandLine0(commandline, delim, args);
 168   }
 169 
 170   // Parallel GC
 171   public native long psVirtualSpaceAlignment();
 172   public native long psHeapGenerationAlignment();
 173 
 174   // NMT
 175   public native long NMTMalloc(long size);
 176   public native void NMTFree(long mem);
 177   public native long NMTReserveMemory(long size);
 178   public native void NMTCommitMemory(long addr, long size);
 179   public native void NMTUncommitMemory(long addr, long size);
 180   public native void NMTReleaseMemory(long addr, long size);
 181   public native long NMTMallocWithPseudoStack(long size, int index);
 182   public native boolean NMTChangeTrackingLevel();
 183   public native int NMTGetHashSize();
 184 
 185   // Compiler
 186   public native int     matchesMethod(Executable method, String pattern);
 187   public native int     matchesInline(Executable method, String pattern);
 188   public native boolean shouldPrintAssembly(Executable method);
 189   public native int     deoptimizeFrames(boolean makeNotEntrant);
 190   public native void    deoptimizeAll();
 191 
 192   @HotSpotIntrinsicCandidate
 193   public        void    deoptimize() {}
 194   public        boolean isMethodCompiled(Executable method) {
 195     return isMethodCompiled(method, false /*not osr*/);
 196   }
 197   private native boolean isMethodCompiled0(Executable method, boolean isOsr);
 198   public         boolean isMethodCompiled(Executable method, boolean isOsr){
 199     Objects.requireNonNull(method);
 200     return isMethodCompiled0(method, isOsr);
 201   }
 202   public        boolean isMethodCompilable(Executable method) {
 203     return isMethodCompilable(method, -1 /*any*/);
 204   }
 205   public        boolean isMethodCompilable(Executable method, int compLevel) {
 206     return isMethodCompilable(method, compLevel, false /*not osr*/);
 207   }
 208   private native boolean isMethodCompilable0(Executable method, int compLevel, boolean isOsr);
 209   public         boolean isMethodCompilable(Executable method, int compLevel, boolean isOsr) {
 210     Objects.requireNonNull(method);
 211     return isMethodCompilable0(method, compLevel, isOsr);
 212   }
 213   private native boolean isMethodQueuedForCompilation0(Executable method);
 214   public         boolean isMethodQueuedForCompilation(Executable method) {
 215     Objects.requireNonNull(method);
 216     return isMethodQueuedForCompilation0(method);
 217   }
 218   // Determine if the compiler corresponding to the compilation level 'compLevel'
 219   // and to the compilation context 'compilation_context' provides an intrinsic
 220   // for the method 'method'. An intrinsic is available for method 'method' if:
 221   //  - the intrinsic is enabled (by using the appropriate command-line flag) and
 222   //  - the platform on which the VM is running provides the instructions necessary
 223   //    for the compiler to generate the intrinsic code.
 224   //
 225   // The compilation context is related to using the DisableIntrinsic flag on a
 226   // per-method level, see hotspot/src/share/vm/compiler/abstractCompiler.hpp
 227   // for more details.
 228   public boolean isIntrinsicAvailable(Executable method,
 229                                       Executable compilationContext,
 230                                       int compLevel) {
 231       Objects.requireNonNull(method);
 232       return isIntrinsicAvailable0(method, compilationContext, compLevel);
 233   }
 234   // If usage of the DisableIntrinsic flag is not expected (or the usage can be ignored),
 235   // use the below method that does not require the compilation context as argument.
 236   public boolean isIntrinsicAvailable(Executable method, int compLevel) {
 237       return isIntrinsicAvailable(method, null, compLevel);
 238   }
 239   private native boolean isIntrinsicAvailable0(Executable method,
 240                                                Executable compilationContext,
 241                                                int compLevel);
 242   public        int     deoptimizeMethod(Executable method) {
 243     return deoptimizeMethod(method, false /*not osr*/);
 244   }
 245   private native int     deoptimizeMethod0(Executable method, boolean isOsr);
 246   public         int     deoptimizeMethod(Executable method, boolean isOsr) {
 247     Objects.requireNonNull(method);
 248     return deoptimizeMethod0(method, isOsr);
 249   }
 250   public        void    makeMethodNotCompilable(Executable method) {
 251     makeMethodNotCompilable(method, -1 /*any*/);
 252   }
 253   public        void    makeMethodNotCompilable(Executable method, int compLevel) {
 254     makeMethodNotCompilable(method, compLevel, false /*not osr*/);
 255   }
 256   private native void    makeMethodNotCompilable0(Executable method, int compLevel, boolean isOsr);
 257   public         void    makeMethodNotCompilable(Executable method, int compLevel, boolean isOsr) {
 258     Objects.requireNonNull(method);
 259     makeMethodNotCompilable0(method, compLevel, isOsr);
 260   }
 261   public        int     getMethodCompilationLevel(Executable method) {
 262     return getMethodCompilationLevel(method, false /*not ost*/);
 263   }
 264   private native int     getMethodCompilationLevel0(Executable method, boolean isOsr);
 265   public         int     getMethodCompilationLevel(Executable method, boolean isOsr) {
 266     Objects.requireNonNull(method);
 267     return getMethodCompilationLevel0(method, isOsr);
 268   }
 269   private native boolean testSetDontInlineMethod0(Executable method, boolean value);
 270   public         boolean testSetDontInlineMethod(Executable method, boolean value) {
 271     Objects.requireNonNull(method);
 272     return testSetDontInlineMethod0(method, value);
 273   }
 274   public        int     getCompileQueuesSize() {
 275     return getCompileQueueSize(-1 /*any*/);
 276   }
 277   public native int     getCompileQueueSize(int compLevel);
 278   private native boolean testSetForceInlineMethod0(Executable method, boolean value);
 279   public         boolean testSetForceInlineMethod(Executable method, boolean value) {
 280     Objects.requireNonNull(method);
 281     return testSetForceInlineMethod0(method, value);
 282   }
 283   public        boolean enqueueMethodForCompilation(Executable method, int compLevel) {
 284     return enqueueMethodForCompilation(method, compLevel, -1 /*InvocationEntryBci*/);
 285   }
 286   private native boolean enqueueMethodForCompilation0(Executable method, int compLevel, int entry_bci);
 287   public  boolean enqueueMethodForCompilation(Executable method, int compLevel, int entry_bci) {
 288     Objects.requireNonNull(method);
 289     return enqueueMethodForCompilation0(method, compLevel, entry_bci);
 290   }
 291   private native void    clearMethodState0(Executable method);
 292   public         void    clearMethodState(Executable method) {
 293     Objects.requireNonNull(method);
 294     clearMethodState0(method);
 295   }
 296   public native void    lockCompilation();
 297   public native void    unlockCompilation();
 298   private native int     getMethodEntryBci0(Executable method);
 299   public         int     getMethodEntryBci(Executable method) {
 300     Objects.requireNonNull(method);
 301     return getMethodEntryBci0(method);
 302   }
 303   private native Object[] getNMethod0(Executable method, boolean isOsr);
 304   public         Object[] getNMethod(Executable method, boolean isOsr) {
 305     Objects.requireNonNull(method);
 306     return getNMethod0(method, isOsr);
 307   }
 308   public native long    allocateCodeBlob(int size, int type);
 309   public        long    allocateCodeBlob(long size, int type) {
 310       int intSize = (int) size;
 311       if ((long) intSize != size || size < 0) {
 312           throw new IllegalArgumentException(
 313                 "size argument has illegal value " + size);
 314       }
 315       return allocateCodeBlob( intSize, type);
 316   }
 317   public native void    freeCodeBlob(long addr);
 318   public native void    forceNMethodSweep();
 319   public native Object[] getCodeHeapEntries(int type);
 320   public native int     getCompilationActivityMode();
 321   private native long getMethodData0(Executable method);
 322   public         long getMethodData(Executable method) {
 323     Objects.requireNonNull(method);
 324     return getMethodData0(method);
 325   }
 326   public native Object[] getCodeBlob(long addr);
 327 
 328   public native void clearInlineCaches();
 329 
 330   // Intered strings
 331   public native boolean isInStringTable(String str);
 332 
 333   // Memory
 334   public native void readReservedMemory();
 335   public native long allocateMetaspace(ClassLoader classLoader, long size);
 336   public native void freeMetaspace(ClassLoader classLoader, long addr, long size);
 337   public native long incMetaspaceCapacityUntilGC(long increment);
 338   public native long metaspaceCapacityUntilGC();
 339 
 340   // Force Young GC
 341   public native void youngGC();
 342 
 343   // Force Full GC
 344   public native void fullGC();
 345 
 346   // Method tries to start concurrent mark cycle.
 347   // It returns false if CM Thread is always in concurrent cycle.
 348   public native boolean g1StartConcMarkCycle();
 349 
 350   // Tests on ReservedSpace/VirtualSpace classes
 351   public native int stressVirtualSpaceResize(long reservedSpaceSize, long magnitude, long iterations);
 352   public native void runMemoryUnitTests();
 353   public native void readFromNoaccessArea();
 354   public native long getThreadStackSize();
 355   public native long getThreadRemainingStackSize();
 356 
 357   // CPU features
 358   public native String getCPUFeatures();
 359 
 360   // Native extensions
 361   public native long getHeapUsageForContext(int context);
 362   public native long getHeapRegionCountForContext(int context);
 363   private native int getContextForObject0(Object obj);
 364   public         int getContextForObject(Object obj) {
 365     Objects.requireNonNull(obj);
 366     return getContextForObject0(obj);
 367   }
 368   public native void printRegionInfo(int context);
 369 
 370   // VM flags
 371   public native boolean isConstantVMFlag(String name);
 372   public native boolean isLockedVMFlag(String name);
 373   public native void    setBooleanVMFlag(String name, boolean value);
 374   public native void    setIntVMFlag(String name, long value);
 375   public native void    setUintVMFlag(String name, long value);
 376   public native void    setIntxVMFlag(String name, long value);
 377   public native void    setUintxVMFlag(String name, long value);
 378   public native void    setUint64VMFlag(String name, long value);
 379   public native void    setSizeTVMFlag(String name, long value);
 380   public native void    setStringVMFlag(String name, String value);
 381   public native void    setDoubleVMFlag(String name, double value);
 382   public native Boolean getBooleanVMFlag(String name);
 383   public native Long    getIntVMFlag(String name);
 384   public native Long    getUintVMFlag(String name);
 385   public native Long    getIntxVMFlag(String name);
 386   public native Long    getUintxVMFlag(String name);
 387   public native Long    getUint64VMFlag(String name);
 388   public native Long    getSizeTVMFlag(String name);
 389   public native String  getStringVMFlag(String name);
 390   public native Double  getDoubleVMFlag(String name);
 391   private final List<Function<String,Object>> flagsGetters = Arrays.asList(
 392     this::getBooleanVMFlag, this::getIntVMFlag, this::getUintVMFlag,
 393     this::getIntxVMFlag, this::getUintxVMFlag, this::getUint64VMFlag,
 394     this::getSizeTVMFlag, this::getStringVMFlag, this::getDoubleVMFlag);
 395 
 396   public Object getVMFlag(String name) {
 397     return flagsGetters.stream()
 398                        .map(f -> f.apply(name))
 399                        .filter(x -> x != null)
 400                        .findAny()
 401                        .orElse(null);
 402   }
 403   public native int getOffsetForName0(String name);
 404   public int getOffsetForName(String name) throws Exception {
 405     int offset = getOffsetForName0(name);
 406     if (offset == -1) {
 407       throw new RuntimeException(name + " not found");
 408     }
 409     return offset;
 410   }
 411   public native Boolean getMethodBooleanOption(Executable method, String name);
 412   public native Long    getMethodIntxOption(Executable method, String name);
 413   public native Long    getMethodUintxOption(Executable method, String name);
 414   public native Double  getMethodDoubleOption(Executable method, String name);
 415   public native String  getMethodStringOption(Executable method, String name);
 416   private final List<BiFunction<Executable,String,Object>> methodOptionGetters
 417       = Arrays.asList(this::getMethodBooleanOption, this::getMethodIntxOption,
 418           this::getMethodUintxOption, this::getMethodDoubleOption,
 419           this::getMethodStringOption);
 420 
 421   public Object getMethodOption(Executable method, String name) {
 422     return methodOptionGetters.stream()
 423                               .map(f -> f.apply(method, name))
 424                               .filter(x -> x != null)
 425                               .findAny()
 426                               .orElse(null);
 427   }
 428 
 429   // Safepoint Checking
 430   public native void assertMatchingSafepointCalls(boolean mutexSafepointValue, boolean attemptedNoSafepointValue);
 431 
 432   // Sharing
 433   public native boolean isSharedClass(Class<?> c);
 434   public native boolean isShared(Object o);
 435   public native boolean areSharedStringsIgnored();
 436 }