1 /*
   2  * Copyright (c) 2012, 2019, 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 package sun.hotspot;
  25 
  26 import java.lang.management.MemoryUsage;
  27 import java.lang.reflect.Executable;
  28 import java.util.Arrays;
  29 import java.util.List;
  30 import java.util.function.BiFunction;
  31 import java.util.function.Function;
  32 import java.security.BasicPermission;
  33 import java.util.Objects;
  34 
  35 import sun.hotspot.parser.DiagnosticCommand;
  36 
  37 public class WhiteBox {
  38   @SuppressWarnings("serial")
  39   public static class WhiteBoxPermission extends BasicPermission {
  40     public WhiteBoxPermission(String s) {
  41       super(s);
  42     }
  43   }
  44 
  45   private WhiteBox() {}
  46   private static final WhiteBox instance = new WhiteBox();
  47   private static native void registerNatives();
  48 
  49   /**
  50    * Returns the singleton WhiteBox instance.
  51    *
  52    * The returned WhiteBox object should be carefully guarded
  53    * by the caller, since it can be used to read and write data
  54    * at arbitrary memory addresses. It must never be passed to
  55    * untrusted code.
  56    */
  57   public synchronized static WhiteBox getWhiteBox() {
  58     SecurityManager sm = System.getSecurityManager();
  59     if (sm != null) {
  60       sm.checkPermission(new WhiteBoxPermission("getInstance"));
  61     }
  62     return instance;
  63   }
  64 
  65   static {
  66     registerNatives();
  67   }
  68 
  69   // Get the maximum heap size supporting COOPs
  70   public native long getCompressedOopsMaxHeapSize();
  71   // Arguments
  72   public native void printHeapSizes();
  73 
  74   // Memory
  75   private native long getObjectAddress0(Object o);
  76   public           long getObjectAddress(Object o) {
  77     Objects.requireNonNull(o);
  78     return getObjectAddress0(o);
  79   }
  80 
  81   public native int  getHeapOopSize();
  82   public native int  getVMPageSize();
  83   public native long getVMAllocationGranularity();
  84   public native long getVMLargePageSize();
  85   public native long getHeapSpaceAlignment();
  86   public native long getHeapAlignment();
  87 
  88   private native boolean isObjectInOldGen0(Object o);
  89   public         boolean isObjectInOldGen(Object o) {
  90     Objects.requireNonNull(o);
  91     return isObjectInOldGen0(o);
  92   }
  93 
  94   private native long getObjectSize0(Object o);
  95   public         long getObjectSize(Object o) {
  96     Objects.requireNonNull(o);
  97     return getObjectSize0(o);
  98   }
  99 
 100   // Runtime
 101   // Make sure class name is in the correct format
 102   public boolean isClassAlive(String name) {
 103     return isClassAlive0(name.replace('.', '/'));
 104   }
 105   private native boolean isClassAlive0(String name);
 106   public  native int getSymbolRefcount(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   private native int getConstantPoolCacheIndexTag0();
 123   public         int getConstantPoolCacheIndexTag() {
 124     return getConstantPoolCacheIndexTag0();
 125   }
 126 
 127   private native int getConstantPoolCacheLength0(Class<?> aClass);
 128   public         int getConstantPoolCacheLength(Class<?> aClass) {
 129     Objects.requireNonNull(aClass);
 130     return getConstantPoolCacheLength0(aClass);
 131   }
 132 
 133   private native int remapInstructionOperandFromCPCache0(Class<?> aClass, int index);
 134   public         int remapInstructionOperandFromCPCache(Class<?> aClass, int index) {
 135     Objects.requireNonNull(aClass);
 136     return remapInstructionOperandFromCPCache0(aClass, index);
 137   }
 138 
 139   private native int encodeConstantPoolIndyIndex0(int index);
 140   public         int encodeConstantPoolIndyIndex(int index) {
 141     return encodeConstantPoolIndyIndex0(index);
 142   }
 143 
 144   // JVMTI
 145   private native void addToBootstrapClassLoaderSearch0(String segment);
 146   public         void addToBootstrapClassLoaderSearch(String segment){
 147     Objects.requireNonNull(segment);
 148     addToBootstrapClassLoaderSearch0(segment);
 149   }
 150 
 151   private native void addToSystemClassLoaderSearch0(String segment);
 152   public         void addToSystemClassLoaderSearch(String segment) {
 153     Objects.requireNonNull(segment);
 154     addToSystemClassLoaderSearch0(segment);
 155   }
 156 
 157   // G1
 158   public native boolean g1InConcurrentMark();
 159   private native boolean g1IsHumongous0(Object o);
 160   public         boolean g1IsHumongous(Object o) {
 161     Objects.requireNonNull(o);
 162     return g1IsHumongous0(o);
 163   }
 164 
 165   private native boolean g1BelongsToHumongousRegion0(long adr);
 166   public         boolean g1BelongsToHumongousRegion(long adr) {
 167     if (adr == 0) {
 168       throw new IllegalArgumentException("adr argument should not be null");
 169     }
 170     return g1BelongsToHumongousRegion0(adr);
 171   }
 172 
 173 
 174   private native boolean g1BelongsToFreeRegion0(long adr);
 175   public         boolean g1BelongsToFreeRegion(long adr) {
 176     if (adr == 0) {
 177       throw new IllegalArgumentException("adr argument should not be null");
 178     }
 179     return g1BelongsToFreeRegion0(adr);
 180   }
 181 
 182   public native long    g1NumMaxRegions();
 183   public native long    g1NumFreeRegions();
 184   public native int     g1RegionSize();
 185   public native long    dramReservedStart();
 186   public native long    dramReservedEnd();
 187   public native long    nvdimmReservedStart();
 188   public native long    nvdimmReservedEnd();
 189   public native MemoryUsage g1AuxiliaryMemoryUsage();
 190   private  native Object[]    parseCommandLine0(String commandline, char delim, DiagnosticCommand[] args);
 191   public          Object[]    parseCommandLine(String commandline, char delim, DiagnosticCommand[] args) {
 192     Objects.requireNonNull(args);
 193     return parseCommandLine0(commandline, delim, args);
 194   }
 195 
 196   // Parallel GC
 197   public native long psVirtualSpaceAlignment();
 198   public native long psHeapGenerationAlignment();
 199 
 200   /**
 201    * Enumerates old regions with liveness less than specified and produces some statistics
 202    * @param liveness percent of region's liveness (live_objects / total_region_size * 100).
 203    * @return long[3] array where long[0] - total count of old regions
 204    *                             long[1] - total memory of old regions
 205    *                             long[2] - lowest estimation of total memory of old regions to be freed (non-full
 206    *                             regions are not included)
 207    */
 208   public native long[] g1GetMixedGCInfo(int liveness);
 209 
 210   // NMT
 211   public native long NMTMalloc(long size);
 212   public native void NMTFree(long mem);
 213   public native long NMTReserveMemory(long size);
 214   public native long NMTAttemptReserveMemoryAt(long addr, long size);
 215   public native void NMTCommitMemory(long addr, long size);
 216   public native void NMTUncommitMemory(long addr, long size);
 217   public native void NMTReleaseMemory(long addr, long size);
 218   public native long NMTMallocWithPseudoStack(long size, int index);
 219   public native long NMTMallocWithPseudoStackAndType(long size, int index, int type);
 220   public native boolean NMTChangeTrackingLevel();
 221   public native int NMTGetHashSize();
 222 
 223   // Compiler
 224   public native int     matchesMethod(Executable method, String pattern);
 225   public native int     matchesInline(Executable method, String pattern);
 226   public native boolean shouldPrintAssembly(Executable method, int comp_level);
 227   public native int     deoptimizeFrames(boolean makeNotEntrant);
 228   public native void    deoptimizeAll();
 229 
 230   public        boolean isMethodCompiled(Executable method) {
 231     return isMethodCompiled(method, false /*not osr*/);
 232   }
 233   private native boolean isMethodCompiled0(Executable method, boolean isOsr);
 234   public         boolean isMethodCompiled(Executable method, boolean isOsr){
 235     Objects.requireNonNull(method);
 236     return isMethodCompiled0(method, isOsr);
 237   }
 238   public        boolean isMethodCompilable(Executable method) {
 239     return isMethodCompilable(method, -2 /*any*/);
 240   }
 241   public        boolean isMethodCompilable(Executable method, int compLevel) {
 242     return isMethodCompilable(method, compLevel, false /*not osr*/);
 243   }
 244   private native boolean isMethodCompilable0(Executable method, int compLevel, boolean isOsr);
 245   public         boolean isMethodCompilable(Executable method, int compLevel, boolean isOsr) {
 246     Objects.requireNonNull(method);
 247     return isMethodCompilable0(method, compLevel, isOsr);
 248   }
 249   private native boolean isMethodQueuedForCompilation0(Executable method);
 250   public         boolean isMethodQueuedForCompilation(Executable method) {
 251     Objects.requireNonNull(method);
 252     return isMethodQueuedForCompilation0(method);
 253   }
 254   // Determine if the compiler corresponding to the compilation level 'compLevel'
 255   // and to the compilation context 'compilation_context' provides an intrinsic
 256   // for the method 'method'. An intrinsic is available for method 'method' if:
 257   //  - the intrinsic is enabled (by using the appropriate command-line flag) and
 258   //  - the platform on which the VM is running provides the instructions necessary
 259   //    for the compiler to generate the intrinsic code.
 260   //
 261   // The compilation context is related to using the DisableIntrinsic flag on a
 262   // per-method level, see hotspot/src/share/vm/compiler/abstractCompiler.hpp
 263   // for more details.
 264   public boolean isIntrinsicAvailable(Executable method,
 265                                       Executable compilationContext,
 266                                       int compLevel) {
 267       Objects.requireNonNull(method);
 268       return isIntrinsicAvailable0(method, compilationContext, compLevel);
 269   }
 270   // If usage of the DisableIntrinsic flag is not expected (or the usage can be ignored),
 271   // use the below method that does not require the compilation context as argument.
 272   public boolean isIntrinsicAvailable(Executable method, int compLevel) {
 273       return isIntrinsicAvailable(method, null, compLevel);
 274   }
 275   private native boolean isIntrinsicAvailable0(Executable method,
 276                                                Executable compilationContext,
 277                                                int compLevel);
 278   public        int     deoptimizeMethod(Executable method) {
 279     return deoptimizeMethod(method, false /*not osr*/);
 280   }
 281   private native int     deoptimizeMethod0(Executable method, boolean isOsr);
 282   public         int     deoptimizeMethod(Executable method, boolean isOsr) {
 283     Objects.requireNonNull(method);
 284     return deoptimizeMethod0(method, isOsr);
 285   }
 286   public        void    makeMethodNotCompilable(Executable method) {
 287     makeMethodNotCompilable(method, -2 /*any*/);
 288   }
 289   public        void    makeMethodNotCompilable(Executable method, int compLevel) {
 290     makeMethodNotCompilable(method, compLevel, false /*not osr*/);
 291   }
 292   private native void    makeMethodNotCompilable0(Executable method, int compLevel, boolean isOsr);
 293   public         void    makeMethodNotCompilable(Executable method, int compLevel, boolean isOsr) {
 294     Objects.requireNonNull(method);
 295     makeMethodNotCompilable0(method, compLevel, isOsr);
 296   }
 297   public        int     getMethodCompilationLevel(Executable method) {
 298     return getMethodCompilationLevel(method, false /*not ost*/);
 299   }
 300   private native int     getMethodCompilationLevel0(Executable method, boolean isOsr);
 301   public         int     getMethodCompilationLevel(Executable method, boolean isOsr) {
 302     Objects.requireNonNull(method);
 303     return getMethodCompilationLevel0(method, isOsr);
 304   }
 305   private native boolean testSetDontInlineMethod0(Executable method, boolean value);
 306   public         boolean testSetDontInlineMethod(Executable method, boolean value) {
 307     Objects.requireNonNull(method);
 308     return testSetDontInlineMethod0(method, value);
 309   }
 310   public        int     getCompileQueuesSize() {
 311     return getCompileQueueSize(-2 /*any*/);
 312   }
 313   public native int     getCompileQueueSize(int compLevel);
 314   private native boolean testSetForceInlineMethod0(Executable method, boolean value);
 315   public         boolean testSetForceInlineMethod(Executable method, boolean value) {
 316     Objects.requireNonNull(method);
 317     return testSetForceInlineMethod0(method, value);
 318   }
 319   public        boolean enqueueMethodForCompilation(Executable method, int compLevel) {
 320     return enqueueMethodForCompilation(method, compLevel, -1 /*InvocationEntryBci*/);
 321   }
 322   private native boolean enqueueMethodForCompilation0(Executable method, int compLevel, int entry_bci);
 323   public  boolean enqueueMethodForCompilation(Executable method, int compLevel, int entry_bci) {
 324     Objects.requireNonNull(method);
 325     return enqueueMethodForCompilation0(method, compLevel, entry_bci);
 326   }
 327   private native boolean enqueueInitializerForCompilation0(Class<?> aClass, int compLevel);
 328   public  boolean enqueueInitializerForCompilation(Class<?> aClass, int compLevel) {
 329     Objects.requireNonNull(aClass);
 330     return enqueueInitializerForCompilation0(aClass, compLevel);
 331   }
 332   private native void    clearMethodState0(Executable method);
 333   public  native void    markMethodProfiled(Executable method);
 334   public         void    clearMethodState(Executable method) {
 335     Objects.requireNonNull(method);
 336     clearMethodState0(method);
 337   }
 338   public native void    lockCompilation();
 339   public native void    unlockCompilation();
 340   private native int     getMethodEntryBci0(Executable method);
 341   public         int     getMethodEntryBci(Executable method) {
 342     Objects.requireNonNull(method);
 343     return getMethodEntryBci0(method);
 344   }
 345   private native Object[] getNMethod0(Executable method, boolean isOsr);
 346   public         Object[] getNMethod(Executable method, boolean isOsr) {
 347     Objects.requireNonNull(method);
 348     return getNMethod0(method, isOsr);
 349   }
 350   public native long    allocateCodeBlob(int size, int type);
 351   public        long    allocateCodeBlob(long size, int type) {
 352       int intSize = (int) size;
 353       if ((long) intSize != size || size < 0) {
 354           throw new IllegalArgumentException(
 355                 "size argument has illegal value " + size);
 356       }
 357       return allocateCodeBlob( intSize, type);
 358   }
 359   public native void    freeCodeBlob(long addr);
 360   public native void    forceNMethodSweep();
 361   public native Object[] getCodeHeapEntries(int type);
 362   public native int     getCompilationActivityMode();
 363   private native long getMethodData0(Executable method);
 364   public         long getMethodData(Executable method) {
 365     Objects.requireNonNull(method);
 366     return getMethodData0(method);
 367   }
 368   public native Object[] getCodeBlob(long addr);
 369 
 370   private native void clearInlineCaches0(boolean preserve_static_stubs);
 371   public void clearInlineCaches() {
 372     clearInlineCaches0(false);
 373   }
 374   public void clearInlineCaches(boolean preserve_static_stubs) {
 375     clearInlineCaches0(preserve_static_stubs);
 376   }
 377 
 378   // Intered strings
 379   public native boolean isInStringTable(String str);
 380 
 381   // Memory
 382   public native void readReservedMemory();
 383   public native long allocateMetaspace(ClassLoader classLoader, long size);
 384   public native void freeMetaspace(ClassLoader classLoader, long addr, long size);
 385   public native long incMetaspaceCapacityUntilGC(long increment);
 386   public native long metaspaceCapacityUntilGC();
 387   public native boolean metaspaceShouldConcurrentCollect();
 388   public native long metaspaceReserveAlignment();
 389 
 390   // Don't use these methods directly
 391   // Use sun.hotspot.gc.GC class instead.
 392   public native boolean isGCSupported(int name);
 393   public native boolean isGCSelected(int name);
 394   public native boolean isGCSelectedErgonomically();
 395 
 396   // Force Young GC
 397   public native void youngGC();
 398 
 399   // Force Full GC
 400   public native void fullGC();
 401 
 402   // Returns true if the current GC supports control of its concurrent
 403   // phase via requestConcurrentGCPhase().  If false, a request will
 404   // always fail.
 405   public native boolean supportsConcurrentGCPhaseControl();
 406 
 407   // Attempt to put the collector into the indicated concurrent phase,
 408   // and attempt to remain in that state until a new request is made.
 409   //
 410   // Returns immediately if already in the requested phase.
 411   // Otherwise, waits until the phase is reached.
 412   //
 413   // Throws IllegalStateException if unsupported by the current collector.
 414   // Throws NullPointerException if phase is null.
 415   // Throws IllegalArgumentException if phase is not valid for the current collector.
 416   public void requestConcurrentGCPhase(String phase) {
 417     if (!supportsConcurrentGCPhaseControl()) {
 418       throw new IllegalStateException("Concurrent GC phase control not supported");
 419     } else if (phase == null) {
 420       throw new NullPointerException("null phase");
 421     } else if (!requestConcurrentGCPhase0(phase)) {
 422       throw new IllegalArgumentException("Unknown concurrent GC phase: " + phase);
 423     }
 424   }
 425 
 426   // Helper for requestConcurrentGCPhase().  Returns true if request
 427   // succeeded, false if the phase is invalid.
 428   private native boolean requestConcurrentGCPhase0(String phase);
 429 
 430   // Method tries to start concurrent mark cycle.
 431   // It returns false if CM Thread is always in concurrent cycle.
 432   public native boolean g1StartConcMarkCycle();
 433 
 434   // Tests on ReservedSpace/VirtualSpace classes
 435   public native int stressVirtualSpaceResize(long reservedSpaceSize, long magnitude, long iterations);
 436   public native void runMemoryUnitTests();
 437   public native void readFromNoaccessArea();
 438   public native long getThreadStackSize();
 439   public native long getThreadRemainingStackSize();
 440 
 441   // CPU features
 442   public native String getCPUFeatures();
 443 
 444   // VM flags
 445   public native boolean isConstantVMFlag(String name);
 446   public native boolean isLockedVMFlag(String name);
 447   public native void    setBooleanVMFlag(String name, boolean value);
 448   public native void    setIntVMFlag(String name, long value);
 449   public native void    setUintVMFlag(String name, long value);
 450   public native void    setIntxVMFlag(String name, long value);
 451   public native void    setUintxVMFlag(String name, long value);
 452   public native void    setUint64VMFlag(String name, long value);
 453   public native void    setSizeTVMFlag(String name, long value);
 454   public native void    setStringVMFlag(String name, String value);
 455   public native void    setDoubleVMFlag(String name, double value);
 456   public native Boolean getBooleanVMFlag(String name);
 457   public native Long    getIntVMFlag(String name);
 458   public native Long    getUintVMFlag(String name);
 459   public native Long    getIntxVMFlag(String name);
 460   public native Long    getUintxVMFlag(String name);
 461   public native Long    getUint64VMFlag(String name);
 462   public native Long    getSizeTVMFlag(String name);
 463   public native String  getStringVMFlag(String name);
 464   public native Double  getDoubleVMFlag(String name);
 465   private final List<Function<String,Object>> flagsGetters = Arrays.asList(
 466     this::getBooleanVMFlag, this::getIntVMFlag, this::getUintVMFlag,
 467     this::getIntxVMFlag, this::getUintxVMFlag, this::getUint64VMFlag,
 468     this::getSizeTVMFlag, this::getStringVMFlag, this::getDoubleVMFlag);
 469 
 470   public Object getVMFlag(String name) {
 471     return flagsGetters.stream()
 472                        .map(f -> f.apply(name))
 473                        .filter(x -> x != null)
 474                        .findAny()
 475                        .orElse(null);
 476   }
 477 
 478   // Jigsaw
 479   public native void DefineModule(Object module, boolean is_open, String version,
 480                                   String location, Object[] packages);
 481   public native void AddModuleExports(Object from_module, String pkg, Object to_module);
 482   public native void AddReadsModule(Object from_module, Object source_module);
 483   public native void AddModuleExportsToAllUnnamed(Object module, String pkg);
 484   public native void AddModuleExportsToAll(Object module, String pkg);
 485 
 486   public native int getOffsetForName0(String name);
 487   public int getOffsetForName(String name) throws Exception {
 488     int offset = getOffsetForName0(name);
 489     if (offset == -1) {
 490       throw new RuntimeException(name + " not found");
 491     }
 492     return offset;
 493   }
 494   public native Boolean getMethodBooleanOption(Executable method, String name);
 495   public native Long    getMethodIntxOption(Executable method, String name);
 496   public native Long    getMethodUintxOption(Executable method, String name);
 497   public native Double  getMethodDoubleOption(Executable method, String name);
 498   public native String  getMethodStringOption(Executable method, String name);
 499   private final List<BiFunction<Executable,String,Object>> methodOptionGetters
 500       = Arrays.asList(this::getMethodBooleanOption, this::getMethodIntxOption,
 501           this::getMethodUintxOption, this::getMethodDoubleOption,
 502           this::getMethodStringOption);
 503 
 504   public Object getMethodOption(Executable method, String name) {
 505     return methodOptionGetters.stream()
 506                               .map(f -> f.apply(method, name))
 507                               .filter(x -> x != null)
 508                               .findAny()
 509                               .orElse(null);
 510   }
 511 
 512   // Safepoint Checking
 513   public native void assertMatchingSafepointCalls(boolean mutexSafepointValue, boolean attemptedNoSafepointValue);
 514   public native void assertSpecialLock(boolean allowVMBlock, boolean safepointCheck);
 515 
 516   // Sharing & archiving
 517   public native String  getDefaultArchivePath();
 518   public native boolean cdsMemoryMappingFailed();
 519   public native boolean isSharingEnabled();
 520   public native boolean isShared(Object o);
 521   public native boolean isSharedClass(Class<?> c);
 522   public native boolean areSharedStringsIgnored();
 523   public native boolean isCDSIncludedInVmBuild();
 524   public native boolean isJFRIncludedInVmBuild();
 525   public native boolean isJavaHeapArchiveSupported();
 526   public native Object  getResolvedReferences(Class<?> c);
 527   public native void    linkClass(Class<?> c);
 528   public native boolean areOpenArchiveHeapObjectsMapped();
 529 
 530   // Compiler Directive
 531   public native int addCompilerDirective(String compDirect);
 532   public native void removeCompilerDirective(int count);
 533 
 534   // Handshakes
 535   public native int handshakeWalkStack(Thread t, boolean all_threads);
 536 
 537   // Returns true on linux if library has the noexecstack flag set.
 538   public native boolean checkLibSpecifiesNoexecstack(String libfilename);
 539 
 540   // Container testing
 541   public native boolean isContainerized();
 542   public native String containerType();
 543   public boolean isCgroupsV1() {
 544     return "cgroupv1".equals(containerType());
 545   }
 546   public boolean isCgroupsV2() {
 547     return "cgroupv2".equals(containerType());
 548   }
 549   public native void printOsInfo();
 550 
 551   // Decoder
 552   public native void disableElfSectionCache();
 553 
 554   // Resolved Method Table
 555   public native long resolvedMethodItemsCount();
 556 
 557   // Protection Domain Table
 558   public native int protectionDomainRemovedCount();
 559 
 560   // Number of loaded AOT libraries
 561   public native int aotLibrariesCount();
 562 }