-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathActivityReceiver.java
394 lines (358 loc) · 15.3 KB
/
ActivityReceiver.java
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
394
package me.piebridge.prevent.framework;
import android.app.INotificationManager;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.RemoteException;
import android.os.ServiceManager;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import me.piebridge.prevent.common.Configuration;
import me.piebridge.prevent.common.TimeUtils;
import me.piebridge.prevent.framework.util.ActivityRecordUtils;
import me.piebridge.prevent.framework.util.HideApiUtils;
import me.piebridge.prevent.framework.util.LogUtils;
import me.piebridge.prevent.framework.util.ProcessRecordUtils;
abstract class ActivityReceiver extends BroadcastReceiver {
protected Context mContext;
protected Map<String, Boolean> mPreventPackages;
private boolean screen = false;
private Map<String, Integer> packageUids = new HashMap<String, Integer>();
private Map<String, Set<String>> abnormalProcesses = new ConcurrentHashMap<String, Set<String>>();
private Map<String, Map<Integer, AtomicInteger>> packageCounters = new ConcurrentHashMap<String, Map<Integer, AtomicInteger>>();
private Map<String, Long> leavingPackages = new ConcurrentHashMap<String, Long>();
private Set<String> checkLeavingNext = new TreeSet<String>();
private ScheduledFuture<?> leavingFuture;
private ScheduledThreadPoolExecutor singleExecutor = new ScheduledThreadPoolExecutor(0x2);
public ActivityReceiver(Context context, Map<String, Boolean> preventPackages) {
mContext = context;
mPreventPackages = preventPackages;
}
protected int countCounter(String packageName) {
return countCounter(-1, packageName);
}
private int countCounter(int currentPid, String packageName) {
int count = 0;
Map<Integer, AtomicInteger> values = packageCounters.get(packageName);
if (values == null) {
return count;
}
Iterator<Map.Entry<Integer, AtomicInteger>> iterator = values.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, AtomicInteger> entry = iterator.next();
int pid = entry.getKey();
if (pid == currentPid || checkPid(pid, packageName)) {
count += entry.getValue().get();
} else {
LogUtils.logIgnore(entry.getKey(), packageName);
iterator.remove();
}
}
return count;
}
private boolean checkPid(int pid, String packageName) {
Integer uid = packageUids.get(packageName);
if (uid == null) {
return false;
}
try {
if (HideApiUtils.getUidForPid(pid) != uid) {
return false;
}
} catch (Throwable t) { // NOSONAR
PreventLog.e("cannot get uid for " + pid, t);
}
String processName = getProcessName(uid, pid, packageName);
if (isNormalProcessName(processName, packageName)) {
return true;
}
PreventLog.v("pid: " + pid + ", package: " + packageName + ", process: " + processName);
Set<String> abnormalPackages = abnormalProcesses.get(processName);
return abnormalPackages != null && abnormalPackages.contains(packageName);
}
private String getProcessName(int uid, int pid, String packageName) {
String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
if (packages != null && packages.length == 1) {
return packageName;
} else {
return SystemHook.getProcessName(pid);
}
}
private boolean isNormalProcessName(String processName, String packageName) {
return (processName != null) && (processName.equals(packageName)
|| processName.startsWith(packageName + ":")
|| "<pre-initialized>".equals(processName));
}
private void setAbnormalProcessIfNeeded(String processName, String packageName) {
if (!isNormalProcessName(processName, packageName)) {
Set<String> abnormalProcess = abnormalProcesses.get(processName);
if (abnormalProcess == null) {
abnormalProcess = new HashSet<String>();
abnormalProcesses.put(processName, abnormalProcess);
}
if (abnormalProcess.add(packageName)) {
PreventLog.d("package " + packageName + " has abnormal process: " + processName);
}
}
}
public void onLaunchActivity(Object activityRecord) {
String packageName = ActivityRecordUtils.getPackageName(activityRecord);
if (packageName == null) {
return;
}
SystemHook.cancelCheck(packageName);
SystemHook.updateRunningGapps(packageName, true);
if (mPreventPackages.containsKey(packageName)) {
mPreventPackages.put(packageName, false);
}
int pid = ActivityRecordUtils.getPid(activityRecord);
int uid = ActivityRecordUtils.getUid(activityRecord);
String processName = ActivityRecordUtils.getInfo(activityRecord).processName;
setAbnormalProcessIfNeeded(processName, packageName);
if (uid > 0) {
packageUids.put(packageName, uid);
}
Map<Integer, AtomicInteger> packageCounter = packageCounters.get(packageName);
if (packageCounter == null) {
packageCounter = new LinkedHashMap<Integer, AtomicInteger>();
packageCounters.put(packageName, packageCounter);
}
AtomicInteger pidCounter = packageCounter.get(pid);
if (pidCounter == null) {
pidCounter = new AtomicInteger();
packageCounter.put(pid, pidCounter);
}
pidCounter.incrementAndGet();
int count = countCounter(pid, packageName);
if (count == 1) {
SystemHook.checkSync(packageName);
}
LogUtils.logActivity("start activity", packageName, count);
removeLeaving(packageName);
}
public boolean onDestroyActivity(Object activityRecord) {
String packageName = ActivityRecordUtils.getPackageName(activityRecord);
if (packageName == null) {
return false;
}
Map<Integer, AtomicInteger> packageCounter = packageCounters.get(packageName);
if (packageCounter != null) {
int pid = ActivityRecordUtils.getPid(activityRecord);
AtomicInteger pidCounter = packageCounter.get(pid);
if (pidCounter != null) {
pidCounter.decrementAndGet();
}
}
int count = countCounter(packageName);
LogUtils.logActivity("destroy activity", packageName, count);
if (count > 0) {
return false;
}
SystemHook.updateRunningGapps(packageName, false);
if (mPreventPackages.containsKey(packageName)) {
mPreventPackages.put(packageName, true);
LogUtils.logForceStop("destroy activity", packageName, "if needed in " + SystemHook.TIME_DESTROY + "s");
SystemHook.checkRunningServices(packageName, SystemHook.TIME_DESTROY);
} else {
SystemHook.checkRunningServices(null, SystemHook.TIME_DESTROY);
}
SystemHook.killNoFather();
return true;
}
public void onDestroyActivity(String reason, String packageName) {
SystemHook.updateRunningGapps(packageName, false);
if (mPreventPackages.containsKey(packageName)) {
mPreventPackages.put(packageName, true);
LogUtils.logForceStop(reason, packageName, "destroy in " + SystemHook.TIME_SUICIDE + "s");
SystemHook.checkRunningServices(packageName, SystemHook.TIME_SUICIDE);
} else {
SystemHook.checkRunningServices(null, SystemHook.TIME_SUICIDE < SystemHook.TIME_DESTROY ? SystemHook.TIME_DESTROY : SystemHook.TIME_SUICIDE);
}
SystemHook.killNoFather();
}
public void onResumeActivity(Object activityRecord) {
String packageName = ActivityRecordUtils.getPackageName(activityRecord);
if (packageName == null) {
return;
}
SystemHook.cancelCheck(packageName);
SystemHook.updateRunningGapps(packageName, true);
if (Boolean.TRUE.equals(mPreventPackages.get(packageName))) {
mPreventPackages.put(packageName, false);
}
int count = countCounter(packageName);
LogUtils.logActivity("resume activity", packageName, count);
removeLeaving(packageName);
}
public void onUserLeavingActivity(Object activityRecord) {
String packageName = ActivityRecordUtils.getPackageName(activityRecord);
if (packageName == null) {
return;
}
int count = countCounter(packageName);
leavingPackages.put(packageName, TimeUtils.now());
LogUtils.logActivity("user leaving activity", packageName, count);
}
private void removeLeaving(String packageName) {
leavingPackages.remove(packageName);
}
protected long fixLeaving(String packageName) {
PreventLog.d(packageName + " is not prevented and has no leaving time, fix it");
long now = TimeUtils.now();
leavingPackages.put(packageName, now);
return now;
}
protected void onPackageRemoved(String packageName) {
removeLeaving(packageName);
}
private void cancelCheckingIfNeeded() {
if (leavingFuture != null && leavingFuture.getDelay(TimeUnit.SECONDS) > 0) {
leavingFuture.cancel(false);
}
}
protected void onScreenOn() {
PreventLog.d("screen on");
screen = true;
cancelCheckingIfNeeded();
}
protected void onScreenOff() {
PreventLog.d("screen off");
screen = false;
cancelCheckingIfNeeded();
checkLeavingNext.clear();
checkLeavingPackages();
}
public void cancelCheckLeaving(String packageName) {
checkLeavingNext.remove(packageName);
}
protected Long getLastRunning(String packageName) {
return leavingPackages.get(packageName);
}
private void checkLeavingPackages() {
long forceStopTimeout = Configuration.getDefault().getForceStopTimeout();
if (forceStopTimeout <= 0) {
return;
}
PreventLog.d("checking leaving packages");
long now = TimeUtils.now();
Iterator<Map.Entry<String, Boolean>> iterator = mPreventPackages.entrySet().iterator();
Set<String> stopPackages = new HashSet<String>();
boolean needCheckMore = false;
while (iterator.hasNext()) {
Map.Entry<String, Boolean> entry = iterator.next();
String packageName = entry.getKey();
Boolean prevent = entry.getValue();
if (!Boolean.FALSE.equals(prevent) || packageName.equals(SystemHook.getCurrentPackageName())) {
continue;
}
Long lastRunning = getLastRunning(packageName);
if (lastRunning == null) {
lastRunning = fixLeaving(packageName);
}
long elapsed = now - lastRunning;
if (elapsed >= forceStopTimeout) {
PreventLog.i("leaving package " + packageName + " for " + elapsed + " seconds");
stopPackages.add(packageName);
} else {
needCheckMore = true;
}
}
forceStopPackages(stopPackages);
if (needCheckMore) {
checkLeavingPackagesIfNeeded();
}
}
private void forceStopPackages(Set<String> stopPackages) {
for (String packageName : stopPackages) {
if (screen) {
break;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || !hasHighPriority(packageName)) {
if (SystemHook.forceStopPackage(packageName, false)) {
removeLeaving(packageName);
}
checkLeavingNext.remove(packageName);
}
}
}
protected boolean hasHighPriority(String packageName) {
INotificationManager sINM = INotificationManager.Stub.asInterface(ServiceManager.getService(Context.NOTIFICATION_SERVICE));
try {
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packageName, 0);
int priority = getPriority(sINM, packageName, info.uid);
if (priority == Notification.PRIORITY_MAX) {
PreventLog.d(packageName + " has high priority " + priority + ", cannot stop");
return true;
}
PreventLog.v("package " + packageName + ", priority: " + priority);
} catch (RemoteException e) {
PreventLog.d("cannot get package priority for " + packageName, e);
} catch (PackageManager.NameNotFoundException e) {
PreventLog.d("cannot find package " + packageName, e);
}
return false;
}
private int getPriority(INotificationManager sINM, String packageName, int uid) throws RemoteException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return sINM.getPriority(packageName, uid);
} else {
return sINM.getPackagePriority(packageName, uid);
}
}
private void checkLeavingPackagesIfNeeded() {
if (!screen) {
leavingFuture = singleExecutor.schedule(new Runnable() {
@Override
public void run() {
if (!screen) {
checkLeavingPackages();
}
}
}, SystemHook.TIME_CHECK_USER_LEAVING, TimeUnit.SECONDS);
}
}
public void onAppDied(Object processRecord) {
String packageName = ProcessRecordUtils.getInfo(processRecord).packageName;
if (leavingPackages.containsKey(packageName)) {
LogUtils.logActivity("app died when user leaving", packageName, -1);
return;
}
int count = countCounter(packageName);
LogUtils.logActivity("app died", packageName, count);
int pid = ProcessRecordUtils.getPid(processRecord);
if (!shouldStop(packageName, pid)) {
return;
}
SystemHook.updateRunningGapps(packageName, false);
if (mPreventPackages.containsKey(packageName)) {
mPreventPackages.put(packageName, true);
SystemHook.checkRunningServices(packageName, SystemHook.TIME_IMMEDIATE < SystemHook.TIME_DESTROY ? SystemHook.TIME_DESTROY : SystemHook.TIME_IMMEDIATE);
}
}
private boolean shouldStop(String packageName, int pid) {
countCounter(packageName);
Map<Integer, AtomicInteger> values = packageCounters.get(packageName);
if (values == null) {
return true;
}
Set<Integer> pids = new HashSet<Integer>(values.keySet());
pids.remove(pid);
return pids.isEmpty();
}
protected void removePackageCounters(String packageName) {
packageCounters.remove(packageName);
}
}