summaryrefslogtreecommitdiff
path: root/hostsidetests/appbinding/hostside/src/com/android/cts/appbinding/AppBindingHostTest.java
blob: f2e4a0489e6da5a0ce7795935c8b9a2b20e84215 (plain)
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
/*
 * Copyright (C) 2018 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 com.android.cts.appbinding;

import com.android.tradefed.util.RunUtil;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.log.LogUtil.CLog;
import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
import com.android.tradefed.testtype.IBuildReceiver;
import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
import com.android.tradefed.testtype.junit4.DeviceTestRunOptions;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RunWith(DeviceJUnit4ClassRunner.class)
public class AppBindingHostTest extends BaseHostJUnit4Test implements IBuildReceiver {

    private static final boolean SKIP_UNINSTALL = false;

    private static final String APK_1 = "CtsAppBindingService1.apk";
    private static final String APK_2 = "CtsAppBindingService2.apk";
    private static final String APK_3 = "CtsAppBindingService3.apk";
    private static final String APK_4 = "CtsAppBindingService4.apk";
    private static final String APK_5 = "CtsAppBindingService5.apk";
    private static final String APK_6 = "CtsAppBindingService6.apk";
    private static final String APK_7 = "CtsAppBindingService7.apk";
    private static final String APK_B = "CtsAppBindingServiceB.apk";

    private static final String PACKAGE_A = "com.android.cts.appbinding.app";
    private static final String PACKAGE_B = "com.android.cts.appbinding.app.b";

    private static final String PACKAGE_A_PROC = PACKAGE_A + ":persistent";

    private static final String APP_BINDING_SETTING = "app_binding_constants";

    private static final String SERVICE_1 = "com.android.cts.appbinding.app.MyService";
    private static final String SERVICE_2 = "com.android.cts.appbinding.app.MyService2";

    private IBuildInfo mCtsBuild;
    private int mCurrentUserId;

    private static final int DEFAULT_TIMEOUT_SEC = 30;

    private interface ThrowingRunnable {
        void run() throws Throwable;
    }

    @Override
    public void setBuild(IBuildInfo buildInfo) {
        mCtsBuild = buildInfo;
    }

    private void installAppAsUser(String appFileName, boolean grantPermissions, int userId)
            throws Exception {
        CLog.d("Installing app " + appFileName + " for user " + userId);
        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
        String result = getDevice().installPackageForUser(
                buildHelper.getTestFile(appFileName), true, grantPermissions, userId, "-t");
        assertNull("Failed to install " + appFileName + " for user " + userId + ": " + result,
                result);

        waitForBroadcastIdle();
    }

    private void waitForBroadcastIdle() throws Exception {
        runCommand("am wait-for-broadcast-idle");
        RunUtil.getDefault().sleep(100); // Just wait a bit to make sure the system isn't too busy...
    }

    private String runCommand(String command) throws Exception {
        return runCommand(command, "", true);
    }

    private String runCommand(String command, String expectedOutputPattern) throws Exception {
        return runCommand(command, expectedOutputPattern, true);
    }

    private String runCommandAndNotMatch(String command, String expectedOutputPattern)
            throws Exception {
        return runCommand(command, expectedOutputPattern, false);
    }

    private String runCommand(String command, String expectedOutputPattern,
            boolean shouldMatch) throws Exception {
        CLog.d("Executing command: " + command);
        final String output = getDevice().executeShellCommand(command);

        CLog.d("Output:\n"
                + "====================\n"
                + output
                + "====================");

        final Pattern pat = Pattern.compile(
                expectedOutputPattern, Pattern.MULTILINE | Pattern.COMMENTS);
        if (pat.matcher(output.trim()).find() != shouldMatch) {
            fail("Output from \"" + command + "\" "
                    + (shouldMatch ? "didn't match" : "unexpectedly matched")
                    + " \"" + expectedOutputPattern + "\"");
        }
        return output;
    }

    private String runCommandAndExtract(String command,
            String startPattern, boolean startInclusive,
            String endPattern, boolean endInclusive) throws Exception {
        final String[] output = runCommand(command).split("\\n");
        final StringBuilder sb = new StringBuilder();

        final Pattern start = Pattern.compile(startPattern, Pattern.COMMENTS);
        final Pattern end = Pattern.compile(endPattern, Pattern.COMMENTS);

        boolean in = false;
        for (String s : output) {
            if (in) {
                if (end.matcher(s.trim()).find()) {
                    if (endInclusive) {
                        sb.append(s);
                        sb.append("\n");
                    }
                    break;
                }
                sb.append(s);
                sb.append("\n");
            } else {
                if (start.matcher(s.trim()).find()) {
                    if (startInclusive) {
                        sb.append(s);
                        sb.append("\n");
                    }
                    continue;
                }
                in = true;
            }
        }

        return sb.toString();
    }

    private void updateConstants(String settings) throws Exception {
        runCommand("settings put global " + APP_BINDING_SETTING + " '" + settings + "'");
    }

    private boolean isSmsCapable() throws Exception {
        String output = runCommand("dumpsys phone");
        if (output.contains("isSmsCapable=true")) {
            CLog.d("Device is SMS capable");
            return true;
        }
        CLog.d("Device is not SMS capable");
        return false;
    }

    private void setSmsApp(String pkg, int userId) throws Throwable {
        runWithRetries(300, () -> {
            String output1 = runCommand("cmd role get-role-holders --user " + userId
                            + " android.app.role.SMS ");
            if (output1.equals(pkg)) {
                CLog.d(pkg + " has been set default sms app.");
            } else {
                String output2 = runCommand("cmd role add-role-holder --user " + userId
                                + " android.app.role.SMS " + pkg);
                if (output2.contains("TimeoutException")) {
                    RunUtil.getDefault().sleep(10000);
                    throw new RuntimeException("cmd role add-role-holder timeout.");
                }
            }
        });
    }

    private void uninstallTestApps(boolean always) throws Exception {
        if (SKIP_UNINSTALL && !always) {
            return;
        }
        getDevice().uninstallPackage(PACKAGE_A);
        getDevice().uninstallPackage(PACKAGE_B);

        waitForBroadcastIdle();
    }

    private void runWithRetries(int timeoutSeconds, ThrowingRunnable r) throws Throwable {
        final long timeout = System.currentTimeMillis() + timeoutSeconds * 1000;
        Throwable lastThrowable = null;

        int sleep = 200;
        while (System.currentTimeMillis() < timeout) {
            try {
                r.run();
                return;
            } catch (Throwable th) {
                lastThrowable = th;
            }
            RunUtil.getDefault().sleep(sleep);
            sleep = Math.min(1000, sleep * 2);
        }
        throw lastThrowable;
    }

    @Before
    public void setUp() throws Exception {
        // Reset to the default setting.
        updateConstants(",");

        uninstallTestApps(true);

        mCurrentUserId = getDevice().getCurrentUser();
    }

    @After
    public void tearDown() throws Exception {
        uninstallTestApps(false);

        // Reset to the default setting.
        updateConstants(",");
    }

    private void installAndCheckBound(String apk, String packageName,
            String serviceClass, int userId) throws Throwable {
        // Install
        installAppAsUser(apk, true, userId);

        // Set as the default app
        setSmsApp(packageName, userId);

        checkBound(packageName, serviceClass, userId);
    }

    private void checkBound(String packageName, String serviceClass, int userId) throws Throwable {
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommand("dumpsys activity service " + packageName + "/" + serviceClass,
                    Pattern.quote("[" + packageName + "]") + " .* "
                    + Pattern.quote("[" + serviceClass + "]"));
        });

        // This should contain:
        // "conn,0,[Default SMS app],PACKAGE,CLASS,bound,connected"

        // The binding information is propagated asynchronously, so we need a retry here too.
        // (Even though the activity manager said it's already bound.)
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommand("dumpsys app_binding -s",
                    "^" + Pattern.quote("conn,[Default SMS app]," + userId + "," + packageName + ","
                            + serviceClass + ",bound,connected,"));
        });
    }

    private void installAndCheckNotBound(String apk, String packageName, int userId,
            String expectedErrorPattern) throws Throwable {
        // Install
        installAppAsUser(apk, true, userId);

        // Set as the default app
        setSmsApp(packageName, userId);

        checkNotBoundWithError(packageName, userId, expectedErrorPattern);
    }

    private void checkNotBoundWithError(String packageName, int userId,
            String expectedErrorPattern) throws Throwable {
        // This should contain:
        // "finder,0,[Default SMS app],PACKAGE,null,ERROR-MESSAGE"
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommand("dumpsys app_binding -s",
                    "^" + Pattern.quote("finder,[Default SMS app]," + userId + ","
                            + packageName + ",null,") + ".*"
                            + Pattern.quote(expectedErrorPattern) + ".*$");
        });
    }

    private void checkPackageNotBound(String packageName, int userId) throws Throwable {
        // This should contain:
        // "finder,0,[Default SMS app],DIFFERENT-PACKAGE,..."
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommand("dumpsys app_binding -s",
                    "^" + Pattern.quote("finder,[Default SMS app]," + userId + ",")
                            + "(?!" // Negative look ahead
                            + Pattern.quote(packageName + ",")
                            + ")");
        });
    }

    private void assertOomAdjustment(String packageName, String processName, int oomAdj)
            throws Exception {
        final String output = runCommandAndExtract("dumpsys activity -a p " + packageName,
                "\\sProcessRecord\\{.*\\:" + Pattern.quote(processName) + "\\/", false,
                "^\\s*oom:", true);
        /* Example:
ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)
  All known processes:
  *APP* UID 10196 ProcessRecord{ef7dd8f 29993:com.android.cts.appbinding.app:persistent/u0a196}
    user #0 uid=10196 gids={50196, 20196, 9997}
    mRequiredAbi=arm64-v8a instructionSet=null
    dir=/data/app/com.android.cts.appbinding.app-zvJ1Z44jYKxm-K0HLBRtLA==/base.apk publicDir=/da...
    packageList={com.android.cts.appbinding.app}
    compat={560dpi}
    thread=android.app.IApplicationThread$Stub$Proxy@a5181c
    pid=29993 starting=false
    lastActivityTime=-14s282ms lastPssTime=-14s316ms pssStatType=0 nextPssTime=+5s718ms
    adjSeq=35457 lruSeq=0 lastPss=0.00 lastSwapPss=0.00 lastCachedPss=0.00 lastCachedSwapPss=0.00
    procStateMemTracker: best=4 () / pending state=2 highest=2 1.0x
    cached=false empty=true
    oom: max=1001 curRaw=200 setRaw=200 cur=200 set=200
    mCurSchedGroup=2 setSchedGroup=2 systemNoUi=false trimMemoryLevel=0
    curProcState=4 mRepProcState=4 pssProcState=19 setProcState=4 lastStateTime=-14s282ms
    reportedInteraction=true time=-14s284ms
    startSeq=369
    lastRequestedGc=-14s283ms lastLowMemory=-14s283ms reportLowMemory=false
     Configuration={1.0 ?mcc?mnc [en_US] ldltr sw411dp w411dp h746dp 560dpi nrml long widecg ...
     OverrideConfiguration={0.0 ?mcc?mnc ?localeList ?layoutDir ?swdp ?wdp ?hdp ?density ?lsize ...
     mLastReportedConfiguration={0.0 ?mcc?mnc ?localeList ?layoutDir ?swdp ?wdp ?hdp ?density ...
    Services:
      - ServiceRecord{383eb86 u0 com.android.cts.appbinding.app/.MyService}
    Connected Providers:
      - 54bfc25/com.android.providers.settings/.SettingsProvider->29993:com.android.cts....

  Process LRU list (sorted by oom_adj, 50 total, non-act at 4, non-svc at 4):
    Proc #10: prcp  F/ /BFGS trm: 0 29993:com.android.cts.appbinding.app:persistent/u0a196 (service)
        com.android.cts.appbinding.app/.MyService<=Proc{1332:system/1000}
         */
        final Pattern pat = Pattern.compile("\\soom:\\s.* set=(\\d+)$", Pattern.MULTILINE);
        final Matcher m = pat.matcher(output);
        if (!m.find()) {
            fail("Unable to fild the oom: line for process " + processName);
        }
        final String oom = m.group(1);
        assertEquals("Unexpected oom adjustment:", String.valueOf(oomAdj), oom);
    }

    /**
     * Install APK 1 and make it the default SMS app and make sure the service gets bound.
     */
    @Test
    public void testSimpleBind1() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);
    }

    /**
     * Install APK 2 and make it the default SMS app and make sure the service gets bound.
     */
    @Test
    public void testSimpleBind2() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckBound(APK_2, PACKAGE_A, SERVICE_2, mCurrentUserId);
    }

    /**
     * Install APK B and make it the default SMS app and make sure the service gets bound.
     */
    @Test
    public void testSimpleBindB() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckBound(APK_B, PACKAGE_B, SERVICE_1, mCurrentUserId);
    }

    /**
     * APK 3 doesn't have a valid service to be bound.
     */
    @Test
    public void testSimpleNotBound3() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckNotBound(APK_3, PACKAGE_A, mCurrentUserId,
                "must be protected with android.permission.BIND_CARRIER_MESSAGING_CLIENT_SERVICE");
    }

    /**
     * APK 4 doesn't have a valid service to be bound.
     */
    @Test
    public void testSimpleNotBound4() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckNotBound(APK_4, PACKAGE_A, mCurrentUserId, "More than one");
    }

    /**
     * APK 5 doesn't have a valid service to be bound.
     */
    @Test
    public void testSimpleNotBound5() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckNotBound(APK_5, PACKAGE_A, mCurrentUserId,
                "Service with android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE not found");
    }

    /**
     * APK 6's service doesn't have android:process.
     */
    @Test
    public void testSimpleNotBound6() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckNotBound(APK_6, PACKAGE_A, mCurrentUserId,
                "Service must not run on the main process");
    }

    /**
     * Make sure when the SMS app gets updated, the service still gets bound correctly.
     */
    @Test
    public void testUpgrade() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        // Replace existing package without uninstalling.
        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);
        installAndCheckBound(APK_2, PACKAGE_A, SERVICE_2, mCurrentUserId);
        installAndCheckNotBound(APK_3, PACKAGE_A, mCurrentUserId,
                "must be protected with android.permission.BIND_CARRIER_MESSAGING_CLIENT_SERVICE");
        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);
        installAndCheckNotBound(APK_4, PACKAGE_A, mCurrentUserId, "More than one");
    }

    private void enableTargetService(boolean enable) throws DeviceNotAvailableException {
        runDeviceTests(new DeviceTestRunOptions(PACKAGE_A)
                .setTestClassName("com.android.cts.appbinding.app.MyEnabler")
                .setTestMethodName(enable ? "enableService" : "disableService")
                .setUserId(mCurrentUserId));
    }

    /**
     * Make sure the service responds to setComponentEnabled.
     */
    @Test
    public void testServiceEnabledByDefault() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);

        // Disable the component and now it should be unbound.

        enableTargetService(false);

        RunUtil.getDefault().sleep(2); // Technically not needed, but allow the system to handle the broadcast.

        checkNotBoundWithError(PACKAGE_A, mCurrentUserId,
                "Service with android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE not found");

        // Enable the component and now it should be bound.
        enableTargetService(true);

        RunUtil.getDefault().sleep(2); // Technically not needed, but allow the system to handle the broadcast.

        checkBound(PACKAGE_A, SERVICE_1, mCurrentUserId);
    }

    /**
     * Make sure the service responds to setComponentEnabled.
     */
    @Test
    public void testServiceDisabledByDefault() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        // The service is disabled by default, so not bound.
        installAndCheckNotBound(APK_7, PACKAGE_A, mCurrentUserId,
                "Service with android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE not found");

        // Enable the component and now it should be bound.
        enableTargetService(true);

        RunUtil.getDefault().sleep(2); // Technically not needed, but allow the system to handle the broadcast.

        checkBound(PACKAGE_A, SERVICE_1, mCurrentUserId);

        // Disable the component and now it should be unbound.

        enableTargetService(false);

        RunUtil.getDefault().sleep(2); // Technically not needed, but allow the system to handle the broadcast.

        checkNotBoundWithError(PACKAGE_A, mCurrentUserId,
                "Service with android.telephony.action.CARRIER_MESSAGING_CLIENT_SERVICE not found");
    }

    /**
     * Make sure when the SMS app is uninstalled, the binding will be gone.
     */
    @Test
    public void testUninstall() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        // Replace existing package without uninstalling.
        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);
        getDevice().uninstallPackage(PACKAGE_A);
        checkPackageNotBound(PACKAGE_A, mCurrentUserId);

        // Try with different APKs, just to make sure.
        installAndCheckBound(APK_B, PACKAGE_B, SERVICE_1, mCurrentUserId);
        getDevice().uninstallPackage(PACKAGE_B);
        checkPackageNotBound(PACKAGE_B, mCurrentUserId);

        installAndCheckBound(APK_2, PACKAGE_A, SERVICE_2, mCurrentUserId);
        getDevice().uninstallPackage(PACKAGE_A);
        checkPackageNotBound(PACKAGE_A, mCurrentUserId);
    }

    /**
     * Make sure when the SMS app changes, the service still gets bound correctly.
     */
    @Test
    public void testSwitchDefaultApp() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);
        installAndCheckBound(APK_B, PACKAGE_B, SERVICE_1, mCurrentUserId);
        installAndCheckBound(APK_2, PACKAGE_A, SERVICE_2, mCurrentUserId);
    }

    private void assertUserHasNoConnection(int userId) throws Throwable {
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommandAndNotMatch("dumpsys app_binding -s",
                    "^conn,\\[Default\\sSMS\\sapp\\]," + userId + ",");
        });
    }

    private void assertUserHasNoFinder(int userId) throws Throwable {
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommandAndNotMatch("dumpsys app_binding -s",
                    "^finder,\\[Default\\sSMS\\sapp\\]," + userId + ",");
        });
    }

    @Test
    public void testSecondaryUser() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        if (!getDevice().isMultiUserSupported()) {
            // device do not support multi-user.
            return;
        }

        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);

        final int userId = getDevice().createUser("test-user");
        try {
            getDevice().startUser(userId);

            // Install SMS app on the secondary user.
            installAndCheckBound(APK_B, PACKAGE_B, SERVICE_1, userId);

            // Package A should still be bound on user-0.
            checkBound(PACKAGE_A, SERVICE_1, mCurrentUserId);

            // Replace the app on the primary user with an invalid one.
            installAndCheckNotBound(APK_3, PACKAGE_A, mCurrentUserId,
                    "must be protected with android.permission.BIND_CARRIER_MESSAGING_CLIENT_SERVICE");

            // Secondary user should still have a valid connection.
            checkBound(PACKAGE_B, SERVICE_1, userId);

            // Upgrade test: Try with apk 1, and then upgrade to apk 2.
            installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, userId);
            installAndCheckBound(APK_2, PACKAGE_A, SERVICE_2, userId);

            // Stop the secondary user, now the binding should be gone.
            getDevice().stopUser(userId);

            // Now the connection should be removed.
            assertUserHasNoConnection(userId);

            // Start the secondary user again.
            getDevice().startUser(userId);

            // Now the binding should recover.
            runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
                checkBound(PACKAGE_A, SERVICE_2, userId);
            });

        } finally {
            getDevice().removeUser(userId);
        }
        assertUserHasNoConnection(userId);
        assertUserHasNoFinder(userId);
    }

    @Test
    public void testCrashAndAutoRebind() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        updateConstants(
                "service_reconnect_backoff_sec=5"
                + ",service_reconnect_backoff_increase=2"
                + ",service_reconnect_max_backoff_sec=1000"
                + ",service_stable_connection_threshold_sec=10");

        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);

        // Ensure the expected status.
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommand("dumpsys app_binding -s",
                    "^conn,\\[Default\\sSMS\\sapp\\]," + mCurrentUserId + ",.*,bound,connected"
                    + ",\\#con=1,\\#dis=0,\\#died=0,backoff=5000");
        });

        // Let the service crash.
        runCommand("dumpsys activity service " + PACKAGE_A + "/" + SERVICE_1 + " crash");

        // Now the connection disconnected and re-connected, so the counters increase.
        // In this case, because binder-died isn't called, so backoff won't increase.
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommand("dumpsys app_binding -s",
                    "^conn,\\[Default\\sSMS\\sapp\\]," + mCurrentUserId + ",.*,bound,connected"
                    + ",\\#con=2,\\#dis=1,\\#died=0,backoff=5000");
        });

        // Force-stop the app.
        runCommand("am force-stop " + PACKAGE_A);

        // Force-stop causes a disconnect and a binder-died. Then it doubles the backoff.
        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            runCommand("dumpsys app_binding -s",
                    "^conn,\\[Default\\sSMS\\sapp\\]," + mCurrentUserId + ",.*,not-bound,not-connected"
                    + ",\\#con=2,\\#dis=2,\\#died=1,backoff=10000");
        });

        RunUtil.getDefault().sleep(5000);

        // It should re-bind.
        runWithRetries(10, () -> {
            runCommand("dumpsys app_binding -s",
                    "^conn,\\[Default\\sSMS\\sapp\\]," + mCurrentUserId + ",.*,bound,connected"
                            + ",\\#con=3,\\#dis=2,\\#died=1,backoff=10000");
        });

        // Force-stop again.
        runCommand("am force-stop " + PACKAGE_A);

        runWithRetries(10, () -> {
            runCommand("dumpsys app_binding -s",
                    "^conn,\\[Default\\sSMS\\sapp\\]," + mCurrentUserId + ",.*,not-bound,not-connected"
                            + ",\\#con=3,\\#dis=3,\\#died=2,backoff=20000");
        });

        RunUtil.getDefault().sleep(10000);

        runWithRetries(10, () -> {
            runCommand("dumpsys app_binding -s",
                    "^conn,\\[Default\\sSMS\\sapp\\]," + mCurrentUserId + ",.*,bound,connected"
                            + ",\\#con=4,\\#dis=3,\\#died=2,backoff=20000");
        });

        // If the connection lasts more than service_stable_connection_threshold_sec seconds,
        // the backoff resets.
        RunUtil.getDefault().sleep(10000);

        runWithRetries(10, () -> {
            runCommand("dumpsys app_binding -s",
                    "^conn,\\[Default\\sSMS\\sapp\\]," + mCurrentUserId + ",.*,bound,connected"
                            + ",\\#con=4,\\#dis=3,\\#died=2,backoff=5000");
        });
    }

    /**
     * Test the feature flag.
     */
    @Test
    public void testFeatureDisabled() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);

        updateConstants("sms_service_enabled=false");

        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            checkNotBoundWithError("null", mCurrentUserId, "feature disabled");
        });

        updateConstants("sms_service_enabled=true");

        runWithRetries(DEFAULT_TIMEOUT_SEC, () -> {
            checkBound(PACKAGE_A, SERVICE_1, mCurrentUserId);
        });
    }

    @Test
    public void testOomAdjustment() throws Throwable {
        if (!isSmsCapable()) {
            // device not supporting sms. cannot run the test.
            return;
        }

        installAndCheckBound(APK_1, PACKAGE_A, SERVICE_1, mCurrentUserId);
        assertOomAdjustment(PACKAGE_A, PACKAGE_A_PROC, 200);
    }
}