Debian Codegraph @

libartservice/service/javatests/com/android/server/art/SecondaryDexopterTest.java

raw
1 /*
2 * Copyright (C) 2022 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 package com.android.server.art;
18
19 import static com.android.server.art.DexUseManagerLocal.DetailedSecondaryDexInfo;
20 import static com.android.server.art.GetDexoptNeededResult.ArtifactsLocation;
21 import static com.android.server.art.OutputArtifacts.PermissionSettings;
22 import static com.android.server.art.model.DexoptResult.DexContainerFileDexoptResult;
23 import static com.android.server.art.testing.TestingUtils.deepEq;
24
25 import static com.google.common.truth.Truth.assertThat;
26
27 import static org.mockito.Mockito.any;
28 import static org.mockito.Mockito.anyBoolean;
29 import static org.mockito.Mockito.anyInt;
30 import static org.mockito.Mockito.argThat;
31 import static org.mockito.Mockito.eq;
32 import static org.mockito.Mockito.isNull;
33 import static org.mockito.Mockito.lenient;
34 import static org.mockito.Mockito.mock;
35 import static org.mockito.Mockito.never;
36 import static org.mockito.Mockito.verify;
37 import static org.mockito.Mockito.when;
38
39 import android.os.CancellationSignal;
40 import android.os.SystemProperties;
41 import android.os.UserHandle;
42
43 import androidx.test.filters.SmallTest;
44 import androidx.test.runner.AndroidJUnit4;
45
46 import com.android.server.art.model.ArtFlags;
47 import com.android.server.art.model.DexoptParams;
48 import com.android.server.art.model.DexoptResult;
49 import com.android.server.art.testing.StaticMockitoRule;
50 import com.android.server.art.testing.TestingUtils;
51 import com.android.server.pm.PackageSetting;
52 import com.android.server.pm.pkg.AndroidPackage;
53 import com.android.server.pm.pkg.PackageState;
54 import com.android.server.pm.pkg.PackageStateUnserialized;
55
56 import org.junit.Before;
57 import org.junit.Rule;
58 import org.junit.Test;
59 import org.junit.runner.RunWith;
60 import org.mockito.Mock;
61
62 import java.util.List;
63 import java.util.Set;
64 import java.util.function.Function;
65
66 @SmallTest
67 @RunWith(AndroidJUnit4.class)
68 public class SecondaryDexopterTest {
69 private static final String PKG_NAME = "com.example.foo";
70 private static final int APP_ID = 12345;
71 private static final UserHandle USER_HANDLE = UserHandle.of(2);
72 private static final int UID = USER_HANDLE.getUid(APP_ID);
73 private static final String APP_DATA_DIR = "/data/user/2/" + PKG_NAME;
74 private static final String DEX_1 = APP_DATA_DIR + "/1.apk";
75 private static final String DEX_2 = APP_DATA_DIR + "/2.apk";
76 private static final String DEX_3 = APP_DATA_DIR + "/3.apk";
77
78 private final DexoptParams mDexoptParams =
79 new DexoptParams.Builder("bg-dexopt")
80 .setCompilerFilter("speed-profile")
81 .setFlags(ArtFlags.FLAG_FOR_PRIMARY_DEX | ArtFlags.FLAG_FOR_SECONDARY_DEX)
82 .build();
83
84 private final ProfilePath mDex1RefProfile = AidlUtils.buildProfilePathForSecondaryRef(DEX_1);
85 private final ProfilePath mDex1CurProfile = AidlUtils.buildProfilePathForSecondaryCur(DEX_1);
86 private final ProfilePath mDex2RefProfile = AidlUtils.buildProfilePathForSecondaryRef(DEX_2);
87 private final ProfilePath mDex3RefProfile = AidlUtils.buildProfilePathForSecondaryRef(DEX_3);
88 private final OutputProfile mDex1PrivateOutputProfile =
89 AidlUtils.buildOutputProfileForSecondary(DEX_1, UID, UID, false /* isOtherReadable */);
90
91 private final int mDefaultDexoptTrigger = DexoptTrigger.COMPILER_FILTER_IS_BETTER
92 | DexoptTrigger.PRIMARY_BOOT_IMAGE_BECOMES_USABLE | DexoptTrigger.NEED_EXTRACTION;
93 private final int mBetterOrSameDexoptTrigger = DexoptTrigger.COMPILER_FILTER_IS_BETTER
94 | DexoptTrigger.COMPILER_FILTER_IS_SAME
95 | DexoptTrigger.PRIMARY_BOOT_IMAGE_BECOMES_USABLE | DexoptTrigger.NEED_EXTRACTION;
96
97 private final MergeProfileOptions mMergeProfileOptions = new MergeProfileOptions();
98
99 @Rule
100 public StaticMockitoRule mockitoRule =
101 new StaticMockitoRule(SystemProperties.class, Constants.class);
102
103 @Mock private SecondaryDexopter.Injector mInjector;
104 @Mock private IArtd mArtd;
105 @Mock private DexUseManagerLocal mDexUseManager;
106 private PackageState mPkgState;
107 private AndroidPackage mPkg;
108 private CancellationSignal mCancellationSignal;
109
110 private SecondaryDexopter mSecondaryDexopter;
111
112 @Before
113 public void setUp() throws Exception {
114 lenient()
115 .when(SystemProperties.getBoolean(eq("dalvik.vm.always_debuggable"), anyBoolean()))
116 .thenReturn(false);
117 lenient().when(SystemProperties.get("dalvik.vm.appimageformat")).thenReturn("lz4");
118 lenient().when(SystemProperties.get("pm.dexopt.shared")).thenReturn("speed");
119
120 // No ISA translation.
121 lenient()
122 .when(SystemProperties.get(argThat(arg -> arg.startsWith("ro.dalvik.vm.isa."))))
123 .thenReturn("");
124
125 lenient().when(Constants.getPreferredAbi()).thenReturn("arm64-v8a");
126 lenient().when(Constants.getNative64BitAbi()).thenReturn("arm64-v8a");
127 lenient().when(Constants.getNative32BitAbi()).thenReturn("armeabi-v7a");
128
129 lenient().when(mInjector.getArtd()).thenReturn(mArtd);
130 lenient().when(mInjector.isSystemUiPackage(any())).thenReturn(false);
131 lenient().when(mInjector.isLauncherPackage(any())).thenReturn(false);
132 lenient().when(mInjector.getDexUseManager()).thenReturn(mDexUseManager);
133
134 List<DetailedSecondaryDexInfo> secondaryDexInfo = createSecondaryDexInfo();
135 lenient()
136 .when(mDexUseManager.getFilteredDetailedSecondaryDexInfo(eq(PKG_NAME)))
137 .thenReturn(secondaryDexInfo);
138
139 mPkgState = createPackageState();
140 mPkg = mPkgState.getAndroidPackage();
141 mCancellationSignal = new CancellationSignal();
142
143 prepareProfiles();
144
145 // Dexopt is always needed and successful.
146 lenient()
147 .when(mArtd.getDexoptNeeded(any(), any(), any(), any(), anyInt()))
148 .thenReturn(dexoptIsNeeded());
149 lenient()
150 .when(mArtd.dexopt(any(), any(), any(), any(), any(), any(), any(), any(), anyInt(),
151 any(), any()))
152 .thenReturn(createArtdDexoptResult());
153
154 lenient()
155 .when(mArtd.createCancellationSignal())
156 .thenReturn(mock(IArtdCancellationSignal.class));
157
158 mSecondaryDexopter = new SecondaryDexopter(
159 mInjector, mPkgState, mPkg, mDexoptParams, mCancellationSignal);
160 }
161
162 @Test
163 public void testDexopt() throws Exception {
164 assertThat(mSecondaryDexopter.dexopt())
165 .comparingElementsUsing(TestingUtils.<DexContainerFileDexoptResult>deepEquality())
166 .containsExactly(
167 DexContainerFileDexoptResult.create(DEX_1, true /* isPrimaryAbi */,
168 "arm64-v8a", "speed-profile", DexoptResult.DEXOPT_PERFORMED,
169 0 /* dex2oatWallTimeMillis */, 0 /* dex2oatCpuTimeMillis */,
170 0 /* sizeBytes */, 0 /* sizeBeforeBytes */,
171 false /* isSkippedDueToStorageLow */),
172 DexContainerFileDexoptResult.create(DEX_2, true /* isPrimaryAbi */,
173 "arm64-v8a", "speed", DexoptResult.DEXOPT_PERFORMED,
174 0 /* dex2oatWallTimeMillis */, 0 /* dex2oatCpuTimeMillis */,
175 0 /* sizeBytes */, 0 /* sizeBeforeBytes */,
176 false /* isSkippedDueToStorageLow */),
177 DexContainerFileDexoptResult.create(DEX_2, false /* isPrimaryAbi */,
178 "armeabi-v7a", "speed", DexoptResult.DEXOPT_PERFORMED,
179 0 /* dex2oatWallTimeMillis */, 0 /* dex2oatCpuTimeMillis */,
180 0 /* sizeBytes */, 0 /* sizeBeforeBytes */,
181 false /* isSkippedDueToStorageLow */),
182 DexContainerFileDexoptResult.create(DEX_3, true /* isPrimaryAbi */,
183 "arm64-v8a", "verify", DexoptResult.DEXOPT_PERFORMED,
184 0 /* dex2oatWallTimeMillis */, 0 /* dex2oatCpuTimeMillis */,
185 0 /* sizeBytes */, 0 /* sizeBeforeBytes */,
186 false /* isSkippedDueToStorageLow */));
187
188 // It should use profile for dex 1.
189
190 verify(mArtd).mergeProfiles(deepEq(List.of(mDex1CurProfile)), deepEq(mDex1RefProfile),
191 deepEq(mDex1PrivateOutputProfile), deepEq(List.of(DEX_1)),
192 deepEq(mMergeProfileOptions));
193
194 verify(mArtd).getDexoptNeeded(
195 eq(DEX_1), eq("arm64"), any(), eq("speed-profile"), eq(mBetterOrSameDexoptTrigger));
196 checkDexoptWithPrivateProfile(verify(mArtd), DEX_1, "arm64",
197 ProfilePath.tmpProfilePath(mDex1PrivateOutputProfile.profilePath), "CLC_FOR_DEX_1");
198
199 verify(mArtd).commitTmpProfile(deepEq(mDex1PrivateOutputProfile.profilePath));
200
201 verify(mArtd).deleteProfile(deepEq(mDex1CurProfile));
202
203 // It should use "speed" for dex 2 for both ISAs and make the artifacts public.
204
205 verify(mArtd, never()).isProfileUsable(deepEq(mDex2RefProfile), any());
206 verify(mArtd, never()).mergeProfiles(any(), deepEq(mDex2RefProfile), any(), any(), any());
207
208 verify(mArtd).getDexoptNeeded(
209 eq(DEX_2), eq("arm64"), any(), eq("speed"), eq(mDefaultDexoptTrigger));
210 checkDexoptWithNoProfile(
211 verify(mArtd), DEX_2, "arm64", "speed", "CLC_FOR_DEX_2", true /* isPublic */);
212
213 verify(mArtd).getDexoptNeeded(
214 eq(DEX_2), eq("arm"), any(), eq("speed"), eq(mDefaultDexoptTrigger));
215 checkDexoptWithNoProfile(
216 verify(mArtd), DEX_2, "arm", "speed", "CLC_FOR_DEX_2", true /* isPublic */);
217
218 // It should use "verify" for dex 3 and make the artifacts private.
219
220 verify(mArtd, never()).isProfileUsable(deepEq(mDex3RefProfile), any());
221 verify(mArtd, never()).mergeProfiles(any(), deepEq(mDex3RefProfile), any(), any(), any());
222
223 verify(mArtd).getDexoptNeeded(
224 eq(DEX_3), eq("arm64"), isNull(), eq("verify"), eq(mDefaultDexoptTrigger));
225 checkDexoptWithNoProfile(verify(mArtd), DEX_3, "arm64", "verify",
226 null /* classLoaderContext */, false /* isPublic */);
227 }
228
229 private AndroidPackage createPackage() {
230 var pkg = mock(AndroidPackage.class);
231 lenient().when(pkg.isVmSafeMode()).thenReturn(false);
232 lenient().when(pkg.isDebuggable()).thenReturn(false);
233 lenient().when(pkg.getTargetSdkVersion()).thenReturn(123);
234 lenient().when(pkg.isSignedWithPlatformKey()).thenReturn(false);
235 lenient().when(pkg.isNonSdkApiRequested()).thenReturn(false);
236 return pkg;
237 }
238
239 private PackageState createPackageState() {
240 var pkgState = mock(PackageState.class);
241 lenient().when(pkgState.getPackageName()).thenReturn(PKG_NAME);
242 lenient().when(pkgState.getPrimaryCpuAbi()).thenReturn("arm64-v8a");
243 lenient().when(pkgState.getSecondaryCpuAbi()).thenReturn("armeabi-v7a");
244 lenient().when(pkgState.getAppId()).thenReturn(APP_ID);
245 lenient().when(pkgState.getSeInfo()).thenReturn("se-info");
246 AndroidPackage pkg = createPackage();
247 lenient().when(pkgState.getAndroidPackage()).thenReturn(pkg);
248 return pkgState;
249 }
250
251 private List<DetailedSecondaryDexInfo> createSecondaryDexInfo() throws Exception {
252 // This should be compiled with profile.
253 var dex1Info = mock(DetailedSecondaryDexInfo.class);
254 lenient().when(dex1Info.dexPath()).thenReturn(DEX_1);
255 lenient().when(dex1Info.userHandle()).thenReturn(USER_HANDLE);
256 lenient().when(dex1Info.classLoaderContext()).thenReturn("CLC_FOR_DEX_1");
257 lenient().when(dex1Info.abiNames()).thenReturn(Set.of("arm64-v8a"));
258 lenient().when(dex1Info.isUsedByOtherApps()).thenReturn(false);
259 lenient().when(dex1Info.isDexFilePublic()).thenReturn(true);
260
261 // This should be compiled without profile because it's used by other apps.
262 var dex2Info = mock(DetailedSecondaryDexInfo.class);
263 lenient().when(dex2Info.dexPath()).thenReturn(DEX_2);
264 lenient().when(dex2Info.userHandle()).thenReturn(USER_HANDLE);
265 lenient().when(dex2Info.classLoaderContext()).thenReturn("CLC_FOR_DEX_2");
266 lenient().when(dex2Info.abiNames()).thenReturn(Set.of("arm64-v8a", "armeabi-v7a"));
267 lenient().when(dex2Info.isUsedByOtherApps()).thenReturn(true);
268 lenient().when(dex2Info.isDexFilePublic()).thenReturn(true);
269
270 // This should be compiled with verify because the class loader context is invalid.
271 var dex3Info = mock(DetailedSecondaryDexInfo.class);
272 lenient().when(dex3Info.dexPath()).thenReturn(DEX_3);
273 lenient().when(dex3Info.userHandle()).thenReturn(USER_HANDLE);
274 lenient().when(dex3Info.classLoaderContext()).thenReturn(null);
275 lenient().when(dex3Info.abiNames()).thenReturn(Set.of("arm64-v8a"));
276 lenient().when(dex3Info.isUsedByOtherApps()).thenReturn(false);
277 lenient().when(dex3Info.isDexFilePublic()).thenReturn(false);
278
279 return List.of(dex1Info, dex2Info, dex3Info);
280 }
281
282 private void prepareProfiles() throws Exception {
283 // Profile for dex file 1 is usable.
284 lenient().when(mArtd.isProfileUsable(deepEq(mDex1RefProfile), any())).thenReturn(true);
285 lenient()
286 .when(mArtd.getProfileVisibility(deepEq(mDex1RefProfile)))
287 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
288
289 // Profiles for dex file 2 and 3 are also usable, but shouldn't be used.
290 lenient().when(mArtd.isProfileUsable(deepEq(mDex2RefProfile), any())).thenReturn(true);
291 lenient()
292 .when(mArtd.getProfileVisibility(deepEq(mDex2RefProfile)))
293 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
294 lenient().when(mArtd.isProfileUsable(deepEq(mDex3RefProfile), any())).thenReturn(true);
295 lenient()
296 .when(mArtd.getProfileVisibility(deepEq(mDex3RefProfile)))
297 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
298
299 lenient().when(mArtd.mergeProfiles(any(), any(), any(), any(), any())).thenReturn(true);
300 }
301
302 private GetDexoptNeededResult dexoptIsNeeded() {
303 var result = new GetDexoptNeededResult();
304 result.isDexoptNeeded = true;
305 result.artifactsLocation = ArtifactsLocation.NONE_OR_ERROR;
306 result.isVdexUsable = false;
307 return result;
308 }
309
310 private ArtdDexoptResult createArtdDexoptResult() {
311 var result = new ArtdDexoptResult();
312 result.cancelled = false;
313 result.wallTimeMs = 0;
314 result.cpuTimeMs = 0;
315 result.sizeBytes = 0;
316 result.sizeBeforeBytes = 0;
317 return result;
318 }
319
320 private void checkDexoptWithPrivateProfile(IArtd artd, String dexPath, String isa,
321 ProfilePath profile, String classLoaderContext) throws Exception {
322 PermissionSettings permissionSettings = buildPermissionSettings(false /* isPublic */);
323 OutputArtifacts outputArtifacts = AidlUtils.buildOutputArtifacts(
324 dexPath, isa, false /* isInDalvikCache */, permissionSettings);
325 artd.dexopt(deepEq(outputArtifacts), eq(dexPath), eq(isa), eq(classLoaderContext),
326 eq("speed-profile"), deepEq(profile), any(), isNull() /* dmFile */, anyInt(),
327 argThat(dexoptOptions -> dexoptOptions.generateAppImage == false), any());
328 }
329
330 private void checkDexoptWithNoProfile(IArtd artd, String dexPath, String isa,
331 String compilerFilter, String classLoaderContext, boolean isPublic) throws Exception {
332 PermissionSettings permissionSettings = buildPermissionSettings(isPublic);
333 OutputArtifacts outputArtifacts = AidlUtils.buildOutputArtifacts(
334 dexPath, isa, false /* isInDalvikCache */, permissionSettings);
335 artd.dexopt(deepEq(outputArtifacts), eq(dexPath), eq(isa), eq(classLoaderContext),
336 eq(compilerFilter), isNull(), any(), isNull() /* dmFile */, anyInt(),
337 argThat(dexoptOptions -> dexoptOptions.generateAppImage == false), any());
338 }
339
340 private PermissionSettings buildPermissionSettings(boolean isPublic) {
341 FsPermission dirFsPermission = AidlUtils.buildFsPermission(UID /* uid */, UID /* gid */,
342 false /* isOtherReadable */, true /* isOtherExecutable */);
343 FsPermission fileFsPermission =
344 AidlUtils.buildFsPermission(UID /* uid */, UID /* gid */, isPublic);
345 return AidlUtils.buildPermissionSettings(
346 dirFsPermission, fileFsPermission, AidlUtils.buildSeContext("se-info", UID));
347 }
348 }