Debian Codegraph @

libartservice/service/javatests/com/android/server/art/DexUseManagerTest.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.DexUseManagerLocal.DexLoader;
21 import static com.android.server.art.DexUseManagerLocal.SecondaryDexInfo;
22
23 import static com.google.common.truth.Truth.assertThat;
24
25 import static org.mockito.Mockito.any;
26 import static org.mockito.Mockito.anyInt;
27 import static org.mockito.Mockito.argThat;
28 import static org.mockito.Mockito.eq;
29 import static org.mockito.Mockito.lenient;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.when;
32
33 import android.content.BroadcastReceiver;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.os.Binder;
37 import android.os.Environment;
38 import android.os.Process;
39 import android.os.SystemProperties;
40 import android.os.UserHandle;
41 import android.os.storage.StorageManager;
42
43 import androidx.test.filters.SmallTest;
44 import androidx.test.runner.AndroidJUnit4;
45
46 import com.android.server.art.model.DexContainerFileUseInfo;
47 import com.android.server.art.proto.DexUseProto;
48 import com.android.server.art.testing.MockClock;
49 import com.android.server.art.testing.StaticMockitoRule;
50 import com.android.server.pm.PackageManagerLocal;
51 import com.android.server.pm.pkg.AndroidPackage;
52 import com.android.server.pm.pkg.AndroidPackageSplit;
53 import com.android.server.pm.pkg.PackageState;
54
55 import dalvik.system.PathClassLoader;
56
57 import org.junit.Before;
58 import org.junit.Rule;
59 import org.junit.Test;
60 import org.junit.runner.RunWith;
61 import org.mockito.ArgumentCaptor;
62 import org.mockito.Mock;
63
64 import java.io.File;
65 import java.io.FileInputStream;
66 import java.io.InputStream;
67 import java.util.ArrayList;
68 import java.util.HashMap;
69 import java.util.List;
70 import java.util.Map;
71 import java.util.Set;
72 import java.util.UUID;
73
74 @SmallTest
75 @RunWith(AndroidJUnit4.class)
76 public class DexUseManagerTest {
77 private static final String LOADING_PKG_NAME = "com.example.loadingpackage";
78 private static final String OWNING_PKG_NAME = "com.example.owningpackage";
79 private static final String BASE_APK = "/data/app/" + OWNING_PKG_NAME + "/base.apk";
80 private static final String SPLIT_APK = "/data/app/" + OWNING_PKG_NAME + "/split_0.apk";
81
82 @Rule
83 public StaticMockitoRule mockitoRule =
84 new StaticMockitoRule(SystemProperties.class, Constants.class, Process.class);
85
86 private final UserHandle mUserHandle = Binder.getCallingUserHandle();
87
88 /**
89 * The default value of `isDexFilePublic` returned by `getSecondaryDexInfo`. The value doesn't
90 * matter because it's undefined, but it's needed for deep equality check, to make the test
91 * simpler.
92 */
93 private final boolean mDefaultIsDexFilePublic = true;
94
95 @Mock private PackageManagerLocal.FilteredSnapshot mSnapshot;
96 @Mock private DexUseManagerLocal.Injector mInjector;
97 @Mock private IArtd mArtd;
98 @Mock private Context mContext;
99 private DexUseManagerLocal mDexUseManager;
100 private String mCeDir;
101 private String mDeDir;
102 private MockClock mMockClock;
103 private ArgumentCaptor<BroadcastReceiver> mBroadcastReceiverCaptor;
104 private File mTempFile;
105 private Map<String, PackageState> mPackageStates;
106
107 @Before
108 public void setUp() throws Exception {
109 // No ISA translation.
110 lenient()
111 .when(SystemProperties.get(argThat(arg -> arg.startsWith("ro.dalvik.vm.isa."))))
112 .thenReturn("");
113
114 lenient().when(Constants.getPreferredAbi()).thenReturn("arm64-v8a");
115 lenient().when(Constants.getNative64BitAbi()).thenReturn("arm64-v8a");
116 lenient().when(Constants.getNative32BitAbi()).thenReturn("armeabi-v7a");
117
118 lenient().when(Process.isIsolatedUid(anyInt())).thenReturn(false);
119
120 mPackageStates = new HashMap<>();
121
122 PackageState loadingPkgState = createPackageState(LOADING_PKG_NAME, "armeabi-v7a");
123 addPackage(LOADING_PKG_NAME, loadingPkgState);
124 PackageState owningPkgState = createPackageState(OWNING_PKG_NAME, "arm64-v8a");
125 addPackage(OWNING_PKG_NAME, owningPkgState);
126 PackageState platformPkgState =
127 createPackageState(Utils.PLATFORM_PACKAGE_NAME, "arm64-v8a");
128 addPackage(Utils.PLATFORM_PACKAGE_NAME, platformPkgState);
129
130 lenient().when(mSnapshot.getPackageStates()).thenReturn(mPackageStates);
131
132 mBroadcastReceiverCaptor = ArgumentCaptor.forClass(BroadcastReceiver.class);
133 lenient()
134 .when(mContext.registerReceiver(mBroadcastReceiverCaptor.capture(), any()))
135 .thenReturn(mock(Intent.class));
136
137 mCeDir = Environment
138 .getDataCePackageDirectoryForUser(StorageManager.UUID_DEFAULT,
139 Binder.getCallingUserHandle(), OWNING_PKG_NAME)
140 .toString();
141 mDeDir = Environment
142 .getDataDePackageDirectoryForUser(StorageManager.UUID_DEFAULT,
143 Binder.getCallingUserHandle(), OWNING_PKG_NAME)
144 .toString();
145 mMockClock = new MockClock();
146
147 mTempFile = File.createTempFile("package-dex-usage", ".pb");
148 mTempFile.deleteOnExit();
149
150 lenient().when(mInjector.getArtd()).thenReturn(mArtd);
151 lenient().when(mInjector.getCurrentTimeMillis()).thenReturn(0l);
152 lenient().when(mInjector.getFilename()).thenReturn(mTempFile.getPath());
153 lenient()
154 .when(mInjector.createScheduledExecutor())
155 .thenAnswer(invocation -> mMockClock.createScheduledExecutor());
156 lenient().when(mInjector.getContext()).thenReturn(mContext);
157 lenient().when(mInjector.getAllPackageNames()).thenReturn(mPackageStates.keySet());
158
159 mDexUseManager = new DexUseManagerLocal(mInjector);
160 mDexUseManager.systemReady();
161 }
162
163 @Test
164 public void testPrimaryDexOwned() {
165 mDexUseManager.notifyDexContainersLoaded(
166 mSnapshot, OWNING_PKG_NAME, Map.of(BASE_APK, "CLC"));
167
168 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, BASE_APK))
169 .containsExactly(DexLoader.create(OWNING_PKG_NAME, false /* isolatedProcess */));
170 assertThat(mDexUseManager.isPrimaryDexUsedByOtherApps(OWNING_PKG_NAME, BASE_APK)).isFalse();
171
172 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, SPLIT_APK)).isEmpty();
173 assertThat(mDexUseManager.isPrimaryDexUsedByOtherApps(OWNING_PKG_NAME, SPLIT_APK))
174 .isFalse();
175 }
176
177 @Test
178 public void testPrimaryDexOwnedIsolated() {
179 when(Process.isIsolatedUid(anyInt())).thenReturn(true);
180 mDexUseManager.notifyDexContainersLoaded(
181 mSnapshot, OWNING_PKG_NAME, Map.of(BASE_APK, "CLC"));
182
183 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, BASE_APK))
184 .containsExactly(DexLoader.create(OWNING_PKG_NAME, true /* isolatedProcess */));
185 assertThat(mDexUseManager.isPrimaryDexUsedByOtherApps(OWNING_PKG_NAME, BASE_APK)).isTrue();
186
187 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, SPLIT_APK)).isEmpty();
188 assertThat(mDexUseManager.isPrimaryDexUsedByOtherApps(OWNING_PKG_NAME, SPLIT_APK))
189 .isFalse();
190 }
191
192 @Test
193 public void testPrimaryDexOwnedSplitIsolated() {
194 when(Process.isIsolatedUid(anyInt())).thenReturn(true);
195 mDexUseManager.notifyDexContainersLoaded(
196 mSnapshot, OWNING_PKG_NAME, Map.of(SPLIT_APK, "CLC"));
197
198 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, BASE_APK)).isEmpty();
199 assertThat(mDexUseManager.isPrimaryDexUsedByOtherApps(OWNING_PKG_NAME, BASE_APK)).isFalse();
200
201 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, SPLIT_APK))
202 .containsExactly(DexLoader.create(OWNING_PKG_NAME, true /* isolatedProcess */));
203 assertThat(mDexUseManager.isPrimaryDexUsedByOtherApps(OWNING_PKG_NAME, SPLIT_APK)).isTrue();
204 }
205
206 @Test
207 public void testPrimaryDexOthers() {
208 mDexUseManager.notifyDexContainersLoaded(
209 mSnapshot, LOADING_PKG_NAME, Map.of(BASE_APK, "CLC"));
210
211 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, BASE_APK))
212 .containsExactly(DexLoader.create(LOADING_PKG_NAME, false /* isolatedProcess */));
213 assertThat(mDexUseManager.isPrimaryDexUsedByOtherApps(OWNING_PKG_NAME, BASE_APK)).isTrue();
214
215 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, SPLIT_APK)).isEmpty();
216 assertThat(mDexUseManager.isPrimaryDexUsedByOtherApps(OWNING_PKG_NAME, SPLIT_APK))
217 .isFalse();
218 }
219
220 /** Checks that it ignores and dedups things correctly. */
221 @Test
222 public void testPrimaryDexMultipleEntries() throws Exception {
223 verifyPrimaryDexMultipleEntries(
224 false /* saveAndLoad */, false /* shutdown */, false /* cleanup */);
225 }
226
227 /** Checks that it saves data after some time has passed and loads data correctly. */
228 @Test
229 public void testPrimaryDexMultipleEntriesPersisted() throws Exception {
230 verifyPrimaryDexMultipleEntries(
231 true /*saveAndLoad */, false /* shutdown */, false /* cleanup */);
232 }
233
234 /** Checks that it saves data when the device is being shutdown and loads data correctly. */
235 @Test
236 public void testPrimaryDexMultipleEntriesPersistedDueToShutdown() throws Exception {
237 verifyPrimaryDexMultipleEntries(
238 true /*saveAndLoad */, true /* shutdown */, false /* cleanup */);
239 }
240
241 /** Checks that it doesn't accidentally cleanup any entry that is needed. */
242 @Test
243 public void testPrimaryDexMultipleEntriesSurviveCleanup() throws Exception {
244 verifyPrimaryDexMultipleEntries(
245 false /*saveAndLoad */, false /* shutdown */, true /* cleanup */);
246 }
247
248 private void verifyPrimaryDexMultipleEntries(
249 boolean saveAndLoad, boolean shutdown, boolean cleanup) throws Exception {
250 when(mInjector.getCurrentTimeMillis()).thenReturn(1000l);
251
252 lenient()
253 .when(mArtd.getDexFileVisibility(BASE_APK))
254 .thenReturn(FileVisibility.OTHER_READABLE);
255 lenient()
256 .when(mArtd.getDexFileVisibility(SPLIT_APK))
257 .thenReturn(FileVisibility.OTHER_READABLE);
258
259 // These should be ignored.
260 mDexUseManager.notifyDexContainersLoaded(
261 mSnapshot, Utils.PLATFORM_PACKAGE_NAME, Map.of(BASE_APK, "CLC"));
262 mDexUseManager.notifyDexContainersLoaded(mSnapshot, OWNING_PKG_NAME,
263 Map.of("/data/app/" + OWNING_PKG_NAME + "/non-existing.apk", "CLC"));
264
265 // Some of these should be deduped.
266 mDexUseManager.notifyDexContainersLoaded(
267 mSnapshot, OWNING_PKG_NAME, Map.of(BASE_APK, "CLC", SPLIT_APK, "CLC"));
268 mDexUseManager.notifyDexContainersLoaded(
269 mSnapshot, OWNING_PKG_NAME, Map.of(BASE_APK, "CLC", SPLIT_APK, "CLC"));
270
271 mDexUseManager.notifyDexContainersLoaded(
272 mSnapshot, LOADING_PKG_NAME, Map.of(BASE_APK, "CLC"));
273 mDexUseManager.notifyDexContainersLoaded(
274 mSnapshot, LOADING_PKG_NAME, Map.of(BASE_APK, "CLC"));
275
276 when(Process.isIsolatedUid(anyInt())).thenReturn(true);
277 mDexUseManager.notifyDexContainersLoaded(
278 mSnapshot, OWNING_PKG_NAME, Map.of(BASE_APK, "CLC"));
279 when(mInjector.getCurrentTimeMillis()).thenReturn(2000l);
280 mDexUseManager.notifyDexContainersLoaded(
281 mSnapshot, OWNING_PKG_NAME, Map.of(BASE_APK, "CLC"));
282
283 if (saveAndLoad) {
284 if (shutdown) {
285 mBroadcastReceiverCaptor.getValue().onReceive(mContext, mock(Intent.class));
286 } else {
287 // MockClock runs tasks synchronously.
288 mMockClock.advanceTime(DexUseManagerLocal.INTERVAL_MS);
289 }
290 mDexUseManager = new DexUseManagerLocal(mInjector);
291 }
292
293 if (cleanup) {
294 // Nothing should be cleaned up.
295 mDexUseManager.cleanup();
296 }
297
298 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, BASE_APK))
299 .containsExactly(DexLoader.create(OWNING_PKG_NAME, false /* isolatedProcess */),
300 DexLoader.create(OWNING_PKG_NAME, true /* isolatedProcess */),
301 DexLoader.create(LOADING_PKG_NAME, false /* isolatedProcess */));
302
303 assertThat(mDexUseManager.getPrimaryDexLoaders(OWNING_PKG_NAME, SPLIT_APK))
304 .containsExactly(DexLoader.create(OWNING_PKG_NAME, false /* isolatedProcess */));
305
306 assertThat(mDexUseManager.getPackageLastUsedAtMs(OWNING_PKG_NAME)).isEqualTo(2000l);
307 }
308
309 @Test
310 public void testSecondaryDexOwned() {
311 mDexUseManager.notifyDexContainersLoaded(
312 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
313
314 List<? extends SecondaryDexInfo> dexInfoList =
315 mDexUseManager.getSecondaryDexInfo(OWNING_PKG_NAME);
316 assertThat(dexInfoList)
317 .containsExactly(DetailedSecondaryDexInfo.create(mCeDir + "/foo.apk", mUserHandle,
318 "CLC", Set.of("arm64-v8a"),
319 Set.of(DexLoader.create(OWNING_PKG_NAME, false /* isolatedProcess */)),
320 false /* isUsedByOtherApps */, mDefaultIsDexFilePublic));
321 assertThat(dexInfoList.get(0).classLoaderContext()).isEqualTo("CLC");
322 }
323
324 @Test
325 public void testSecondaryDexOwnedIsolated() {
326 when(Process.isIsolatedUid(anyInt())).thenReturn(true);
327 mDexUseManager.notifyDexContainersLoaded(
328 mSnapshot, OWNING_PKG_NAME, Map.of(mDeDir + "/foo.apk", "CLC"));
329
330 List<? extends SecondaryDexInfo> dexInfoList =
331 mDexUseManager.getSecondaryDexInfo(OWNING_PKG_NAME);
332 assertThat(dexInfoList)
333 .containsExactly(DetailedSecondaryDexInfo.create(mDeDir + "/foo.apk", mUserHandle,
334 "CLC", Set.of("arm64-v8a"),
335 Set.of(DexLoader.create(OWNING_PKG_NAME, true /* isolatedProcess */)),
336 true /* isUsedByOtherApps */, mDefaultIsDexFilePublic));
337 assertThat(dexInfoList.get(0).classLoaderContext()).isEqualTo("CLC");
338 }
339
340 @Test
341 public void testSecondaryDexOthers() {
342 mDexUseManager.notifyDexContainersLoaded(
343 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
344
345 List<? extends SecondaryDexInfo> dexInfoList =
346 mDexUseManager.getSecondaryDexInfo(OWNING_PKG_NAME);
347 assertThat(dexInfoList)
348 .containsExactly(DetailedSecondaryDexInfo.create(mCeDir + "/foo.apk", mUserHandle,
349 "CLC", Set.of("armeabi-v7a"),
350 Set.of(DexLoader.create(LOADING_PKG_NAME, false /* isolatedProcess */)),
351 true /* isUsedByOtherApps */, mDefaultIsDexFilePublic));
352 assertThat(dexInfoList.get(0).classLoaderContext()).isEqualTo("CLC");
353 }
354
355 @Test
356 public void testSecondaryDexUnsupportedClc() {
357 mDexUseManager.notifyDexContainersLoaded(mSnapshot, LOADING_PKG_NAME,
358 Map.of(mCeDir + "/foo.apk", SecondaryDexInfo.UNSUPPORTED_CLASS_LOADER_CONTEXT));
359
360 List<? extends SecondaryDexInfo> dexInfoList =
361 mDexUseManager.getSecondaryDexInfo(OWNING_PKG_NAME);
362 assertThat(dexInfoList)
363 .containsExactly(DetailedSecondaryDexInfo.create(mCeDir + "/foo.apk", mUserHandle,
364 SecondaryDexInfo.UNSUPPORTED_CLASS_LOADER_CONTEXT, Set.of("armeabi-v7a"),
365 Set.of(DexLoader.create(LOADING_PKG_NAME, false /* isolatedProcess */)),
366 true /* isUsedByOtherApps */, mDefaultIsDexFilePublic));
367 assertThat(dexInfoList.get(0).classLoaderContext()).isNull();
368 }
369
370 @Test
371 public void testSecondaryDexVariableClc() {
372 mDexUseManager.notifyDexContainersLoaded(
373 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
374 mDexUseManager.notifyDexContainersLoaded(
375 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC2"));
376
377 List<? extends SecondaryDexInfo> dexInfoList =
378 mDexUseManager.getSecondaryDexInfo(OWNING_PKG_NAME);
379 assertThat(dexInfoList)
380 .containsExactly(DetailedSecondaryDexInfo.create(mCeDir + "/foo.apk", mUserHandle,
381 SecondaryDexInfo.VARYING_CLASS_LOADER_CONTEXTS,
382 Set.of("arm64-v8a", "armeabi-v7a"),
383 Set.of(DexLoader.create(OWNING_PKG_NAME, false /* isolatedProcess */),
384 DexLoader.create(LOADING_PKG_NAME, false /* isolatedProcess */)),
385 true /* isUsedByOtherApps */, mDefaultIsDexFilePublic));
386 assertThat(dexInfoList.get(0).classLoaderContext()).isNull();
387 }
388
389 /** Checks that it ignores and dedups things correctly. */
390 @Test
391 public void testSecondaryDexMultipleEntries() throws Exception {
392 verifySecondaryDexMultipleEntries(
393 false /*saveAndLoad */, false /* shutdown */, false /* cleanup */);
394 }
395
396 /** Checks that it saves data after some time has passed and loads data correctly. */
397 @Test
398 public void testSecondaryDexMultipleEntriesPersisted() throws Exception {
399 verifySecondaryDexMultipleEntries(
400 true /*saveAndLoad */, false /* shutdown */, false /* cleanup */);
401 }
402
403 /** Checks that it saves data when the device is being shutdown and loads data correctly. */
404 @Test
405 public void testSecondaryDexMultipleEntriesPersistedDueToShutdown() throws Exception {
406 verifySecondaryDexMultipleEntries(
407 true /*saveAndLoad */, true /* shutdown */, false /* cleanup */);
408 }
409
410 /** Checks that it doesn't accidentally cleanup any entry that is needed. */
411 @Test
412 public void testSecondaryDexMultipleEntriesSurviveCleanup() throws Exception {
413 verifySecondaryDexMultipleEntries(
414 false /*saveAndLoad */, false /* shutdown */, true /* cleanup */);
415 }
416
417 private void verifySecondaryDexMultipleEntries(
418 boolean saveAndLoad, boolean shutdown, boolean cleanup) throws Exception {
419 when(mInjector.getCurrentTimeMillis()).thenReturn(1000l);
420
421 lenient()
422 .when(mArtd.getDexFileVisibility(mCeDir + "/foo.apk"))
423 .thenReturn(FileVisibility.OTHER_READABLE);
424 lenient()
425 .when(mArtd.getDexFileVisibility(mCeDir + "/bar.apk"))
426 .thenReturn(FileVisibility.OTHER_READABLE);
427 lenient()
428 .when(mArtd.getDexFileVisibility(mCeDir + "/baz.apk"))
429 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
430
431 // These should be ignored.
432 mDexUseManager.notifyDexContainersLoaded(
433 mSnapshot, Utils.PLATFORM_PACKAGE_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
434 mDexUseManager.notifyDexContainersLoaded(
435 mSnapshot, OWNING_PKG_NAME, Map.of("/some/non-existing.apk", "CLC"));
436
437 // Some of these should be deduped.
438 mDexUseManager.notifyDexContainersLoaded(mSnapshot, OWNING_PKG_NAME,
439 Map.of(mCeDir + "/foo.apk", "CLC", mCeDir + "/bar.apk", "CLC"));
440 mDexUseManager.notifyDexContainersLoaded(mSnapshot, OWNING_PKG_NAME,
441 Map.of(mCeDir + "/foo.apk", "UpdatedCLC", mCeDir + "/bar.apk", "UpdatedCLC"));
442
443 mDexUseManager.notifyDexContainersLoaded(
444 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
445 mDexUseManager.notifyDexContainersLoaded(
446 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "UpdatedCLC"));
447
448 mDexUseManager.notifyDexContainersLoaded(
449 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/bar.apk", "DifferentCLC"));
450 mDexUseManager.notifyDexContainersLoaded(
451 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/bar.apk", "UpdatedDifferentCLC"));
452
453 mDexUseManager.notifyDexContainersLoaded(mSnapshot, OWNING_PKG_NAME,
454 Map.of(mCeDir + "/baz.apk", SecondaryDexInfo.UNSUPPORTED_CLASS_LOADER_CONTEXT));
455
456 when(Process.isIsolatedUid(anyInt())).thenReturn(true);
457 mDexUseManager.notifyDexContainersLoaded(
458 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
459 when(mInjector.getCurrentTimeMillis()).thenReturn(2000l);
460 mDexUseManager.notifyDexContainersLoaded(mSnapshot, OWNING_PKG_NAME,
461 Map.of(mCeDir + "/foo.apk", SecondaryDexInfo.UNSUPPORTED_CLASS_LOADER_CONTEXT));
462
463 if (saveAndLoad) {
464 if (shutdown) {
465 mBroadcastReceiverCaptor.getValue().onReceive(mContext, mock(Intent.class));
466 } else {
467 // MockClock runs tasks synchronously.
468 mMockClock.advanceTime(DexUseManagerLocal.INTERVAL_MS);
469 }
470 mDexUseManager = new DexUseManagerLocal(mInjector);
471 }
472
473 if (cleanup) {
474 // Nothing should be cleaned up.
475 mDexUseManager.cleanup();
476 }
477
478 List<? extends SecondaryDexInfo> dexInfoList =
479 mDexUseManager.getSecondaryDexInfo(OWNING_PKG_NAME);
480 assertThat(dexInfoList)
481 .containsExactly(DetailedSecondaryDexInfo.create(mCeDir + "/foo.apk", mUserHandle,
482 "UpdatedCLC", Set.of("arm64-v8a", "armeabi-v7a"),
483 Set.of(DexLoader.create(OWNING_PKG_NAME,
484 false /* isolatedProcess */),
485 DexLoader.create(OWNING_PKG_NAME,
486 true /* isolatedProcess */),
487 DexLoader.create(LOADING_PKG_NAME,
488 false /* isolatedProcess */)),
489 true /* isUsedByOtherApps */, mDefaultIsDexFilePublic),
490 DetailedSecondaryDexInfo.create(mCeDir + "/bar.apk", mUserHandle,
491 SecondaryDexInfo.VARYING_CLASS_LOADER_CONTEXTS,
492 Set.of("arm64-v8a", "armeabi-v7a"),
493 Set.of(DexLoader.create(
494 OWNING_PKG_NAME, false /* isolatedProcess */),
495 DexLoader.create(
496 LOADING_PKG_NAME, false /* isolatedProcess */)),
497 true /* isUsedByOtherApps */, mDefaultIsDexFilePublic),
498 DetailedSecondaryDexInfo.create(mCeDir + "/baz.apk", mUserHandle,
499 SecondaryDexInfo.UNSUPPORTED_CLASS_LOADER_CONTEXT,
500 Set.of("arm64-v8a"),
501 Set.of(DexLoader.create(
502 OWNING_PKG_NAME, false /* isolatedProcess */)),
503 false /* isUsedByOtherApps */, mDefaultIsDexFilePublic));
504
505 assertThat(mDexUseManager.getSecondaryDexContainerFileUseInfo(OWNING_PKG_NAME))
506 .containsExactly(DexContainerFileUseInfo.create(mCeDir + "/foo.apk", mUserHandle,
507 Set.of(OWNING_PKG_NAME, LOADING_PKG_NAME)),
508 DexContainerFileUseInfo.create(mCeDir + "/bar.apk", mUserHandle,
509 Set.of(OWNING_PKG_NAME, LOADING_PKG_NAME)),
510 DexContainerFileUseInfo.create(
511 mCeDir + "/baz.apk", mUserHandle, Set.of(OWNING_PKG_NAME)));
512
513 assertThat(mDexUseManager.getPackageLastUsedAtMs(OWNING_PKG_NAME)).isEqualTo(2000l);
514 }
515
516 @Test
517 public void testFilteredDetailedSecondaryDexPublic() throws Exception {
518 when(mArtd.getDexFileVisibility(mCeDir + "/foo.apk"))
519 .thenReturn(FileVisibility.OTHER_READABLE);
520
521 mDexUseManager.notifyDexContainersLoaded(
522 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
523 mDexUseManager.notifyDexContainersLoaded(
524 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
525
526 assertThat(mDexUseManager.getFilteredDetailedSecondaryDexInfo(OWNING_PKG_NAME))
527 .containsExactly(DetailedSecondaryDexInfo.create(mCeDir + "/foo.apk", mUserHandle,
528 "CLC", Set.of("arm64-v8a", "armeabi-v7a"),
529 Set.of(DexLoader.create(OWNING_PKG_NAME, false /* isolatedProcess */),
530 DexLoader.create(LOADING_PKG_NAME, false /* isolatedProcess */)),
531 true /* isUsedByOtherApps */, true /* isDexFilePublic */));
532 }
533
534 @Test
535 public void testFilteredDetailedSecondaryDexPrivate() throws Exception {
536 when(mArtd.getDexFileVisibility(mCeDir + "/foo.apk"))
537 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
538
539 mDexUseManager.notifyDexContainersLoaded(
540 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
541 mDexUseManager.notifyDexContainersLoaded(
542 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
543
544 when(Process.isIsolatedUid(anyInt())).thenReturn(true);
545 mDexUseManager.notifyDexContainersLoaded(
546 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
547
548 assertThat(mDexUseManager.getFilteredDetailedSecondaryDexInfo(OWNING_PKG_NAME))
549 .containsExactly(DetailedSecondaryDexInfo.create(mCeDir + "/foo.apk", mUserHandle,
550 "CLC", Set.of("arm64-v8a"),
551 Set.of(DexLoader.create(OWNING_PKG_NAME, false /* isolatedProcess */)),
552 false /* isUsedByOtherApps */, false /* isDexFilePublic */));
553 }
554
555 @Test
556 public void testFilteredDetailedSecondaryDexFilteredDueToVisibility() throws Exception {
557 when(mArtd.getDexFileVisibility(mCeDir + "/foo.apk"))
558 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
559
560 mDexUseManager.notifyDexContainersLoaded(
561 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
562
563 when(Process.isIsolatedUid(anyInt())).thenReturn(true);
564 mDexUseManager.notifyDexContainersLoaded(
565 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
566
567 assertThat(mDexUseManager.getFilteredDetailedSecondaryDexInfo(OWNING_PKG_NAME)).isEmpty();
568 }
569
570 @Test
571 public void testFilteredDetailedSecondaryDexFilteredDueToNotFound() throws Exception {
572 when(mArtd.getDexFileVisibility(mCeDir + "/foo.apk")).thenReturn(FileVisibility.NOT_FOUND);
573
574 mDexUseManager.notifyDexContainersLoaded(
575 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
576
577 assertThat(mDexUseManager.getFilteredDetailedSecondaryDexInfo(OWNING_PKG_NAME)).isEmpty();
578 }
579
580 @Test
581 public void testCleanup() throws Exception {
582 PackageState pkgState = createPackageState("com.example.deletedpackage", "arm64-v8a");
583 addPackage("com.example.deletedpackage", pkgState);
584 lenient()
585 .when(mArtd.getDexFileVisibility("/data/app/com.example.deletedpackage/base.apk"))
586 .thenReturn(FileVisibility.OTHER_READABLE);
587 lenient()
588 .when(mArtd.getDexFileVisibility(BASE_APK))
589 .thenReturn(FileVisibility.OTHER_READABLE);
590 // Simulate that a package loads its own dex file and another package's dex file.
591 mDexUseManager.notifyDexContainersLoaded(mSnapshot, "com.example.deletedpackage",
592 Map.of("/data/app/com.example.deletedpackage/base.apk", "CLC", BASE_APK, "CLC"));
593 // Simulate that another package loads this package's dex file.
594 mDexUseManager.notifyDexContainersLoaded(mSnapshot, LOADING_PKG_NAME,
595 Map.of("/data/app/com.example.deletedpackage/base.apk", "CLC"));
596 // Simulate that the package is then deleted.
597 removePackage("com.example.deletedpackage");
598
599 // Simulate that a primary dex file is loaded and then deleted.
600 lenient()
601 .when(mArtd.getDexFileVisibility(SPLIT_APK))
602 .thenReturn(FileVisibility.OTHER_READABLE);
603 mDexUseManager.notifyDexContainersLoaded(
604 mSnapshot, OWNING_PKG_NAME, Map.of(SPLIT_APK, "CLC"));
605 mDexUseManager.notifyDexContainersLoaded(
606 mSnapshot, LOADING_PKG_NAME, Map.of(SPLIT_APK, "CLC"));
607 lenient().when(mArtd.getDexFileVisibility(SPLIT_APK)).thenReturn(FileVisibility.NOT_FOUND);
608
609 // Simulate that a secondary dex file is loaded and then deleted.
610 lenient()
611 .when(mArtd.getDexFileVisibility(mCeDir + "/foo.apk"))
612 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
613 mDexUseManager.notifyDexContainersLoaded(
614 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
615 mDexUseManager.notifyDexContainersLoaded(
616 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
617 lenient()
618 .when(mArtd.getDexFileVisibility(mCeDir + "/foo.apk"))
619 .thenReturn(FileVisibility.NOT_FOUND);
620
621 // Create an entry that should be kept.
622 lenient()
623 .when(mArtd.getDexFileVisibility(mCeDir + "/bar.apk"))
624 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
625 mDexUseManager.notifyDexContainersLoaded(
626 mSnapshot, OWNING_PKG_NAME, Map.of(mCeDir + "/bar.apk", "CLC"));
627
628 // Simulate that a secondary dex file is loaded by another package and then made private.
629 lenient()
630 .when(mArtd.getDexFileVisibility(mCeDir + "/baz.apk"))
631 .thenReturn(FileVisibility.OTHER_READABLE);
632 mDexUseManager.notifyDexContainersLoaded(
633 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/baz.apk", "CLC"));
634 lenient()
635 .when(mArtd.getDexFileVisibility(mCeDir + "/baz.apk"))
636 .thenReturn(FileVisibility.NOT_OTHER_READABLE);
637
638 // Simulate that all the files of a package are deleted. The whole container entry of the
639 // package should be cleaned up, though the package still exists.
640 lenient()
641 .when(mArtd.getDexFileVisibility("/data/app/" + LOADING_PKG_NAME + "/base.apk"))
642 .thenReturn(FileVisibility.OTHER_READABLE);
643 mDexUseManager.notifyDexContainersLoaded(mSnapshot, LOADING_PKG_NAME,
644 Map.of("/data/app/" + LOADING_PKG_NAME + "/base.apk", "CLC"));
645 lenient()
646 .when(mArtd.getDexFileVisibility("/data/app/" + LOADING_PKG_NAME + "/base.apk"))
647 .thenReturn(FileVisibility.NOT_FOUND);
648
649 // Run cleanup.
650 mDexUseManager.cleanup();
651
652 // Save.
653 mMockClock.advanceTime(DexUseManagerLocal.INTERVAL_MS);
654
655 // Check that the entries are removed from the proto. Normally, we should check the return
656 // values of the public get methods instead of checking the raw proto. However, here we want
657 // to make sure that the container entries are cleaned up when they are empty so that they
658 // don't cost extra memory or storage.
659 // Note that every repeated field must not contain more than one entry, to keep the
660 // textproto deterministic.
661 DexUseProto proto;
662 try (InputStream in = new FileInputStream(mTempFile.getPath())) {
663 proto = DexUseProto.parseFrom(in);
664 }
665 String textproto = proto.toString();
666 // Remove the first line, which is an auto-generated comment.
667 textproto = textproto.substring(textproto.indexOf('\n') + 1).trim();
668 assertThat(textproto).isEqualTo("package_dex_use {\n"
669 + " owning_package_name: \"com.example.owningpackage\"\n"
670 + " secondary_dex_use {\n"
671 + " dex_file: \"/data/user/0/com.example.owningpackage/bar.apk\"\n"
672 + " record {\n"
673 + " abi_name: \"arm64-v8a\"\n"
674 + " class_loader_context: \"CLC\"\n"
675 + " last_used_at_ms: 0\n"
676 + " loading_package_name: \"com.example.owningpackage\"\n"
677 + " }\n"
678 + " user_id {\n"
679 + " }\n"
680 + " }\n"
681 + "}");
682 }
683
684 @Test(expected = IllegalArgumentException.class)
685 public void testUnknownPackage() {
686 mDexUseManager.notifyDexContainersLoaded(mSnapshot, "bogus", Map.of(BASE_APK, "CLC"));
687 }
688
689 @Test(expected = IllegalArgumentException.class)
690 public void testEmptyMap() {
691 mDexUseManager.notifyDexContainersLoaded(mSnapshot, OWNING_PKG_NAME, Map.of());
692 }
693
694 @Test(expected = IllegalArgumentException.class)
695 public void testNullKey() {
696 var map = new HashMap<String, String>();
697 map.put(null, "CLC");
698 mDexUseManager.notifyDexContainersLoaded(mSnapshot, OWNING_PKG_NAME, map);
699 }
700
701 @Test(expected = IllegalArgumentException.class)
702 public void testNonAbsoluteKey() {
703 mDexUseManager.notifyDexContainersLoaded(
704 mSnapshot, OWNING_PKG_NAME, Map.of("a/b.jar", "CLC"));
705 }
706
707 @Test(expected = IllegalArgumentException.class)
708 public void testNullValue() {
709 var map = new HashMap<String, String>();
710 map.put(mCeDir + "/foo.apk", null);
711 mDexUseManager.notifyDexContainersLoaded(mSnapshot, OWNING_PKG_NAME, map);
712 }
713
714 @Test
715 public void testFileNotFound() {
716 // It should fail to load the file.
717 when(mInjector.getFilename()).thenReturn("/nonexisting/file");
718 mDexUseManager = new DexUseManagerLocal(mInjector);
719
720 // Add some arbitrary data to see if it works fine after a failed load.
721 mDexUseManager.notifyDexContainersLoaded(
722 mSnapshot, LOADING_PKG_NAME, Map.of(mCeDir + "/foo.apk", "CLC"));
723
724 assertThat(mDexUseManager.getSecondaryDexInfo(OWNING_PKG_NAME))
725 .containsExactly(DetailedSecondaryDexInfo.create(mCeDir + "/foo.apk", mUserHandle,
726 "CLC", Set.of("armeabi-v7a"),
727 Set.of(DexLoader.create(LOADING_PKG_NAME, false /* isolatedProcess */)),
728 true /* isUsedByOtherApps */, mDefaultIsDexFilePublic));
729 }
730
731 private AndroidPackage createPackage(String packageName) {
732 AndroidPackage pkg = mock(AndroidPackage.class);
733 lenient().when(pkg.getStorageUuid()).thenReturn(StorageManager.UUID_DEFAULT);
734
735 var baseSplit = mock(AndroidPackageSplit.class);
736 lenient().when(baseSplit.getPath()).thenReturn("/data/app/" + packageName + "/base.apk");
737 lenient().when(baseSplit.isHasCode()).thenReturn(true);
738 lenient().when(baseSplit.getClassLoaderName()).thenReturn(PathClassLoader.class.getName());
739
740 var split0 = mock(AndroidPackageSplit.class);
741 lenient().when(split0.getName()).thenReturn("split_0");
742 lenient().when(split0.getPath()).thenReturn("/data/app/" + packageName + "/split_0.apk");
743 lenient().when(split0.isHasCode()).thenReturn(true);
744
745 lenient().when(pkg.getSplits()).thenReturn(List.of(baseSplit, split0));
746
747 return pkg;
748 }
749
750 private PackageState createPackageState(String packageName, String primaryAbi) {
751 PackageState pkgState = mock(PackageState.class);
752 lenient().when(pkgState.getPackageName()).thenReturn(packageName);
753 AndroidPackage pkg = createPackage(packageName);
754 lenient().when(pkgState.getAndroidPackage()).thenReturn(pkg);
755 lenient().when(pkgState.getPrimaryCpuAbi()).thenReturn(primaryAbi);
756 return pkgState;
757 }
758
759 private void addPackage(String packageName, PackageState pkgState) {
760 lenient().when(mSnapshot.getPackageState(packageName)).thenReturn(pkgState);
761 mPackageStates.put(packageName, pkgState);
762 }
763
764 private void removePackage(String packageName) {
765 lenient().when(mSnapshot.getPackageState(packageName)).thenReturn(null);
766 mPackageStates.remove(packageName);
767 }
768 }