1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.testutils;
18 
19 import static com.android.testutils.TestPermissionUtil.runAsShell;
20 
21 import static org.junit.Assert.assertTrue;
22 import static org.junit.Assert.fail;
23 
24 import android.os.IBinder;
25 import android.os.RemoteException;
26 import android.os.ServiceManager;
27 import android.system.ErrnoException;
28 import android.system.Os;
29 
30 import libcore.io.IoUtils;
31 import libcore.io.Streams;
32 
33 import java.io.FileDescriptor;
34 import java.io.FileInputStream;
35 import java.io.InputStreamReader;
36 import java.nio.charset.StandardCharsets;
37 import java.util.Arrays;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.TimeUnit;
40 import java.util.concurrent.atomic.AtomicReference;
41 
42 /**
43  * Utilities for testing output of service dumps.
44  */
45 public class DumpTestUtils {
46 
dumpService(String serviceName, boolean adoptPermission, String... args)47     private static String dumpService(String serviceName, boolean adoptPermission, String... args)
48             throws RemoteException, InterruptedException, ErrnoException {
49         final IBinder ib = ServiceManager.getService(serviceName);
50         FileDescriptor[] pipe = Os.pipe();
51 
52         // Start a thread to read the dump output, or dump might block if it fills the pipe.
53         final CountDownLatch latch = new CountDownLatch(1);
54         AtomicReference<String> output = new AtomicReference<>();
55         // Used to send exceptions back to the main thread to ensure that the test fails cleanly.
56         AtomicReference<Exception> exception = new AtomicReference<>();
57         new Thread(() -> {
58             try {
59                 output.set(Streams.readFully(
60                         new InputStreamReader(new FileInputStream(pipe[0]),
61                                 StandardCharsets.UTF_8)));
62                 latch.countDown();
63             } catch (Exception e) {
64                 exception.set(e);
65                 latch.countDown();
66             }
67         }).start();
68 
69         final int timeoutMs = 5_000;
70         final String what = "service '" + serviceName + "' with args: " + Arrays.toString(args);
71         try {
72             if (adoptPermission) {
73                 runAsShell(android.Manifest.permission.DUMP, () -> ib.dump(pipe[1], args));
74             } else {
75                 ib.dump(pipe[1], args);
76             }
77             IoUtils.closeQuietly(pipe[1]);
78             assertTrue("Dump of " + what + " timed out after " + timeoutMs + "ms",
79                     latch.await(timeoutMs, TimeUnit.MILLISECONDS));
80         } finally {
81             // Closing the fds will terminate the thread if it's blocked on read.
82             IoUtils.closeQuietly(pipe[0]);
83             if (pipe[1].valid()) IoUtils.closeQuietly(pipe[1]);
84         }
85         if (exception.get() != null) {
86             fail("Exception dumping " + what + ": " + exception.get());
87         }
88         return output.get();
89     }
90 
91     /**
92      * Dumps the specified service and returns a string. Sends a dump IPC to the given service
93      * with the specified args and a pipe, then reads from the pipe in a separate thread.
94      * The current process must already have the DUMP permission.
95      *
96      * @param serviceName the service to dump.
97      * @param args the arguments to pass to the dump function.
98      * @return The dump text.
99      * @throws RemoteException dumping the service failed.
100      * @throws InterruptedException the dump timed out.
101      * @throws ErrnoException opening or closing the pipe for the dump failed.
102      */
dumpService(String serviceName, String... args)103     public static String dumpService(String serviceName, String... args)
104             throws RemoteException, InterruptedException, ErrnoException {
105         return dumpService(serviceName, false, args);
106     }
107 
108     /**
109      * Dumps the specified service and returns a string. Sends a dump IPC to the given service
110      * with the specified args and a pipe, then reads from the pipe in a separate thread.
111      * Adopts the {@code DUMP} permission via {@code adoptShellPermissionIdentity} and then releases
112      * it. This method should not be used if the caller already has the shell permission identity.
113      * TODO: when Q and R are no longer supported, use
114      * {@link android.app.UiAutomation#getAdoptedShellPermissions} to automatically acquire the
115      * shell permission if the caller does not already have it.
116      *
117      * @param serviceName the service to dump.
118      * @param args the arguments to pass to the dump function.
119      * @return The dump text.
120      * @throws RemoteException dumping the service failed.
121      * @throws InterruptedException the dump timed out.
122      * @throws ErrnoException opening or closing the pipe for the dump failed.
123      */
dumpServiceWithShellPermission(String serviceName, String... args)124     public static String dumpServiceWithShellPermission(String serviceName, String... args)
125             throws RemoteException, InterruptedException, ErrnoException {
126         return dumpService(serviceName, true, args);
127     }
128 }
129