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