1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 import java.lang.reflect.InvocationTargetException; 18 import java.lang.reflect.Method; 19 20 public class Main { main(String[] args)21 public static void main(String[] args) throws Throwable { 22 // Class BadField is defined in BadField.smali. 23 Class<?> c = Class.forName("BadField"); 24 25 // Storing null is OK. 26 c.getMethod("storeStaticNull").invoke(null); 27 c.getMethod("storeInstanceNull").invoke(null); 28 c.getMethod("storeStatic", Object.class).invoke(null, new Object[]{ null }); 29 c.getMethod("storeInstance", c, Object.class).invoke( 30 null, new Object[]{ c.newInstance(), null }); 31 32 // Storing anything else should throw an exception. 33 testStoreObject(c.getMethod("storeStaticObject")); 34 testStoreObject(c.getMethod("storeInstanceObject")); 35 testStoreObject(c.getMethod("storeStatic", Object.class), new Object()); 36 testStoreObject( 37 c.getMethod("storeInstance", c, Object.class), c.newInstance(), new Object()); 38 39 // Loading is OK. 40 c = Class.forName("BadFieldGet"); 41 testLoadObject(c, "loadStatic"); 42 } 43 testLoadObject(Class<?> c, String methodName)44 public static void testLoadObject(Class<?> c, String methodName) throws Throwable { 45 c.getMethod(methodName).invoke(null); 46 } 47 testStoreObject(Method method, Object... arguments)48 public static void testStoreObject(Method method, Object... arguments) throws Throwable { 49 try { 50 method.invoke(null, arguments); 51 throw new Error("Expected NoClassDefFoundError"); 52 } catch (InvocationTargetException expected) { 53 Throwable e = expected.getCause(); 54 if (e instanceof NoClassDefFoundError) { 55 // The NoClassDefFoundError is for the field widget in class BadField. 56 if (!e.getMessage().equals("Failed resolution of: LWidget;")) { 57 throw new Error("Unexpected " + e); 58 } 59 } else { 60 throw new Error("Unexpected " + e); 61 } 62 } 63 } 64 privateMethod()65 private static void privateMethod() { 66 } 67 } 68