Path: blob/master/test/jdk/java/lang/StackWalker/LocalsAndOperands.java
41149 views
/*1* Copyright (c) 2015, 2018, 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*/2223/*24* @test25* @bug 8020968 8147039 815607326* @summary Tests for locals and operands27* @modules java.base/java.lang:open28* @run testng/othervm -Xint -DtestUnused=true LocalsAndOperands29* @run testng/othervm -Xcomp LocalsAndOperands30*/3132/*33* @test34* @bug 8020968 8147039 815607335* @modules java.base/java.lang:open36* @requires !vm.graal.enabled37* @run testng/othervm -Xcomp -XX:-TieredCompilation LocalsAndOperands38*/3940import org.testng.annotations.*;41import static org.testng.Assert.*;42import java.lang.StackWalker.StackFrame;43import static java.lang.StackWalker.Option.*;44import java.lang.reflect.*;45import java.util.*;46import java.util.stream.*;4748public class LocalsAndOperands {49static final boolean debug = false;50static final boolean is32bit;51static final boolean testUnused;5253static Class<?> liveStackFrameClass;54static Class<?> primitiveSlotClass;55static Class<?> primitiveSlot32Class;56static Class<?> primitiveSlot64Class;5758static StackWalker extendedWalker;59static Method getLocals;60static Method getOperands;61static Method getMonitors;62static Method primitiveSize;63static Method primitiveLongValue;64static Method primitiveIntValue;65static Method getExtendedWalker;6667private static final long LOWER_LONG_VAL = 4L; // Lower bits68private static final long UPPER_LONG_VAL = 0x123400000000L; // Upper bits69private static final long NEG_LONG_VAL = Long.MIN_VALUE;7071private static final double LOWER_DOUBLE_VAL = Double.longBitsToDouble(0xABCDL);72private static final double UPPER_DOUBLE_VAL = Double.longBitsToDouble(0x432100000000L);7374static {75try {76liveStackFrameClass = Class.forName("java.lang.LiveStackFrame");77primitiveSlotClass = Class.forName("java.lang.LiveStackFrame$PrimitiveSlot");78primitiveSlot32Class = Class.forName("java.lang.LiveStackFrameInfo$PrimitiveSlot32");79primitiveSlot64Class = Class.forName("java.lang.LiveStackFrameInfo$PrimitiveSlot64");8081getLocals = liveStackFrameClass.getDeclaredMethod("getLocals");82getLocals.setAccessible(true);8384getOperands = liveStackFrameClass.getDeclaredMethod("getStack");85getOperands.setAccessible(true);8687getMonitors = liveStackFrameClass.getDeclaredMethod("getMonitors");88getMonitors.setAccessible(true);8990primitiveSize = primitiveSlotClass.getDeclaredMethod("size");91primitiveSize.setAccessible(true);9293primitiveLongValue = primitiveSlotClass.getDeclaredMethod("longValue");94primitiveLongValue.setAccessible(true);9596primitiveIntValue = primitiveSlotClass.getDeclaredMethod("intValue");97primitiveIntValue.setAccessible(true);9899getExtendedWalker = liveStackFrameClass.getMethod("getStackWalker", Set.class);100getExtendedWalker.setAccessible(true);101extendedWalker = (StackWalker) getExtendedWalker.invoke(null,102EnumSet.noneOf(StackWalker.Option.class));103104String dataModel = System.getProperty("sun.arch.data.model");105if ("32".equals(dataModel)) {106is32bit = true;107} else if ("64".equals(dataModel)) {108is32bit= false;109} else {110throw new RuntimeException("Weird data model:" + dataModel);111}112System.out.println("VM bits: " + dataModel);113114testUnused = System.getProperty("testUnused") != null;115} catch (Throwable t) { throw new RuntimeException(t); }116}117118/** Helper method to return a StackFrame's locals */119static Object[] invokeGetLocals(StackFrame arg) {120try {121return (Object[]) getLocals.invoke(arg);122} catch (Exception e) { throw new RuntimeException(e); }123}124125/*****************126* DataProviders *127*****************/128129/** Calls KnownLocalsTester.testLocals* and provides LiveStackFrames */130@DataProvider131public static StackFrame[][] knownLocalsProvider() {132List<StackFrame[]> list = new ArrayList<>(3);133list.add(new KnownLocalsTester().testLocalsKeepAlive());134list.add(new KnownLocalsTester().testLocalsKeepAliveArgs(0xA, 'z',135"himom", 0x3FF00000000L + 0xFFFF, Math.PI));136if (testUnused) {137list.add(new KnownLocalsTester().testLocalsUnused());138}139return list.toArray(new StackFrame[1][1]);140}141142/****************143* Test methods *144****************/145146/**147* Check for expected local values in the LiveStackFrame148*/149@Test(dataProvider = "knownLocalsProvider")150public static void checkLocalValues(StackFrame... frames) {151dumpFramesIfDebug(frames);152try {153Stream.of(frames)154.filter(f -> KnownLocalsTester.TEST_METHODS.contains(f.getMethodName()))155.forEach(LocalsAndOperands::checkFrameLocals);156} catch (Exception e) { dumpFramesIfNotDebug(frames); throw e; }157}158159/**160* Check the locals in the given StackFrame against the expected values.161*/162private static void checkFrameLocals(StackFrame f) {163Object[] expectedArray = KnownLocalsTester.LOCAL_VALUES;164Object[] locals = invokeGetLocals(f);165166for (int i = 0; i < locals.length; i++) {167Object expected = expectedArray[i];168Object observed = locals[i];169170if (expected == null) { /* skip nulls in golden values */171continue;172} else if (expected instanceof KnownLocalsTester.TwoSlotValue) {173// confirm integrity of expected values174assertEquals(expectedArray[i+1], null,175"Malformed array of expected values - slot after TwoSlotValue should be null");176assertLongIsInSlots(locals[i], locals[i+1],177((KnownLocalsTester.TwoSlotValue)expected).value);178i++; // skip following slot179} else if (primitiveSlotClass.isInstance(observed)) { // single slot primitive180assertTrue(primitiveValueEquals(observed, expected),181"Local value mismatch: local " + i + " value is " +182observed + ", expected " + expected);183} else if (expected instanceof Class) {184assertTrue(((Class)expected).isInstance(observed),185"Local value mismatch: local " + i + " expected instancof " +186expected + " but got " + observed);187} else if (expected instanceof String) {188assertEquals(expected, observed, "Local value mismatch: local " +189i + " value is " + observed + ", expected " + expected);190} else {191throw new RuntimeException("Unrecognized expected local value " +192i + ": " + expected);193}194}195}196197/**198* Sanity check for locals and operands, including testng/jtreg frames199* using all StackWalker options.200*/201@Test202public synchronized void fullStackSanityCheck() throws Throwable {203if (debug) {204System.out.println("Running fullStackSanityCheck");205}206StackWalker sw = (StackWalker) getExtendedWalker.invoke(null,207EnumSet.of(SHOW_HIDDEN_FRAMES, SHOW_REFLECT_FRAMES,208RETAIN_CLASS_REFERENCE));209sw.forEach(f -> {210if (debug) {211printLocals(f);212} else {213try {214System.out.println(" " + f + ": " +215((Object[]) getLocals.invoke(f)).length + " locals, " +216((Object[]) getOperands.invoke(f)).length + " operands, " +217((Object[]) getMonitors.invoke(f)).length + " monitors");218} catch (IllegalAccessException|InvocationTargetException t) {219throw new RuntimeException(t);220}221}222});223}224225/**226* Test that LiveStackFrames are not provided with the default StackWalker227* options.228*/229@Test230public static void noLocalsSanityCheck() {231StackWalker sw = StackWalker.getInstance();232sw.forEach(f -> {233assertFalse(liveStackFrameClass.isInstance(f),234"should not be LiveStackFrame");235});236}237238/**239* Class stack-walking methods with a known set of methods and local variables.240*/241static class KnownLocalsTester {242private StackWalker walker;243244KnownLocalsTester() {245this.walker = extendedWalker;246}247248/**249* Perform stackwalk without keeping local variables alive and return an250* array of the collected StackFrames251*/252private synchronized StackFrame[] testLocalsUnused() {253// Unused local variables will become dead254int x = 0xA;255char c = 'z'; // 0x7A256String hi = "himom";257long l = 0x3FF00000000L + 0xFFFFL;258double d = Math.PI;259260return walker.walk(s ->261s.filter(f -> TEST_METHODS.contains(f.getMethodName()))262.toArray(StackFrame[]::new)263);264}265266/**267* Perform stackwalk, keeping local variables alive, and return a list of268* the collected StackFrames269*/270private synchronized StackFrame[] testLocalsKeepAlive() {271int x = 0xA;272char c = 'z'; // 0x7A273String hi = "himom";274long l = 0x3FF00000000L + 0xFFFFL;275double d = Math.PI;276277StackFrame[] frames = walker.walk(s ->278s.filter(f -> TEST_METHODS.contains(f.getMethodName()))279.toArray(StackFrame[]::new)280);281282// Use local variables so they stay alive283System.out.println("Stayin' alive: "+this+" "+x+" "+c+" "+hi+" "+l+" "+d);284return frames;285}286287/**288* Perform stackwalk, keeping method arguments alive, and return a list of289* the collected StackFrames290*/291private synchronized StackFrame[] testLocalsKeepAliveArgs(int x, char c,292String hi, long l,293double d) {294StackFrame[] frames = walker.walk(s ->295s.filter(f -> TEST_METHODS.contains(f.getMethodName()))296.toArray(StackFrame[]::new)297);298299// Use local variables so they stay alive300System.out.println("Stayin' alive: "+this+" "+x+" "+c+" "+hi+" "+l+" "+d);301return frames;302}303304// An expected two-slot local (i.e. long or double)305static class TwoSlotValue {306public long value;307public TwoSlotValue(long value) { this.value = value; }308}309310// Expected values for locals in KnownLocalsTester.testLocals* methods311private final static Object[] LOCAL_VALUES = new Object[] {312LocalsAndOperands.KnownLocalsTester.class,313Integer.valueOf(0xA),314Integer.valueOf(0x7A),315"himom",316new TwoSlotValue(0x3FF00000000L + 0xFFFFL),317null, // 2nd slot318new TwoSlotValue(Double.doubleToRawLongBits(Math.PI)),319null, // 2nd slot320Integer.valueOf(0)321};322323private final static List<String> TEST_METHODS =324List.of("testLocalsUnused",325"testLocalsKeepAlive",326"testLocalsKeepAliveArgs");327}328329/* Simpler tests of long & double arguments */330331@Test332public static void testUsedLongArg() throws Exception {333usedLong(LOWER_LONG_VAL);334usedLong(UPPER_LONG_VAL);335usedLong(NEG_LONG_VAL);336}337338private static void usedLong(long longArg) throws Exception {339StackFrame[] frames = extendedWalker.walk(s ->340s.filter(f -> "usedLong".equals(f.getMethodName()))341.toArray(StackFrame[]::new)342);343try {344dumpFramesIfDebug(frames);345346Object[] locals = (Object[]) getLocals.invoke(frames[0]);347assertLongIsInSlots(locals[0], locals[1], longArg);348System.out.println("Stayin' alive: " + longArg);349} catch (Exception t) {350dumpFramesIfNotDebug(frames);351throw t;352}353}354355@Test356public static void testUnusedLongArg() throws Exception {357if (testUnused) {358unusedLong(NEG_LONG_VAL);359}360}361362private static void unusedLong(long longArg) throws Exception {363StackFrame[] frames = extendedWalker.walk(s ->364s.filter(f -> "unusedLong".equals(f.getMethodName()))365.toArray(StackFrame[]::new)366);367try {368dumpFramesIfDebug(frames);369370final Object[] locals = (Object[]) getLocals.invoke(frames[0]);371assertLongIsInSlots(locals[0], locals[1], NEG_LONG_VAL);372} catch (Exception t) {373dumpFramesIfNotDebug(frames);374throw t;375}376}377378@Test379public static void testUsedDoubleArg() throws Exception {380usedDouble(LOWER_DOUBLE_VAL);381usedDouble(UPPER_DOUBLE_VAL);382}383384private static void usedDouble(double doubleArg) throws Exception {385StackFrame[] frames = extendedWalker.walk(s ->386s.filter(f -> "usedDouble".equals(f.getMethodName()))387.toArray(StackFrame[]::new)388);389try {390dumpFramesIfDebug(frames);391392Object[] locals = (Object[]) getLocals.invoke(frames[0]);393assertDoubleIsInSlots(locals[0], locals[1], doubleArg);394System.out.println("Stayin' alive: " + doubleArg);395} catch (Exception t) {396dumpFramesIfNotDebug(frames);397throw t;398}399}400401/*******************402* Utility Methods *403*******************/404405/**406* Print stack trace with locals407*/408public static void dumpStackWithLocals(StackFrame...frames) {409Stream.of(frames).forEach(LocalsAndOperands::printLocals);410}411412public static void dumpFramesIfDebug(StackFrame...frames) {413if (debug) { dumpStackWithLocals(frames); }414}415416public static void dumpFramesIfNotDebug(StackFrame...frames) {417if (!debug) { dumpStackWithLocals(frames); }418}419420/**421* Print the StackFrame and an indexed list of its locals422*/423public static void printLocals(StackWalker.StackFrame frame) {424try {425System.out.println("Locals for: " + frame);426Object[] locals = (Object[]) getLocals.invoke(frame);427for (int i = 0; i < locals.length; i++) {428String localStr = null;429430if (primitiveSlot64Class.isInstance(locals[i])) {431localStr = String.format("0x%X",432(Long)primitiveLongValue.invoke(locals[i]));433} else if (primitiveSlot32Class.isInstance(locals[i])) {434localStr = String.format("0x%X",435(Integer)primitiveIntValue.invoke(locals[i]));436} else if (locals[i] != null) {437localStr = locals[i].toString();438}439System.out.format(" local %d: %s type %s\n", i, localStr, type(locals[i]));440}441442Object[] operands = (Object[]) getOperands.invoke(frame);443for (int i = 0; i < operands.length; i++) {444System.out.format(" operand %d: %s type %s%n", i, operands[i],445type(operands[i]));446}447448Object[] monitors = (Object[]) getMonitors.invoke(frame);449for (int i = 0; i < monitors.length; i++) {450System.out.format(" monitor %d: %s%n", i, monitors[i]);451}452} catch (Exception e) { throw new RuntimeException(e); }453}454455private static String type(Object o) {456try {457if (o == null) {458return "null";459} else if (primitiveSlotClass.isInstance(o)) {460int s = (int)primitiveSize.invoke(o);461return s + "-byte primitive";462} else {463return o.getClass().getName();464}465} catch(Exception e) { throw new RuntimeException(e); }466}467468/*469* Check if the PrimitiveValue "primVal" contains the specified value,470* either a Long or an Integer.471*/472static boolean primitiveValueEquals(Object primVal, Object expectedVal) {473try {474if (expectedVal instanceof Long) {475assertFalse(is32bit);476assertTrue(primitiveSlot64Class.isInstance(primVal));477assertTrue(8 == (int)primitiveSize.invoke(primVal));478return Objects.equals(primitiveLongValue.invoke(primVal), expectedVal);479} else if (expectedVal instanceof Integer) {480int expectedInt = (Integer)expectedVal;481if (is32bit) {482assertTrue(primitiveSlot32Class.isInstance(primVal),483"expected a PrimitiveSlot32 on 32-bit VM");484assertTrue(4 == (int)primitiveSize.invoke(primVal));485return expectedInt == (int)primitiveIntValue.invoke(primVal);486} else {487assertTrue(primitiveSlot64Class.isInstance(primVal),488"expected a PrimitiveSlot64 on 64-bit VM");489assertTrue(8 == (int)primitiveSize.invoke(primVal));490// Look for int expectedVal in high- or low-order 32 bits491long primValLong = (long)primitiveLongValue.invoke(primVal);492return (int)(primValLong & 0x00000000FFFFFFFFL) == expectedInt ||493(int)(primValLong >>> 32) == expectedInt;494}495} else {496throw new RuntimeException("Called with non-Integer/Long: " + expectedVal);497}498} catch (IllegalAccessException|InvocationTargetException e) {499throw new RuntimeException(e);500}501502}503504/*505* Assert that the expected 2-slot long value is stored somewhere in the506* pair of slots.507* Throw exception if long value isn't in the two slots given.508* Accounts for 32 vs 64 bit, but is lax on endianness (accepts either)509*/510static void assertLongIsInSlots(Object primVal0, Object primVal1, long expected) {511try {512if (is32bit) {513int upper = (int)(expected & 0xFFFFFFFFL);514int lower = (int)(expected >> 32);515516if (!((primitiveValueEquals(primVal0, upper) &&517primitiveValueEquals(primVal1, lower)) ||518(primitiveValueEquals(primVal0, lower) &&519primitiveValueEquals(primVal1, upper)))) {520throw new RuntimeException(String.format("0x%X and 0x%X of 0x%016X not found in 0x%X and 0x%X",521upper, lower, expected,522(int)primitiveIntValue.invoke(primVal0),523(int)primitiveIntValue.invoke(primVal1)));524}525} else {526if (!(primitiveValueEquals(primVal0, expected) ||527primitiveValueEquals(primVal1, expected))) {528throw new RuntimeException(String.format("0x%016X not found in 0x%016X or 0x%016X",529expected,530(long)primitiveLongValue.invoke(primVal0),531(long)primitiveLongValue.invoke(primVal1)));532}533}534} catch (IllegalAccessException|InvocationTargetException e) {535throw new RuntimeException(e);536}537}538539static void assertDoubleIsInSlots(Object primVal0, Object primVal1, double expected) {540assertLongIsInSlots(primVal0, primVal1, Double.doubleToRawLongBits(expected));541}542}543544545