Path: blob/master/test/lib/sun/hotspot/WhiteBox.java
41144 views
/*1* Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223package sun.hotspot;2425import java.lang.management.MemoryUsage;26import java.lang.reflect.Executable;27import java.util.Arrays;28import java.util.List;29import java.util.function.BiFunction;30import java.util.function.Function;31import java.security.BasicPermission;32import java.util.Objects;3334import sun.hotspot.parser.DiagnosticCommand;3536public class WhiteBox {37@SuppressWarnings("serial")38public static class WhiteBoxPermission extends BasicPermission {39public WhiteBoxPermission(String s) {40super(s);41}42}4344private WhiteBox() {}45private static final WhiteBox instance = new WhiteBox();46private static native void registerNatives();4748/**49* Returns the singleton WhiteBox instance.50*51* The returned WhiteBox object should be carefully guarded52* by the caller, since it can be used to read and write data53* at arbitrary memory addresses. It must never be passed to54* untrusted code.55*/56public synchronized static WhiteBox getWhiteBox() {57@SuppressWarnings("removal")58SecurityManager sm = System.getSecurityManager();59if (sm != null) {60sm.checkPermission(new WhiteBoxPermission("getInstance"));61}62return instance;63}6465static {66registerNatives();67}6869// Get the maximum heap size supporting COOPs70public native long getCompressedOopsMaxHeapSize();71// Arguments72public native void printHeapSizes();7374// Memory75private native long getObjectAddress0(Object o);76public long getObjectAddress(Object o) {77Objects.requireNonNull(o);78return getObjectAddress0(o);79}8081public native int getHeapOopSize();82public native int getVMPageSize();83public native long getVMAllocationGranularity();84public native long getVMLargePageSize();85public native long getHeapSpaceAlignment();86public native long getHeapAlignment();8788private native boolean isObjectInOldGen0(Object o);89public boolean isObjectInOldGen(Object o) {90Objects.requireNonNull(o);91return isObjectInOldGen0(o);92}9394private native long getObjectSize0(Object o);95public long getObjectSize(Object o) {96Objects.requireNonNull(o);97return getObjectSize0(o);98}99100// Runtime101// Make sure class name is in the correct format102public int countAliveClasses(String name) {103return countAliveClasses0(name.replace('.', '/'));104}105private native int countAliveClasses0(String name);106107public boolean isClassAlive(String name) {108return countAliveClasses(name) != 0;109}110111public native int getSymbolRefcount(String name);112113public native boolean deflateIdleMonitors();114115private native boolean isMonitorInflated0(Object obj);116public boolean isMonitorInflated(Object obj) {117Objects.requireNonNull(obj);118return isMonitorInflated0(obj);119}120121public native void forceSafepoint();122123private native long getConstantPool0(Class<?> aClass);124public long getConstantPool(Class<?> aClass) {125Objects.requireNonNull(aClass);126return getConstantPool0(aClass);127}128129private native int getConstantPoolCacheIndexTag0();130public int getConstantPoolCacheIndexTag() {131return getConstantPoolCacheIndexTag0();132}133134private native int getConstantPoolCacheLength0(Class<?> aClass);135public int getConstantPoolCacheLength(Class<?> aClass) {136Objects.requireNonNull(aClass);137return getConstantPoolCacheLength0(aClass);138}139140private native int remapInstructionOperandFromCPCache0(Class<?> aClass, int index);141public int remapInstructionOperandFromCPCache(Class<?> aClass, int index) {142Objects.requireNonNull(aClass);143return remapInstructionOperandFromCPCache0(aClass, index);144}145146private native int encodeConstantPoolIndyIndex0(int index);147public int encodeConstantPoolIndyIndex(int index) {148return encodeConstantPoolIndyIndex0(index);149}150151// JVMTI152private native void addToBootstrapClassLoaderSearch0(String segment);153public void addToBootstrapClassLoaderSearch(String segment){154Objects.requireNonNull(segment);155addToBootstrapClassLoaderSearch0(segment);156}157158private native void addToSystemClassLoaderSearch0(String segment);159public void addToSystemClassLoaderSearch(String segment) {160Objects.requireNonNull(segment);161addToSystemClassLoaderSearch0(segment);162}163164// G1165public native boolean g1InConcurrentMark();166public native boolean g1HasRegionsToUncommit();167private native boolean g1IsHumongous0(Object o);168public boolean g1IsHumongous(Object o) {169Objects.requireNonNull(o);170return g1IsHumongous0(o);171}172173private native boolean g1BelongsToHumongousRegion0(long adr);174public boolean g1BelongsToHumongousRegion(long adr) {175if (adr == 0) {176throw new IllegalArgumentException("adr argument should not be null");177}178return g1BelongsToHumongousRegion0(adr);179}180181182private native boolean g1BelongsToFreeRegion0(long adr);183public boolean g1BelongsToFreeRegion(long adr) {184if (adr == 0) {185throw new IllegalArgumentException("adr argument should not be null");186}187return g1BelongsToFreeRegion0(adr);188}189190public native long g1NumMaxRegions();191public native long g1NumFreeRegions();192public native int g1RegionSize();193public native MemoryUsage g1AuxiliaryMemoryUsage();194private native Object[] parseCommandLine0(String commandline, char delim, DiagnosticCommand[] args);195public Object[] parseCommandLine(String commandline, char delim, DiagnosticCommand[] args) {196Objects.requireNonNull(args);197return parseCommandLine0(commandline, delim, args);198}199200public native int g1ActiveMemoryNodeCount();201public native int[] g1MemoryNodeIds();202203// Parallel GC204public native long psVirtualSpaceAlignment();205public native long psHeapGenerationAlignment();206207/**208* Enumerates old regions with liveness less than specified and produces some statistics209* @param liveness percent of region's liveness (live_objects / total_region_size * 100).210* @return long[3] array where long[0] - total count of old regions211* long[1] - total memory of old regions212* long[2] - lowest estimation of total memory of old regions to be freed (non-full213* regions are not included)214*/215public native long[] g1GetMixedGCInfo(int liveness);216217// NMT218public native long NMTMalloc(long size);219public native void NMTFree(long mem);220public native long NMTReserveMemory(long size);221public native long NMTAttemptReserveMemoryAt(long addr, long size);222public native void NMTCommitMemory(long addr, long size);223public native void NMTUncommitMemory(long addr, long size);224public native void NMTReleaseMemory(long addr, long size);225public native long NMTMallocWithPseudoStack(long size, int index);226public native long NMTMallocWithPseudoStackAndType(long size, int index, int type);227public native boolean NMTChangeTrackingLevel();228public native int NMTGetHashSize();229public native long NMTNewArena(long initSize);230public native void NMTFreeArena(long arena);231public native void NMTArenaMalloc(long arena, long size);232233// Compiler234public native boolean isC2OrJVMCIIncluded();235public native boolean isJVMCISupportedByGC();236237public native int matchesMethod(Executable method, String pattern);238public native int matchesInline(Executable method, String pattern);239public native boolean shouldPrintAssembly(Executable method, int comp_level);240public native int deoptimizeFrames(boolean makeNotEntrant);241public native boolean isFrameDeoptimized(int depth);242public native void deoptimizeAll();243244public boolean isMethodCompiled(Executable method) {245return isMethodCompiled(method, false /*not osr*/);246}247private native boolean isMethodCompiled0(Executable method, boolean isOsr);248public boolean isMethodCompiled(Executable method, boolean isOsr){249Objects.requireNonNull(method);250return isMethodCompiled0(method, isOsr);251}252public boolean isMethodCompilable(Executable method) {253return isMethodCompilable(method, -1 /*any*/);254}255public boolean isMethodCompilable(Executable method, int compLevel) {256return isMethodCompilable(method, compLevel, false /*not osr*/);257}258private native boolean isMethodCompilable0(Executable method, int compLevel, boolean isOsr);259public boolean isMethodCompilable(Executable method, int compLevel, boolean isOsr) {260Objects.requireNonNull(method);261return isMethodCompilable0(method, compLevel, isOsr);262}263private native boolean isMethodQueuedForCompilation0(Executable method);264public boolean isMethodQueuedForCompilation(Executable method) {265Objects.requireNonNull(method);266return isMethodQueuedForCompilation0(method);267}268// Determine if the compiler corresponding to the compilation level 'compLevel'269// and to the compilation context 'compilation_context' provides an intrinsic270// for the method 'method'. An intrinsic is available for method 'method' if:271// - the intrinsic is enabled (by using the appropriate command-line flag) and272// - the platform on which the VM is running provides the instructions necessary273// for the compiler to generate the intrinsic code.274//275// The compilation context is related to using the DisableIntrinsic flag on a276// per-method level, see hotspot/src/share/vm/compiler/abstractCompiler.hpp277// for more details.278public boolean isIntrinsicAvailable(Executable method,279Executable compilationContext,280int compLevel) {281Objects.requireNonNull(method);282return isIntrinsicAvailable0(method, compilationContext, compLevel);283}284// If usage of the DisableIntrinsic flag is not expected (or the usage can be ignored),285// use the below method that does not require the compilation context as argument.286public boolean isIntrinsicAvailable(Executable method, int compLevel) {287return isIntrinsicAvailable(method, null, compLevel);288}289private native boolean isIntrinsicAvailable0(Executable method,290Executable compilationContext,291int compLevel);292public int deoptimizeMethod(Executable method) {293return deoptimizeMethod(method, false /*not osr*/);294}295private native int deoptimizeMethod0(Executable method, boolean isOsr);296public int deoptimizeMethod(Executable method, boolean isOsr) {297Objects.requireNonNull(method);298return deoptimizeMethod0(method, isOsr);299}300public void makeMethodNotCompilable(Executable method) {301makeMethodNotCompilable(method, -1 /*any*/);302}303public void makeMethodNotCompilable(Executable method, int compLevel) {304makeMethodNotCompilable(method, compLevel, false /*not osr*/);305}306private native void makeMethodNotCompilable0(Executable method, int compLevel, boolean isOsr);307public void makeMethodNotCompilable(Executable method, int compLevel, boolean isOsr) {308Objects.requireNonNull(method);309makeMethodNotCompilable0(method, compLevel, isOsr);310}311public int getMethodCompilationLevel(Executable method) {312return getMethodCompilationLevel(method, false /*not ost*/);313}314private native int getMethodCompilationLevel0(Executable method, boolean isOsr);315public int getMethodCompilationLevel(Executable method, boolean isOsr) {316Objects.requireNonNull(method);317return getMethodCompilationLevel0(method, isOsr);318}319private native boolean testSetDontInlineMethod0(Executable method, boolean value);320public boolean testSetDontInlineMethod(Executable method, boolean value) {321Objects.requireNonNull(method);322return testSetDontInlineMethod0(method, value);323}324public int getCompileQueuesSize() {325return getCompileQueueSize(-1 /*any*/);326}327public native int getCompileQueueSize(int compLevel);328private native boolean testSetForceInlineMethod0(Executable method, boolean value);329public boolean testSetForceInlineMethod(Executable method, boolean value) {330Objects.requireNonNull(method);331return testSetForceInlineMethod0(method, value);332}333public boolean enqueueMethodForCompilation(Executable method, int compLevel) {334return enqueueMethodForCompilation(method, compLevel, -1 /*InvocationEntryBci*/);335}336private native boolean enqueueMethodForCompilation0(Executable method, int compLevel, int entry_bci);337public boolean enqueueMethodForCompilation(Executable method, int compLevel, int entry_bci) {338Objects.requireNonNull(method);339return enqueueMethodForCompilation0(method, compLevel, entry_bci);340}341private native boolean enqueueInitializerForCompilation0(Class<?> aClass, int compLevel);342public boolean enqueueInitializerForCompilation(Class<?> aClass, int compLevel) {343Objects.requireNonNull(aClass);344return enqueueInitializerForCompilation0(aClass, compLevel);345}346private native void clearMethodState0(Executable method);347public native void markMethodProfiled(Executable method);348public void clearMethodState(Executable method) {349Objects.requireNonNull(method);350clearMethodState0(method);351}352public native void lockCompilation();353public native void unlockCompilation();354private native int getMethodEntryBci0(Executable method);355public int getMethodEntryBci(Executable method) {356Objects.requireNonNull(method);357return getMethodEntryBci0(method);358}359private native Object[] getNMethod0(Executable method, boolean isOsr);360public Object[] getNMethod(Executable method, boolean isOsr) {361Objects.requireNonNull(method);362return getNMethod0(method, isOsr);363}364public native long allocateCodeBlob(int size, int type);365public long allocateCodeBlob(long size, int type) {366int intSize = (int) size;367if ((long) intSize != size || size < 0) {368throw new IllegalArgumentException(369"size argument has illegal value " + size);370}371return allocateCodeBlob( intSize, type);372}373public native void freeCodeBlob(long addr);374public native void forceNMethodSweep();375public native Object[] getCodeHeapEntries(int type);376public native int getCompilationActivityMode();377private native long getMethodData0(Executable method);378public long getMethodData(Executable method) {379Objects.requireNonNull(method);380return getMethodData0(method);381}382public native Object[] getCodeBlob(long addr);383384private native void clearInlineCaches0(boolean preserve_static_stubs);385public void clearInlineCaches() {386clearInlineCaches0(false);387}388public void clearInlineCaches(boolean preserve_static_stubs) {389clearInlineCaches0(preserve_static_stubs);390}391392// Intered strings393public native boolean isInStringTable(String str);394395// Memory396public native void readReservedMemory();397public native long allocateMetaspace(ClassLoader classLoader, long size);398public native long incMetaspaceCapacityUntilGC(long increment);399public native long metaspaceCapacityUntilGC();400public native long metaspaceSharedRegionAlignment();401402// Metaspace Arena Tests403public native long createMetaspaceTestContext(long commit_limit, long reserve_limit);404public native void destroyMetaspaceTestContext(long context);405public native void purgeMetaspaceTestContext(long context);406public native void printMetaspaceTestContext(long context);407public native long getTotalCommittedWordsInMetaspaceTestContext(long context);408public native long getTotalUsedWordsInMetaspaceTestContext(long context);409public native long createArenaInTestContext(long context, boolean is_micro);410public native void destroyMetaspaceTestArena(long arena);411public native long allocateFromMetaspaceTestArena(long arena, long word_size);412public native void deallocateToMetaspaceTestArena(long arena, long p, long word_size);413414public native long maxMetaspaceAllocationSize();415416// Don't use these methods directly417// Use sun.hotspot.gc.GC class instead.418public native boolean isGCSupported(int name);419public native boolean isGCSupportedByJVMCICompiler(int name);420public native boolean isGCSelected(int name);421public native boolean isGCSelectedErgonomically();422423// Force Young GC424public native void youngGC();425426// Force Full GC427public native void fullGC();428429// Returns true if the current GC supports concurrent collection control.430public native boolean supportsConcurrentGCBreakpoints();431432private void checkConcurrentGCBreakpointsSupported() {433if (!supportsConcurrentGCBreakpoints()) {434throw new UnsupportedOperationException("Concurrent GC breakpoints not supported");435}436}437438private native void concurrentGCAcquireControl0();439private native void concurrentGCReleaseControl0();440private native void concurrentGCRunToIdle0();441private native boolean concurrentGCRunTo0(String breakpoint);442443private static boolean concurrentGCIsControlled = false;444private void checkConcurrentGCIsControlled() {445if (!concurrentGCIsControlled) {446throw new IllegalStateException("Not controlling concurrent GC");447}448}449450// All collectors supporting concurrent GC breakpoints are expected451// to provide at least the following breakpoints.452public final String AFTER_MARKING_STARTED = "AFTER MARKING STARTED";453public final String BEFORE_MARKING_COMPLETED = "BEFORE MARKING COMPLETED";454455// Collectors supporting concurrent GC breakpoints that do reference456// processing concurrently should provide the following breakpoint.457public final String AFTER_CONCURRENT_REFERENCE_PROCESSING_STARTED =458"AFTER CONCURRENT REFERENCE PROCESSING STARTED";459460public void concurrentGCAcquireControl() {461checkConcurrentGCBreakpointsSupported();462if (concurrentGCIsControlled) {463throw new IllegalStateException("Already controlling concurrent GC");464}465concurrentGCAcquireControl0();466concurrentGCIsControlled = true;467}468469public void concurrentGCReleaseControl() {470checkConcurrentGCBreakpointsSupported();471concurrentGCReleaseControl0();472concurrentGCIsControlled = false;473}474475// Keep concurrent GC idle. Release from breakpoint.476public void concurrentGCRunToIdle() {477checkConcurrentGCBreakpointsSupported();478checkConcurrentGCIsControlled();479concurrentGCRunToIdle0();480}481482// Allow concurrent GC to run to breakpoint.483// Throws IllegalStateException if reached end of cycle first.484public void concurrentGCRunTo(String breakpoint) {485concurrentGCRunTo(breakpoint, true);486}487488// Allow concurrent GC to run to breakpoint.489// Returns true if reached breakpoint. If reached end of cycle first,490// then throws IllegalStateException if errorIfFail is true, returning491// false otherwise.492public boolean concurrentGCRunTo(String breakpoint, boolean errorIfFail) {493checkConcurrentGCBreakpointsSupported();494checkConcurrentGCIsControlled();495if (breakpoint == null) {496throw new NullPointerException("null breakpoint");497} else if (concurrentGCRunTo0(breakpoint)) {498return true;499} else if (errorIfFail) {500throw new IllegalStateException("Missed requested breakpoint \"" + breakpoint + "\"");501} else {502return false;503}504}505506// Method tries to start concurrent mark cycle.507// It returns false if CM Thread is always in concurrent cycle.508public native boolean g1StartConcMarkCycle();509510// Tests on ReservedSpace/VirtualSpace classes511public native int stressVirtualSpaceResize(long reservedSpaceSize, long magnitude, long iterations);512public native void readFromNoaccessArea();513public native long getThreadStackSize();514public native long getThreadRemainingStackSize();515516// CPU features517public native String getCPUFeatures();518519// VM flags520public native boolean isConstantVMFlag(String name);521public native boolean isLockedVMFlag(String name);522public native void setBooleanVMFlag(String name, boolean value);523public native void setIntVMFlag(String name, long value);524public native void setUintVMFlag(String name, long value);525public native void setIntxVMFlag(String name, long value);526public native void setUintxVMFlag(String name, long value);527public native void setUint64VMFlag(String name, long value);528public native void setSizeTVMFlag(String name, long value);529public native void setStringVMFlag(String name, String value);530public native void setDoubleVMFlag(String name, double value);531public native Boolean getBooleanVMFlag(String name);532public native Long getIntVMFlag(String name);533public native Long getUintVMFlag(String name);534public native Long getIntxVMFlag(String name);535public native Long getUintxVMFlag(String name);536public native Long getUint64VMFlag(String name);537public native Long getSizeTVMFlag(String name);538public native String getStringVMFlag(String name);539public native Double getDoubleVMFlag(String name);540private final List<Function<String,Object>> flagsGetters = Arrays.asList(541this::getBooleanVMFlag, this::getIntVMFlag, this::getUintVMFlag,542this::getIntxVMFlag, this::getUintxVMFlag, this::getUint64VMFlag,543this::getSizeTVMFlag, this::getStringVMFlag, this::getDoubleVMFlag);544545public Object getVMFlag(String name) {546return flagsGetters.stream()547.map(f -> f.apply(name))548.filter(x -> x != null)549.findAny()550.orElse(null);551}552553// Jigsaw554public native void DefineModule(Object module, boolean is_open, String version,555String location, Object[] packages);556public native void AddModuleExports(Object from_module, String pkg, Object to_module);557public native void AddReadsModule(Object from_module, Object source_module);558public native void AddModuleExportsToAllUnnamed(Object module, String pkg);559public native void AddModuleExportsToAll(Object module, String pkg);560561public native int getOffsetForName0(String name);562public int getOffsetForName(String name) throws Exception {563int offset = getOffsetForName0(name);564if (offset == -1) {565throw new RuntimeException(name + " not found");566}567return offset;568}569public native Boolean getMethodBooleanOption(Executable method, String name);570public native Long getMethodIntxOption(Executable method, String name);571public native Long getMethodUintxOption(Executable method, String name);572public native Double getMethodDoubleOption(Executable method, String name);573public native String getMethodStringOption(Executable method, String name);574private final List<BiFunction<Executable,String,Object>> methodOptionGetters575= Arrays.asList(this::getMethodBooleanOption, this::getMethodIntxOption,576this::getMethodUintxOption, this::getMethodDoubleOption,577this::getMethodStringOption);578579public Object getMethodOption(Executable method, String name) {580return methodOptionGetters.stream()581.map(f -> f.apply(method, name))582.filter(x -> x != null)583.findAny()584.orElse(null);585}586587// Sharing & archiving588public native String getDefaultArchivePath();589public native boolean cdsMemoryMappingFailed();590public native boolean isSharingEnabled();591public native boolean isShared(Object o);592public native boolean isSharedClass(Class<?> c);593public native boolean areSharedStringsIgnored();594public native boolean isCDSIncluded();595public native boolean isJFRIncluded();596public native boolean isJavaHeapArchiveSupported();597public native Object getResolvedReferences(Class<?> c);598public native void linkClass(Class<?> c);599public native boolean areOpenArchiveHeapObjectsMapped();600601// Compiler Directive602public native int addCompilerDirective(String compDirect);603public native void removeCompilerDirective(int count);604605// Handshakes606public native int handshakeWalkStack(Thread t, boolean all_threads);607public native void asyncHandshakeWalkStack(Thread t);608609// Returns true on linux if library has the noexecstack flag set.610public native boolean checkLibSpecifiesNoexecstack(String libfilename);611612// Container testing613public native boolean isContainerized();614public native int validateCgroup(String procCgroups,615String procSelfCgroup,616String procSelfMountinfo);617public native void printOsInfo();618619// Decoder620public native void disableElfSectionCache();621622// Resolved Method Table623public native long resolvedMethodItemsCount();624625// Protection Domain Table626public native int protectionDomainRemovedCount();627628public native int getKlassMetadataSize(Class<?> c);629630// ThreadSMR GC safety check for threadObj631public native void checkThreadObjOfTerminatingThread(Thread target);632633// libc name634public native String getLibcName();635636// Walk stack frames of current thread637public native void verifyFrames(boolean log, boolean updateRegisterMap);638639public native boolean isJVMTIIncluded();640641public native void waitUnsafe(int time_ms);642643public native void lockCritical();644645public native void unlockCritical();646}647648649