1 /*
<lambda>null2  * Copyright (C) 2023 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.permission.access.appop
18 
19 import android.os.Process
20 import android.util.Slog
21 import com.android.server.LocalServices
22 import com.android.server.appop.AppOpMigrationHelper
23 import com.android.server.permission.access.MutableAccessState
24 import com.android.server.permission.access.immutable.* // ktlint-disable no-wildcard-imports
25 import com.android.server.permission.access.util.PackageVersionMigration
26 
27 class AppIdAppOpMigration {
28     fun migrateUserState(state: MutableAccessState, userId: Int) {
29         val legacyAppOpsManager = LocalServices.getService(AppOpMigrationHelper::class.java)!!
30         if (!legacyAppOpsManager.hasLegacyAppOpState()) {
31             return
32         }
33 
34         val legacyAppIdAppOpModes = legacyAppOpsManager.getLegacyAppIdAppOpModes(userId)
35         val version = PackageVersionMigration.getVersion(userId)
36 
37         val userState = state.mutateUserState(userId)!!
38         val appIdAppOpModes = userState.mutateAppIdAppOpModes()
39         legacyAppIdAppOpModes.forEach { (appId, legacyAppOpModes) ->
40             val packageNames = state.externalState.appIdPackageNames[appId]
41             // Non-application UIDs may not have an Android package but may still have app op state.
42             if (packageNames == null && appId >= Process.FIRST_APPLICATION_UID) {
43                 Slog.w(LOG_TAG, "Dropping unknown app ID $appId when migrating app op state")
44                 return@forEach
45             }
46 
47             val appOpModes = MutableIndexedMap<String, Int>()
48             appIdAppOpModes[appId] = appOpModes
49             legacyAppOpModes.forEach { (appOpName, appOpMode) -> appOpModes[appOpName] = appOpMode }
50 
51             if (packageNames != null) {
52                 val packageVersions = userState.mutatePackageVersions()
53                 packageNames.forEachIndexed { _, packageName ->
54                     packageVersions[packageName] = version
55                 }
56             }
57         }
58     }
59 
60     companion object {
61         private val LOG_TAG = AppIdAppOpMigration::class.java.simpleName
62     }
63 }
64