File: PermissionUsageHelper.java

package info (click to toggle)
android-platform-frameworks-base 1%3A14~beta1-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 326,092 kB
  • sloc: java: 2,032,373; xml: 343,016; cpp: 304,181; python: 3,683; ansic: 2,090; sh: 1,871; makefile: 117; sed: 19
file content (800 lines) | stat: -rw-r--r-- 34,495 bytes parent folder | download | duplicates (2)
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.permission;

import static android.Manifest.permission_group.CAMERA;
import static android.Manifest.permission_group.LOCATION;
import static android.Manifest.permission_group.MICROPHONE;
import static android.app.AppOpsManager.ATTRIBUTION_CHAIN_ID_NONE;
import static android.app.AppOpsManager.ATTRIBUTION_FLAGS_NONE;
import static android.app.AppOpsManager.ATTRIBUTION_FLAG_ACCESSOR;
import static android.app.AppOpsManager.ATTRIBUTION_FLAG_RECEIVER;
import static android.app.AppOpsManager.ATTRIBUTION_FLAG_TRUSTED;
import static android.app.AppOpsManager.AttributionFlags;
import static android.app.AppOpsManager.OPSTR_CAMERA;
import static android.app.AppOpsManager.OPSTR_COARSE_LOCATION;
import static android.app.AppOpsManager.OPSTR_FINE_LOCATION;
import static android.app.AppOpsManager.OPSTR_PHONE_CALL_CAMERA;
import static android.app.AppOpsManager.OPSTR_PHONE_CALL_MICROPHONE;
import static android.app.AppOpsManager.OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO;
import static android.app.AppOpsManager.OPSTR_RECORD_AUDIO;
import static android.app.AppOpsManager.OP_CAMERA;
import static android.app.AppOpsManager.OP_FLAGS_ALL_TRUSTED;
import static android.app.AppOpsManager.OP_RECORD_AUDIO;
import static android.media.AudioSystem.MODE_IN_COMMUNICATION;
import static android.telephony.TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.Attribution;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.icu.text.ListFormatter;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Process;
import android.os.UserHandle;
import android.provider.DeviceConfig;
import android.telephony.TelephonyManager;
import android.util.ArrayMap;
import android.util.ArraySet;

import com.android.internal.annotations.GuardedBy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * A helper which gets all apps which have used microphone, camera, and possible location
 * permissions within a certain timeframe, as well as possible special attributions, and if the
 * usage is a phone call.
 *
 * @hide
 */
