forked from ThePedroo/ReLSPosed
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPackageService.java
More file actions
393 lines (352 loc) · 17.3 KB
/
PackageService.java
File metadata and controls
393 lines (352 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
* This file is part of LSPosed.
*
* LSPosed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LSPosed is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LSPosed. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright (C) 2021 LSPosed Contributors
*/
package org.lsposed.lspd.service;
import static android.content.pm.ServiceInfo.FLAG_ISOLATED_PROCESS;
import static org.lsposed.lspd.service.ServiceManager.TAG;
import static org.lsposed.lspd.service.ServiceManager.existsInGlobalNamespace;
import android.content.IIntentReceiver;
import android.content.IIntentSender;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.ApplicationInfo;
import android.content.pm.ComponentInfo;
import android.content.pm.IPackageManager;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.content.pm.ParceledListSlice;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.content.pm.VersionedPackage;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.util.Log;
import android.util.Pair;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.lsposed.lspd.models.Application;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;
import rikka.parcelablelist.ParcelableListSlice;
public class PackageService {
static final int INSTALL_FAILED_INTERNAL_ERROR = -110;
static final int INSTALL_REASON_UNKNOWN = 0;
static final int MATCH_ANY_USER = 0x00400000; // PackageManager.MATCH_ANY_USER
static final int MATCH_ALL_FLAGS = PackageManager.MATCH_DISABLED_COMPONENTS | PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE | PackageManager.MATCH_UNINSTALLED_PACKAGES | MATCH_ANY_USER;
public static final int PER_USER_RANGE = 100000;
private static IPackageManager pm = null;
private static IBinder binder = null;
static boolean isAlive() {
var pm = getPackageManager();
return pm != null && pm.asBinder().isBinderAlive();
}
private static final IBinder.DeathRecipient recipient = new IBinder.DeathRecipient() {
@Override
public void binderDied() {
Log.w(TAG, "pm is dead");
binder.unlinkToDeath(this, 0);
binder = null;
pm = null;
}
};
private static IPackageManager getPackageManager() {
if (binder == null || pm == null) {
binder = ServiceManager.getService("package");
if (binder == null) return null;
try {
binder.linkToDeath(recipient, 0);
} catch (RemoteException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
pm = IPackageManager.Stub.asInterface(binder);
}
return pm;
}
@Nullable
public static PackageInfo getPackageInfo(String packageName, int flags, int userId) throws RemoteException {
IPackageManager pm = getPackageManager();
if (pm == null) return null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return pm.getPackageInfo(packageName, (long) flags, userId);
}
return pm.getPackageInfo(packageName, flags, userId);
}
public static @NonNull
Map<Integer, PackageInfo> getPackageInfoFromAllUsers(String packageName, int flags) throws RemoteException {
IPackageManager pm = getPackageManager();
Map<Integer, PackageInfo> res = new HashMap<>();
if (pm == null) return res;
for (var user : UserService.getUsers()) {
var info = getPackageInfo(packageName, flags, user.id);
if (info != null && info.applicationInfo != null) res.put(user.id, info);
}
return res;
}
@Nullable
public static ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) throws RemoteException {
IPackageManager pm = getPackageManager();
if (pm == null) return null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
return pm.getApplicationInfo(packageName, (long) flags, userId);
}
return pm.getApplicationInfo(packageName, flags, userId);
}
// Only for manager
public static ParcelableListSlice<PackageInfo> getInstalledPackagesFromAllUsers(int flags, boolean filterNoProcess) throws RemoteException {
List<PackageInfo> res = new ArrayList<>();
IPackageManager pm = getPackageManager();
if (pm == null) return ParcelableListSlice.emptyList();
for (var user : UserService.getUsers()) {
// in case pkginfo of other users in primary user
ParceledListSlice<PackageInfo> infos;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
infos = pm.getInstalledPackages((long) flags, user.id);
} else {
infos = pm.getInstalledPackages(flags, user.id);
}
res.addAll(infos
.getList().parallelStream()
.filter(info -> info.applicationInfo != null && info.applicationInfo.uid / PER_USER_RANGE == user.id)
.filter(info -> {
try {
return isPackageAvailable(info.packageName, user.id, true);
} catch (RemoteException e) {
return false;
}
})
.collect(Collectors.toList()));
}
if (filterNoProcess) {
return new ParcelableListSlice<>(res.parallelStream().filter(packageInfo -> {
try {
PackageInfo pkgInfo = getPackageInfoWithComponents(packageInfo.packageName, MATCH_ALL_FLAGS, packageInfo.applicationInfo.uid / PER_USER_RANGE);
return !fetchProcesses(pkgInfo).isEmpty();
} catch (RemoteException e) {
Log.w(TAG, "filter failed", e);
return true;
}
}).collect(Collectors.toList()));
}
return new ParcelableListSlice<>(res);
}
private static Set<String> fetchProcesses(PackageInfo pkgInfo) {
HashSet<String> processNames = new HashSet<>();
if (pkgInfo == null) return processNames;
for (ComponentInfo[] componentInfos : new ComponentInfo[][]{pkgInfo.activities, pkgInfo.receivers, pkgInfo.providers}) {
if (componentInfos == null) continue;
for (ComponentInfo componentInfo : componentInfos) {
processNames.add(componentInfo.processName);
}
}
if (pkgInfo.services == null) return processNames;
for (ServiceInfo service : pkgInfo.services) {
if ((service.flags & FLAG_ISOLATED_PROCESS) == 0) {
processNames.add(service.processName);
}
}
return processNames;
}
public static Pair<Set<String>, Integer> fetchProcessesWithUid(Application app) throws RemoteException {
IPackageManager pm = getPackageManager();
if (pm == null) return new Pair<>(Collections.emptySet(), -1);
PackageInfo pkgInfo = getPackageInfoWithComponents(app.packageName, MATCH_ALL_FLAGS, app.userId);
if (pkgInfo == null || pkgInfo.applicationInfo == null)
return new Pair<>(Collections.emptySet(), -1);
return new Pair<>(fetchProcesses(pkgInfo), pkgInfo.applicationInfo.uid);
}
public static boolean isPackageAvailable(String packageName, int userId, boolean ignoreHidden) throws RemoteException {
return pm.isPackageAvailable(packageName, userId) || (ignoreHidden && pm.getApplicationHiddenSettingAsUser(packageName, userId));
}
@SuppressWarnings({"ConstantConditions", "SameParameterValue"})
@Nullable
private static PackageInfo getPackageInfoWithComponents(String packageName, int flags, int userId) throws RemoteException {
IPackageManager pm = getPackageManager();
if (pm == null) return null;
PackageInfo pkgInfo;
try {
pkgInfo = getPackageInfo(packageName, flags | PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES | PackageManager.GET_RECEIVERS | PackageManager.GET_PROVIDERS, userId);
} catch (Exception e) {
pkgInfo = getPackageInfo(packageName, flags, userId);
if (pkgInfo == null) return null;
try {
pkgInfo.activities = getPackageInfo(packageName, flags | PackageManager.GET_ACTIVITIES, userId).activities;
} catch (Exception ignored) {
}
try {
pkgInfo.services = getPackageInfo(packageName, flags | PackageManager.GET_SERVICES, userId).services;
} catch (Exception ignored) {
}
try {
pkgInfo.receivers = getPackageInfo(packageName, flags | PackageManager.GET_RECEIVERS, userId).receivers;
} catch (Exception ignored) {
}
try {
pkgInfo.providers = getPackageInfo(packageName, flags | PackageManager.GET_PROVIDERS, userId).providers;
} catch (Exception ignored) {
}
}
if (pkgInfo == null || pkgInfo.applicationInfo == null || (!pkgInfo.packageName.equals("android") && (pkgInfo.applicationInfo.sourceDir == null || !existsInGlobalNamespace(pkgInfo.applicationInfo.sourceDir) || !isPackageAvailable(packageName, userId, true))))
return null;
return pkgInfo;
}
static abstract class IntentSenderAdaptor extends IIntentSender.Stub {
public abstract void send(Intent intent);
@Override
public int send(int code, Intent intent, String resolvedType, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
send(intent);
return 0;
}
@Override
public void send(int code, Intent intent, String resolvedType, IBinder whitelistToken, IIntentReceiver finishedReceiver, String requiredPermission, Bundle options) {
send(intent);
}
public IntentSender getIntentSender() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
@SuppressWarnings("JavaReflectionMemberAccess")
Constructor<IntentSender> intentSenderConstructor = IntentSender.class.getConstructor(IIntentSender.class);
intentSenderConstructor.setAccessible(true);
return intentSenderConstructor.newInstance(this);
}
}
public static boolean uninstallPackage(VersionedPackage versionedPackage, int userId) throws RemoteException, InterruptedException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
CountDownLatch latch = new CountDownLatch(1);
final boolean[] result = {false};
var flag = userId == -1 ? 0x00000002 : 0; //PackageManager.DELETE_ALL_USERS = 0x00000002; UserHandle ALL = new UserHandle(-1);
pm.getPackageInstaller().uninstall(versionedPackage, "android", flag, new IntentSenderAdaptor() {
@Override
public void send(Intent intent) {
int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE);
result[0] = status == PackageInstaller.STATUS_SUCCESS;
Log.d(TAG, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE));
latch.countDown();
}
}.getIntentSender(), userId == -1 ? 0 : userId);
latch.await();
return result[0];
}
public static int installExistingPackageAsUser(String packageName, int userId) throws RemoteException {
IPackageManager pm = getPackageManager();
Log.d(TAG, "about to install existing package " + packageName + "/" + userId);
if (pm == null) return INSTALL_FAILED_INTERNAL_ERROR;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
return pm.installExistingPackageAsUser(packageName, userId, 0, INSTALL_REASON_UNKNOWN, null);
} else {
return pm.installExistingPackageAsUser(packageName, userId, 0, INSTALL_REASON_UNKNOWN);
}
}
@Nullable
public static ParcelableListSlice<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, int flags, int userId) {
try {
IPackageManager pm = getPackageManager();
if (pm == null) return null;
ParceledListSlice<ResolveInfo> infos;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
infos = pm.queryIntentActivities(intent, resolvedType, (long) flags, userId);
} else {
infos = pm.queryIntentActivities(intent, resolvedType, flags, userId);
}
return new ParcelableListSlice<>(infos.getList());
} catch (Exception e) {
Log.e(TAG, "queryIntentActivities", e);
return new ParcelableListSlice<>(new ArrayList<>());
}
}
@Nullable
public static Intent getLaunchIntentForPackage(String packageName) throws RemoteException {
Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
intentToResolve.addCategory(Intent.CATEGORY_INFO);
intentToResolve.setPackage(packageName);
var ris = queryIntentActivities(intentToResolve, intentToResolve.getType(), 0, 0);
// Otherwise, try to find a main launcher activity.
if (ris == null || ris.getList().size() == 0) {
// reuse the intent instance
intentToResolve.removeCategory(Intent.CATEGORY_INFO);
intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
intentToResolve.setPackage(packageName);
ris = queryIntentActivities(intentToResolve, intentToResolve.getType(), 0, 0);
}
if (ris == null || ris.getList().size() == 0) {
return null;
}
Intent intent = new Intent(intentToResolve);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(ris.getList().get(0).activityInfo.packageName,
ris.getList().get(0).activityInfo.name);
return intent;
}
public static void clearApplicationProfileData(String packageName) throws RemoteException {
IPackageManager pm = getPackageManager();
if (pm == null) return;
pm.clearApplicationProfileData(packageName);
}
public static boolean performDexOptMode(String packageName) throws RemoteException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
Process process = null;
try {
// The 'speed-profile' filter is a balanced choice for performance.
String command = "cmd package compile -m speed-profile -f " + packageName;
process = Runtime.getRuntime().exec(command);
// Capture and log the output for debugging.
StringBuilder output = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
int exitCode = process.waitFor();
Log.i(TAG, "Dexopt command finished for " + packageName + " with exit code: " + exitCode);
// A successful command returns exit code 0 and typically "Success" in its output.
return exitCode == 0 && output.toString().contains("Success");
} catch (Exception e) {
Log.e(TAG, "Failed to execute dexopt shell command for " + packageName, e);
if (e instanceof InterruptedException) {
// Preserve the interrupted status.
Thread.currentThread().interrupt();
}
return false;
} finally {
if (process != null) {
process.destroy();
}
}
} else {
// Fallback to the original reflection method for older Android versions.
IPackageManager pm = getPackageManager();
if (pm == null) return false;
return pm.performDexOptMode(packageName,
SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false),
SystemProperties.get("pm.dexopt.install", "speed-profile"), true, true, null);
}
}
}