1 /*
2  * Copyright (C) 2020 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 dalvik.system.PathClassLoader;
18 
19 class Main {
20   static final String TEST_NAME = "597-app-images-same-classloader";
21 
22   static final String DEX_FILE = System.getenv("DEX_LOCATION") + "/" + TEST_NAME + ".jar";
23   static final String LIBRARY_SEARCH_PATH = System.getProperty("java.library.path");
24 
25   static final String SECONDARY_NAME = TEST_NAME + "-ex";
26   static final String SECONDARY_DEX_FILE =
27     System.getenv("DEX_LOCATION") + "/" + SECONDARY_NAME + ".jar";
28 
main(String[] args)29   public static void main(String[] args) throws Exception {
30     System.loadLibrary(args[0]);
31 
32     testLoadingSecondaryAppImageInLoadedClassLoader();
33   }
34 
checkAppImageLoaded(String name)35   public static native boolean checkAppImageLoaded(String name);
checkAppImageContains(Class<?> klass)36   public static native boolean checkAppImageContains(Class<?> klass);
checkInitialized(Class<?> klass)37   public static native boolean checkInitialized(Class<?> klass);
38 
testLoadingSecondaryAppImageInLoadedClassLoader()39   public static void testLoadingSecondaryAppImageInLoadedClassLoader() throws Exception {
40     // Initial check that the image isn't already loaded so we don't get bogus results below
41     assertFalse("Secondary app image isn't already loaded",
42         checkAppImageLoaded(SECONDARY_NAME));
43 
44     PathClassLoader pcl = new PathClassLoader(DEX_FILE, LIBRARY_SEARCH_PATH, null);
45     pcl.addDexPath(SECONDARY_DEX_FILE);
46 
47     assertTrue("Ensure app image is loaded if it should be",
48         checkAppImageLoaded(SECONDARY_NAME));
49 
50     Class<?> secondaryCls = pcl.loadClass("Secondary");
51     assertTrue("Ensure Secondary class is in the app image",
52         checkAppImageContains(secondaryCls));
53     assertTrue("Ensure Secondary class is preinitialized", checkInitialized(secondaryCls));
54 
55     secondaryCls.getDeclaredMethod("go").invoke(null);
56   }
57 
assertTrue(String message, boolean flag)58   private static void assertTrue(String message, boolean flag) {
59     if (flag) {
60       return;
61     }
62     throw new AssertionError(message);
63   }
64 
assertFalse(String message, boolean flag)65   private static void assertFalse(String message, boolean flag) {
66     assertTrue(message, !flag);
67   }
68 }
69