public class PermissionUsageHelper implements AppOpsManager.OnOpActiveChangedListener,
        AppOpsManager.OnOpStartedListener {

    /**
     * Whether to show the mic and camera icons.
     */
    private static final String PROPERTY_CAMERA_MIC_ICONS_ENABLED = "camera_mic_icons_enabled";

    /**
     * Whether to show the location indicators.
     */
    private static final String PROPERTY_LOCATION_INDICATORS_ENABLED =
            "location_indicators_enabled";

    /**
     * Whether to show the Permissions Hub.
     */
    private static final String PROPERTY_PERMISSIONS_HUB_2_ENABLED = "permissions_hub_2_enabled";

    /**
     * How long after an access to show it as "recent"
     */
    private static final String RECENT_ACCESS_TIME_MS = "recent_access_time_ms";

    /**
     * How long after an access to show it as "running"
     */
    private static final String RUNNING_ACCESS_TIME_MS = "running_access_time_ms";

    private static final String SYSTEM_PKG = "android";

    private static final long DEFAULT_RUNNING_TIME_MS = 5000L;
    private static final long DEFAULT_RECENT_TIME_MS = 15000L;

    private static boolean shouldShowPermissionsHub() {
        return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY,
                PROPERTY_PERMISSIONS_HUB_2_ENABLED, false);
    }

    private static boolean shouldShowIndicators() {
        return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY,
                PROPERTY_CAMERA_MIC_ICONS_ENABLED, true) || shouldShowPermissionsHub();
    }

    private static boolean shouldShowLocationIndicator() {
        return DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY,
                PROPERTY_LOCATION_INDICATORS_ENABLED, false);
    }

    private static long getRecentThreshold(Long now) {
        return now - DeviceConfig.getLong(DeviceConfig.NAMESPACE_PRIVACY,
                RECENT_ACCESS_TIME_MS, DEFAULT_RECENT_TIME_MS);
    }

    private static long getRunningThreshold(Long now) {
        return now - DeviceConfig.getLong(DeviceConfig.NAMESPACE_PRIVACY,
                RUNNING_ACCESS_TIME_MS, DEFAULT_RUNNING_TIME_MS);
    }

    private static final List<String> LOCATION_OPS = List.of(
            OPSTR_COARSE_LOCATION,
            OPSTR_FINE_LOCATION
    );

    private static final List<String> MIC_OPS = List.of(
            OPSTR_PHONE_CALL_MICROPHONE,
            OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO,
            OPSTR_RECORD_AUDIO
    );

    private static final List<String> CAMERA_OPS = List.of(
            OPSTR_PHONE_CALL_CAMERA,
            OPSTR_CAMERA
    );

    private static @NonNull String getGroupForOp(String op) {
        switch (op) {
            case OPSTR_RECEIVE_AMBIENT_TRIGGER_AUDIO:
            case OPSTR_RECORD_AUDIO:
                return MICROPHONE;
            case OPSTR_CAMERA:
                return CAMERA;
            case OPSTR_PHONE_CALL_MICROPHONE:
            case OPSTR_PHONE_CALL_CAMERA:
                return op;
            case OPSTR_COARSE_LOCATION:
            case OPSTR_FINE_LOCATION:
                return LOCATION;
            default:
                throw new IllegalArgumentException("Unknown app op: " + op);
        }
    }

    private Context mContext;
    private ArrayMap<UserHandle, Context> mUserContexts;
    private PackageManager mPkgManager;
    private AppOpsManager mAppOpsManager;
    @GuardedBy("mAttributionChains")
    private final ArrayMap<Integer, ArrayList<AccessChainLink>> mAttributionChains =
            new ArrayMap<>();

    /**
     * Constructor for PermissionUsageHelper
     *
     * @param context The context from which to derive the package information
     */
    public PermissionUsageHelper(@NonNull Context context) {
        mContext = context;
        mPkgManager = context.getPackageManager();
        mAppOpsManager = context.getSystemService(AppOpsManager.class);
        mUserContexts = new ArrayMap<>();
        mUserContexts.put(Process.myUserHandle(), mContext);
        // TODO ntmyren: make this listen for flag enable/disable changes
        String[] opStrs = {OPSTR_CAMERA, OPSTR_RECORD_AUDIO};
        mAppOpsManager.startWatchingActive(opStrs, context.getMainExecutor(), this);
        int[] ops = {OP_CAMERA, OP_RECORD_AUDIO};
        mAppOpsManager.startWatchingStarted(ops, this);
    }

    private Context getUserContext(UserHandle user) {
        if (!(mUserContexts.containsKey(user))) {
            mUserContexts.put(user, mContext.createContextAsUser(user, 0));
        }
        return mUserContexts.get(user);
    }

    public void tearDown() {
        mAppOpsManager.stopWatchingActive(this);
        mAppOpsManager.stopWatchingStarted(this);
    }

    @Override
    public void onOpActiveChanged(@NonNull String op, int uid, @NonNull String packageName,
            boolean active) {
        // not part of an attribution chain. Do nothing
    }

    @Override
    public void onOpActiveChanged(@NonNull String op, int uid, @NonNull String packageName,
            @Nullable String attributionTag, boolean active, @AttributionFlags int attributionFlags,
            int attributionChainId) {
        if (active) {
            // Started callback handles these
            return;
        }

        // if any link in the chain is finished, remove the chain. Then, find any other chains that
        // contain this op/package/uid/tag combination, and remove them, as well.
        // TODO ntmyren: be smarter about this
        synchronized (mAttributionChains) {
            mAttributionChains.remove(attributionChainId);
            int numChains = mAttributionChains.size();
            ArrayList<Integer> toRemove = new ArrayList<>();
            for (int i = 0; i < numChains; i++) {
                int chainId = mAttributionChains.keyAt(i);
                ArrayList<AccessChainLink> chain = mAttributionChains.valueAt(i);
                int chainSize = chain.size();
                for (int j = 0; j < chainSize; j++) {
                    AccessChainLink link = chain.get(j);
                    if (link.packageAndOpEquals(op, packageName, attributionTag, uid)) {
                        toRemove.add(chainId);
                        break;
                    }
                }
            }
            mAttributionChains.removeAll(toRemove);
        }
    }

    @Override
    public void onOpStarted(int op, int uid, String packageName, String attributionTag,
            @AppOpsManager.OpFlags int flags, @AppOpsManager.Mode int result) {
        // not part of an attribution chain. Do nothing
    }

    @Override
    public void onOpStarted(int op, int uid, String packageName, String attributionTag,
            @AppOpsManager.OpFlags int flags, @AppOpsManager.Mode int result,
            @StartedType int startedType, @AttributionFlags int attributionFlags,
            int attributionChainId) {
        if (startedType == START_TYPE_FAILED || attributionChainId == ATTRIBUTION_CHAIN_ID_NONE
                || attributionFlags == ATTRIBUTION_FLAGS_NONE
                || (attributionFlags & ATTRIBUTION_FLAG_TRUSTED) == 0) {
            // If this is not a successful start, or it is not a chain, or it is untrusted, return
            return;
        }
        synchronized (mAttributionChains) {
            addLinkToChainIfNotPresentLocked(AppOpsManager.opToPublicName(op), packageName, uid,
                    attributionTag, attributionFlags, attributionChainId);
        }
    }

    private void addLinkToChainIfNotPresentLocked(String op, String packageName, int uid,
            String attributionTag, int attributionFlags, int attributionChainId) {

        ArrayList<AccessChainLink> currentChain = mAttributionChains.computeIfAbsent(
                attributionChainId, k -> new ArrayList<>());
        AccessChainLink link = new AccessChainLink(op, packageName, attributionTag, uid,
                attributionFlags);

        if (currentChain.contains(link)) {
            return;
        }

        int currSize = currentChain.size();
        if (currSize == 0 || link.isEnd() || !currentChain.get(currSize - 1).isEnd()) {
            // if the list is empty, this link is the end, or the last link in the current chain
            // isn't the end, add it to the end
            currentChain.add(link);
        } else if (link.isStart()) {
            currentChain.add(0, link);
        } else if (currentChain.get(currentChain.size() - 1).isEnd()) {
            // we already have the end, and this is a mid node, so insert before the end
            currentChain.add(currSize - 1, link);
        }
    }

    /**
     * @see PermissionManager.getIndicatorAppOpUsageData
     */
    public @NonNull List<PermissionGroupUsage> getOpUsageData(boolean isMicMuted) {
        List<PermissionGroupUsage> usages = new ArrayList<>();

        if (!shouldShowIndicators()) {
            return usages;
        }

        List<String> ops = new ArrayList<>(CAMERA_OPS);
        if (shouldShowLocationIndicator()) {
            ops.addAll(LOCATION_OPS);
        }
        if (!isMicMuted) {
            ops.addAll(MIC_OPS);
        }

        Map<String, List<OpUsage>> rawUsages = getOpUsages(ops);

        ArrayList<String> usedPermGroups = new ArrayList<>(rawUsages.keySet());

        // If we have a phone call, and a carrier privileged app using microphone, hide the
        // phone call.
        AudioManager audioManager = mContext.getSystemService(AudioManager.class);
        boolean hasPhoneCall = usedPermGroups.contains(OPSTR_PHONE_CALL_CAMERA)
                || usedPermGroups.contains(OPSTR_PHONE_CALL_MICROPHONE);
        if (hasPhoneCall && usedPermGroups.contains(MICROPHONE) && audioManager.getMode()
                == MODE_IN_COMMUNICATION) {
            TelephonyManager telephonyManager =
                    mContext.getSystemService(TelephonyManager.class);
            List<OpUsage> permUsages = rawUsages.get(MICROPHONE);
            for (int usageNum = 0; usageNum < permUsages.size(); usageNum++) {
                if (telephonyManager.checkCarrierPrivilegesForPackage(
                        permUsages.get(usageNum).packageName)
                        == CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
                    usedPermGroups.remove(OPSTR_PHONE_CALL_CAMERA);
                    usedPermGroups.remove(OPSTR_PHONE_CALL_MICROPHONE);
                }
            }
        }

        // map of package name -> map of attribution tag -> attribution labels
        ArrayMap<String, Map<String, String>> subAttributionLabelsMap = new ArrayMap<>();

        for (int permGroupNum = 0; permGroupNum < usedPermGroups.size(); permGroupNum++) {
            boolean isPhone = false;
            String permGroup = usedPermGroups.get(permGroupNum);

            ArrayMap<OpUsage, CharSequence> usagesWithLabels =
                    getUniqueUsagesWithLabels(permGroup, rawUsages.get(permGroup));

            updateSubattributionLabelsMap(rawUsages.get(permGroup), subAttributionLabelsMap);

            if (permGroup.equals(OPSTR_PHONE_CALL_MICROPHONE)) {
                isPhone = true;
                permGroup = MICROPHONE;
            } else if (permGroup.equals(OPSTR_PHONE_CALL_CAMERA)) {
                isPhone = true;
                permGroup = CAMERA;
            }

            for (int usageNum = 0; usageNum < usagesWithLabels.size(); usageNum++) {
                OpUsage usage = usagesWithLabels.keyAt(usageNum);
                String attributionLabel = subAttributionLabelsMap.getOrDefault(usage.packageName,
                        new ArrayMap<>()).getOrDefault(usage.attributionTag, null);
                usages.add(
                        new PermissionGroupUsage(usage.packageName, usage.uid, usage.lastAccessTime,
                                permGroup,
                                usage.isRunning, isPhone, usage.attributionTag, attributionLabel,
                                usagesWithLabels.valueAt(usageNum)));
            }
        }

        return usages;
    }

    private void updateSubattributionLabelsMap(List<OpUsage> usages,
            ArrayMap<String, Map<String, String>> subAttributionLabelsMap) {
        if (usages == null || usages.isEmpty()) {
            return;
        }
        for (OpUsage usage : usages) {
            if (usage.attributionTag != null && !subAttributionLabelsMap.containsKey(
                    usage.packageName)) {
                subAttributionLabelsMap.put(usage.packageName,
                        getSubattributionLabelsForPackage(usage.packageName, usage.uid));
            }
        }
    }

    /**
     * Query attribution labels for a package
     *
     * @param packageName
     * @param uid
     * @return map of attribution tag -> attribution labels for a package
     */
    private ArrayMap<String, String> getSubattributionLabelsForPackage(String packageName,
            int uid) {
        ArrayMap<String, String> attributionLabelMap = new ArrayMap<>();
        UserHandle user = UserHandle.getUserHandleForUid(uid);
        try {
            if (!isSubattributionSupported(packageName, uid)) {
                return attributionLabelMap;
            }
            Context userContext = getUserContext(user);
            PackageInfo packageInfo = userContext.getPackageManager().getPackageInfo(
                    packageName,
                    PackageManager.GET_PERMISSIONS | PackageManager.GET_ATTRIBUTIONS);
            Context pkgContext = userContext.createPackageContext(packageInfo.packageName, 0);
            for (Attribution attribution : packageInfo.attributions) {
                try {
                    String resourceForLabel = pkgContext.getString(attribution.getLabel());
                    attributionLabelMap.put(attribution.getTag(), resourceForLabel);
                } catch (Resources.NotFoundException e) {
                    // Shouldn't happen, do nothing
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            // Did not find the package, do nothing
        }
        return attributionLabelMap;
    }

    /**
     * Returns true if the app satisfies subattribution policies and supports it
     */
    private boolean isSubattributionSupported(String packageName, int uid) {
        try {
            if (!isLocationProvider(packageName)) {
                return false;
            }
            PackageManager userPkgManager =
                    getUserContext(UserHandle.getUserHandleForUid(uid)).getPackageManager();
            ApplicationInfo appInfo = userPkgManager.getApplicationInfoAsUser(packageName,
                    PackageManager.ApplicationInfoFlags.of(0),
                    UserHandle.getUserId(uid));
            if (appInfo != null) {
                return appInfo.areAttributionsUserVisible();
            }
            return false;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * @param packageName
     * @return If the package is location provider
     */
    private boolean isLocationProvider(String packageName) {
        return Objects.requireNonNull(
                mContext.getSystemService(LocationManager.class)).isProviderPackage(packageName);
    }

    /**
     * Get the raw usages from the system, and then parse out the ones that are not recent enough,
     * determine which permission group each belongs in, and removes duplicates (if the same app
     * uses multiple permissions of the same group). Stores the package name, attribution tag, user,
     * running/recent info, if the usage is a phone call, per permission group.
     *
     * @param opNames a list of op names to get usage for
     * @return A map of permission group -> list of usages that are recent or running
     */
    private Map<String, List<OpUsage>> getOpUsages(List<String> opNames) {
        List<AppOpsManager.PackageOps> ops;
        try {
            ops = mAppOpsManager.getPackagesForOps(opNames.toArray(new String[opNames.size()]));
        } catch (NullPointerException e) {
            // older builds might not support all the app-ops requested
            return Collections.emptyMap();
        }

        long now = System.currentTimeMillis();
        long recentThreshold = getRecentThreshold(now);
        long runningThreshold = getRunningThreshold(now);
        int opFlags = OP_FLAGS_ALL_TRUSTED;
        Map<String, Map<Integer, OpUsage>> usages = new ArrayMap<>();

        int numPkgOps = ops.size();
        for (int pkgOpNum = 0; pkgOpNum < numPkgOps; pkgOpNum++) {
            AppOpsManager.PackageOps pkgOps = ops.get(pkgOpNum);
            int uid = pkgOps.getUid();
            UserHandle user = UserHandle.getUserHandleForUid(uid);
            String packageName = pkgOps.getPackageName();

            int numOpEntries = pkgOps.getOps().size();
            for (int opEntryNum = 0; opEntryNum < numOpEntries; opEntryNum++) {
                AppOpsManager.OpEntry opEntry = pkgOps.getOps().get(opEntryNum);
                String op = opEntry.getOpStr();
                List<String> attributionTags =
                        new ArrayList<>(opEntry.getAttributedOpEntries().keySet());


                int numAttrEntries = opEntry.getAttributedOpEntries().size();
                for (int attrOpEntryNum = 0; attrOpEntryNum < numAttrEntries; attrOpEntryNum++) {
                    String attributionTag = attributionTags.get(attrOpEntryNum);
                    AppOpsManager.AttributedOpEntry attrOpEntry =
                            opEntry.getAttributedOpEntries().get(attributionTag);

                    long lastAccessTime = attrOpEntry.getLastAccessTime(opFlags);
                    if (attrOpEntry.isRunning()) {
                        lastAccessTime = now;
                    }

                    if (lastAccessTime < recentThreshold && !attrOpEntry.isRunning()) {
                        continue;
                    }

                    boolean isRunning = attrOpEntry.isRunning()
                            || lastAccessTime >= runningThreshold;

                    OpUsage proxyUsage = null;
                    AppOpsManager.OpEventProxyInfo proxy = attrOpEntry.getLastProxyInfo(opFlags);
                    if (proxy != null && proxy.getPackageName() != null) {
                        proxyUsage = new OpUsage(proxy.getPackageName(), proxy.getAttributionTag(),
                                op, proxy.getUid(), lastAccessTime, isRunning, null);
                    }

                    String permGroupName = getGroupForOp(op);
                    OpUsage usage = new OpUsage(packageName, attributionTag, op, uid,
                            lastAccessTime, isRunning, proxyUsage);

                    Integer packageAttr = usage.getPackageIdHash();
                    if (!usages.containsKey(permGroupName)) {
                        ArrayMap<Integer, OpUsage> map = new ArrayMap<>();
                        map.put(packageAttr, usage);
                        usages.put(permGroupName, map);
                    } else {
                        Map<Integer, OpUsage> permGroupUsages =
                                usages.get(permGroupName);
                        if (!permGroupUsages.containsKey(packageAttr)) {
                            permGroupUsages.put(packageAttr, usage);
                        } else if (usage.lastAccessTime
                                > permGroupUsages.get(packageAttr).lastAccessTime) {
                            permGroupUsages.put(packageAttr, usage);
                        }
                    }
                }
            }
        }

        Map<String, List<OpUsage>> flattenedUsages = new ArrayMap<>();
        List<String> permGroups = new ArrayList<>(usages.keySet());
        for (int i = 0; i < permGroups.size(); i++) {
            String permGroupName = permGroups.get(i);
            flattenedUsages.put(permGroupName, new ArrayList<>(usages.get(permGroupName).values()));
        }
        return flattenedUsages;
    }

    private CharSequence formatLabelList(List<CharSequence> labels) {
        return ListFormatter.getInstance().format(labels);
    }

    private ArrayMap<OpUsage, CharSequence> getUniqueUsagesWithLabels(String permGroup,
            List<OpUsage> usages) {
        ArrayMap<OpUsage, CharSequence> usagesAndLabels = new ArrayMap<>();

        if (usages == null || usages.isEmpty()) {
            return usagesAndLabels;
        }

        ArrayMap<Integer, OpUsage> allUsages = new ArrayMap<>();
        // map of packageName and uid hash -> most recent non-proxy-related usage for that uid.
        ArrayMap<Integer, OpUsage> mostRecentUsages = new ArrayMap<>();
        // set of all packages involved in a proxy usage
        ArraySet<Integer> proxyPackages = new ArraySet<>();
        // map of usage -> list of proxy app labels
        ArrayMap<OpUsage, ArrayList<CharSequence>> proxyLabels = new ArrayMap<>();
        // map of usage.proxy hash -> usage hash, telling us if a usage is a proxy
        ArrayMap<Integer, OpUsage> proxies = new ArrayMap<>();

        for (int i = 0; i < usages.size(); i++) {
            OpUsage usage = usages.get(i);
            allUsages.put(usage.getPackageIdHash(), usage);
            if (usage.proxy != null) {
                proxies.put(usage.proxy.getPackageIdHash(), usage);
            }
        }

        // find all possible end points for chains, and find the most recent of the rest of the uses
        for (int usageNum = 0; usageNum < usages.size(); usageNum++) {
            OpUsage usage = usages.get(usageNum);
            if (usage == null) {
                continue;
            }

            int usageAttr = usage.getPackageIdHash();
            // If this usage has a proxy, but is not a proxy, it is the end of a chain.
            // TODO remove once camera converted
            if (!proxies.containsKey(usageAttr) && usage.proxy != null
                    && !MICROPHONE.equals(permGroup)) {
                proxyLabels.put(usage, new ArrayList<>());
                proxyPackages.add(usage.getPackageIdHash());
            }
            // If this usage is not by the system, and is more recent than the next-most recent
            // for it's uid and package name, save it.
            int usageId = usage.getPackageIdHash();
            OpUsage lastMostRecent = mostRecentUsages.get(usageId);
            if (shouldShowPackage(usage.packageName) && (lastMostRecent == null
                    || usage.lastAccessTime > lastMostRecent.lastAccessTime)) {
                mostRecentUsages.put(usageId, usage);
            }
        }

        // get all the proxy labels
        for (int numStart = 0; numStart < proxyLabels.size(); numStart++) {
            OpUsage start = proxyLabels.keyAt(numStart);
            // Remove any non-proxy usage for the starting package
            mostRecentUsages.remove(start.getPackageIdHash());
            OpUsage currentUsage = proxyLabels.keyAt(numStart);
            ArrayList<CharSequence> proxyLabelList = proxyLabels.get(currentUsage);
            if (currentUsage == null || proxyLabelList == null) {
                continue;
            }
            int iterNum = 0;
            int maxUsages = allUsages.size();
            while (currentUsage.proxy != null) {

                if (allUsages.containsKey(currentUsage.proxy.getPackageIdHash())) {
                    currentUsage = allUsages.get(currentUsage.proxy.getPackageIdHash());
                } else {
                    // We are missing the proxy usage. This may be because it's a one-step trusted
                    // proxy. Check if we should show the proxy label, and show it, if so.
                    OpUsage proxy = currentUsage.proxy;
                    if (shouldShowPackage(proxy.packageName)) {
                        currentUsage = proxy;
                        // We've effectively added one usage, so increment the max number of usages
                        maxUsages++;
                    } else {
                        break;
                    }
                }

                if (currentUsage == null || iterNum == maxUsages
                        || currentUsage.getPackageIdHash() == start.getPackageIdHash()) {
                    // We have an invalid state, or a cycle, so break
                    break;
                }

                proxyPackages.add(currentUsage.getPackageIdHash());
                // Don't add an app label for the main app, or the system app
                if (!currentUsage.packageName.equals(start.packageName)
                        && shouldShowPackage(currentUsage.packageName)) {
                    try {
                        PackageManager userPkgManager =
                                getUserContext(currentUsage.getUser()).getPackageManager();
                        ApplicationInfo appInfo = userPkgManager.getApplicationInfo(
                                currentUsage.packageName, 0);
                        CharSequence appLabel = appInfo.loadLabel(userPkgManager);
                        // If we don't already have the app label add it
                        if (!proxyLabelList.contains(appLabel)) {
                            proxyLabelList.add(appLabel);
                        }
                    } catch (PackageManager.NameNotFoundException e) {
                        // Ignore
                    }
                }
                iterNum++;
            }

            // TODO ntmyren: remove this proxy logic once camera is converted to AttributionSource
            // For now: don't add mic proxy usages
            if (!MICROPHONE.equals(permGroup)) {
                usagesAndLabels.put(start,
                        proxyLabelList.isEmpty() ? null : formatLabelList(proxyLabelList));
            }
        }

        synchronized (mAttributionChains) {
            for (int i = 0; i < mAttributionChains.size(); i++) {
                List<AccessChainLink> usageList = mAttributionChains.valueAt(i);
                int lastVisible = usageList.size() - 1;
                // TODO ntmyren: remove this mic code once camera is converted to AttributionSource
                // if the list is empty or incomplete, do not show it.
                if (usageList.isEmpty() || !usageList.get(lastVisible).isEnd()
                        || !usageList.get(0).isStart()
                        || !permGroup.equals(getGroupForOp(usageList.get(0).usage.op))
                        || !MICROPHONE.equals(permGroup)) {
                    continue;
                }

                //TODO ntmyren: remove once camera etc. etc.
                for (AccessChainLink link : usageList) {
                    proxyPackages.add(link.usage.getPackageIdHash());
                }

                AccessChainLink start = usageList.get(0);
                AccessChainLink lastVisibleLink = usageList.get(lastVisible);
                while (lastVisible > 0 && !shouldShowPackage(lastVisibleLink.usage.packageName)) {
                    lastVisible--;
                    lastVisibleLink = usageList.get(lastVisible);
                }
                String proxyLabel = null;
                if (!lastVisibleLink.usage.packageName.equals(start.usage.packageName)) {
                    try {
                        PackageManager userPkgManager =
                                getUserContext(lastVisibleLink.usage.getUser()).getPackageManager();
                        ApplicationInfo appInfo = userPkgManager.getApplicationInfo(
                                lastVisibleLink.usage.packageName, 0);
                        proxyLabel = appInfo.loadLabel(userPkgManager).toString();
                    } catch (PackageManager.NameNotFoundException e) {
                        // do nothing
                    }
                }
                usagesAndLabels.put(start.usage, proxyLabel);
            }
        }

        for (int packageHash : mostRecentUsages.keySet()) {
            if (!proxyPackages.contains(packageHash)) {
                usagesAndLabels.put(mostRecentUsages.get(packageHash), null);
            }
        }

        return usagesAndLabels;
    }

    private boolean shouldShowPackage(String packageName) {
        return PermissionManager.shouldShowPackageForIndicatorCached(mContext, packageName);
    }

    /**
     * Represents the usage of an App op by a particular package and attribution
     */
    private static class OpUsage {

        public final String packageName;
        public final String attributionTag;
        public final String op;
        public final int uid;
        public final long lastAccessTime;
        public final OpUsage proxy;
        public final boolean isRunning;

        OpUsage(String packageName, String attributionTag, String op, int uid, long lastAccessTime,
                boolean isRunning, OpUsage proxy) {
            this.packageName = packageName;
            this.attributionTag = attributionTag;
            this.op = op;
            this.uid = uid;
            this.lastAccessTime = lastAccessTime;
            this.isRunning = isRunning;
            this.proxy = proxy;
        }

        public UserHandle getUser() {
            return UserHandle.getUserHandleForUid(uid);
        }

        public int getPackageIdHash() {
            return Objects.hash(packageName, uid);
        }

        @Override
        public int hashCode() {
            return Objects.hash(packageName, attributionTag, op, uid, lastAccessTime, isRunning);
        }

        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof OpUsage)) {
                return false;
            }
            OpUsage other = (OpUsage) obj;
            return Objects.equals(packageName, other.packageName) && Objects.equals(attributionTag,
                    other.attributionTag) && Objects.equals(op, other.op) && uid == other.uid
                    && lastAccessTime == other.lastAccessTime && isRunning == other.isRunning;
        }
    }

    private static class AccessChainLink {
        public final OpUsage usage;
        public final @AttributionFlags int flags;

        AccessChainLink(String op, String packageName, String attributionTag, int uid,
                int flags) {
            this.usage = new OpUsage(packageName, attributionTag, op, uid,
                    System.currentTimeMillis(), true, null);
            this.flags = flags;
        }

        public boolean isEnd() {
            return (flags & ATTRIBUTION_FLAG_ACCESSOR) != 0;
        }

        public boolean isStart() {
            return (flags & ATTRIBUTION_FLAG_RECEIVER) != 0;
        }

        @Override
        public boolean equals(Object obj) {
            if (!(obj instanceof AccessChainLink)) {
                return false;
            }
            AccessChainLink other = (AccessChainLink) obj;
            return other.flags == flags && packageAndOpEquals(other.usage.op,
                    other.usage.packageName, other.usage.attributionTag, other.usage.uid);
        }

        public boolean packageAndOpEquals(String op, String packageName, String attributionTag,
                int uid) {
            return Objects.equals(op, usage.op) && Objects.equals(packageName, usage.packageName)
                    && Objects.equals(attributionTag, usage.attributionTag) && uid == usage.uid;
        }
    }
}