Debian Codegraph @

core/java/android/app/UiAutomationConnection.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2013 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 android.app;
18
19 import android.accessibilityservice.AccessibilityServiceInfo;
20 import android.accessibilityservice.IAccessibilityServiceClient;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.compat.annotation.UnsupportedAppUsage;
24 import android.content.Context;
25 import android.graphics.Bitmap;
26 import android.graphics.Rect;
27 import android.hardware.input.InputManager;
28 import android.os.Binder;
29 import android.os.Build;
30 import android.os.IBinder;
31 import android.os.ParcelFileDescriptor;
32 import android.os.Process;
33 import android.os.RemoteException;
34 import android.os.ServiceManager;
35 import android.os.UserHandle;
36 import android.permission.IPermissionManager;
37 import android.util.Log;
38 import android.view.IWindowManager;
39 import android.view.InputDevice;
40 import android.view.InputEvent;
41 import android.view.KeyEvent;
42 import android.view.MotionEvent;
43 import android.view.SurfaceControl;
44 import android.view.WindowAnimationFrameStats;
45 import android.view.WindowContentFrameStats;
46 import android.view.accessibility.AccessibilityEvent;
47 import android.view.accessibility.IAccessibilityManager;
48
49 import libcore.io.IoUtils;
50
51 import java.io.FileInputStream;
52 import java.io.FileOutputStream;
53 import java.io.IOException;
54 import java.io.InputStream;
55 import java.io.OutputStream;
56 import java.util.List;
57
58 /**
59 * This is a remote object that is passed from the shell to an instrumentation
60 * for enabling access to privileged operations which the shell can do and the
61 * instrumentation cannot. These privileged operations are needed for implementing
62 * a {@link UiAutomation} that enables across application testing by simulating
63 * user actions and performing screen introspection.
64 *
65 * @hide
66 */
67 public final class UiAutomationConnection extends IUiAutomationConnection.Stub {
68
69 private static final String TAG = "UiAutomationConnection";
70
71 private static final int INITIAL_FROZEN_ROTATION_UNSPECIFIED = -1;
72
73 private final IWindowManager mWindowManager = IWindowManager.Stub.asInterface(
74 ServiceManager.getService(Service.WINDOW_SERVICE));
75
76 private final IAccessibilityManager mAccessibilityManager = IAccessibilityManager.Stub
77 .asInterface(ServiceManager.getService(Service.ACCESSIBILITY_SERVICE));
78
79 private final IPermissionManager mPermissionManager = IPermissionManager.Stub
80 .asInterface(ServiceManager.getService("permissionmgr"));
81
82 private final IActivityManager mActivityManager = IActivityManager.Stub
83 .asInterface(ServiceManager.getService("activity"));
84
85 private final Object mLock = new Object();
86
87 private final Binder mToken = new Binder();
88
89 private int mInitialFrozenRotation = INITIAL_FROZEN_ROTATION_UNSPECIFIED;
90
91 private IAccessibilityServiceClient mClient;
92
93 private boolean mIsShutdown;
94
95 private int mOwningUid;
96
97 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
98 public UiAutomationConnection() {
99 }
100
101 @Override
102 public void connect(IAccessibilityServiceClient client, int flags) {
103 if (client == null) {
104 throw new IllegalArgumentException("Client cannot be null!");
105 }
106 synchronized (mLock) {
107 throwIfShutdownLocked();
108 if (isConnectedLocked()) {
109 throw new IllegalStateException("Already connected.");
110 }
111 mOwningUid = Binder.getCallingUid();
112 registerUiTestAutomationServiceLocked(client, flags);
113 storeRotationStateLocked();
114 }
115 }
116
117 @Override
118 public void disconnect() {
119 synchronized (mLock) {
120 throwIfCalledByNotTrustedUidLocked();
121 throwIfShutdownLocked();
122 if (!isConnectedLocked()) {
123 throw new IllegalStateException("Already disconnected.");
124 }
125 mOwningUid = -1;
126 unregisterUiTestAutomationServiceLocked();
127 restoreRotationStateLocked();
128 }
129 }
130
131 @Override
132 public boolean injectInputEvent(InputEvent event, boolean sync, boolean waitForAnimations) {
133 synchronized (mLock) {
134 throwIfCalledByNotTrustedUidLocked();
135 throwIfShutdownLocked();
136 throwIfNotConnectedLocked();
137 }
138
139 final boolean syncTransactionsBefore;
140 final boolean syncTransactionsAfter;
141 if (event instanceof KeyEvent) {
142 KeyEvent keyEvent = (KeyEvent) event;
143 syncTransactionsBefore = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
144 syncTransactionsAfter = keyEvent.getAction() == KeyEvent.ACTION_UP;
145 } else {
146 MotionEvent motionEvent = (MotionEvent) event;
147 syncTransactionsBefore = motionEvent.getAction() == MotionEvent.ACTION_DOWN
148 || motionEvent.isFromSource(InputDevice.SOURCE_MOUSE);
149 syncTransactionsAfter = motionEvent.getAction() == MotionEvent.ACTION_UP;
150 }
151
152 final long identity = Binder.clearCallingIdentity();
153 try {
154 if (syncTransactionsBefore) {
155 mWindowManager.syncInputTransactions(waitForAnimations);
156 }
157
158 final boolean result = InputManager.getInstance().injectInputEvent(event,
159 sync ? InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
160 : InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
161
162 if (syncTransactionsAfter) {
163 mWindowManager.syncInputTransactions(waitForAnimations);
164 }
165 return result;
166 } catch (RemoteException e) {
167 e.rethrowFromSystemServer();
168 } finally {
169 Binder.restoreCallingIdentity(identity);
170 }
171 return false;
172 }
173
174 @Override
175 public void syncInputTransactions(boolean waitForAnimations) {
176 synchronized (mLock) {
177 throwIfCalledByNotTrustedUidLocked();
178 throwIfShutdownLocked();
179 throwIfNotConnectedLocked();
180 }
181
182 try {
183 mWindowManager.syncInputTransactions(waitForAnimations);
184 } catch (RemoteException e) {
185 }
186 }
187
188 @Override
189 public boolean setRotation(int rotation) {
190 synchronized (mLock) {
191 throwIfCalledByNotTrustedUidLocked();
192 throwIfShutdownLocked();
193 throwIfNotConnectedLocked();
194 }
195 final long identity = Binder.clearCallingIdentity();
196 try {
197 if (rotation == UiAutomation.ROTATION_UNFREEZE) {
198 mWindowManager.thawRotation();
199 } else {
200 mWindowManager.freezeRotation(rotation);
201 }
202 return true;
203 } catch (RemoteException re) {
204 /* ignore */
205 } finally {
206 Binder.restoreCallingIdentity(identity);
207 }
208 return false;
209 }
210
211 @Override
212 public Bitmap takeScreenshot(Rect crop) {
213 synchronized (mLock) {
214 throwIfCalledByNotTrustedUidLocked();
215 throwIfShutdownLocked();
216 throwIfNotConnectedLocked();
217 }
218 final long identity = Binder.clearCallingIdentity();
219 try {
220 int width = crop.width();
221 int height = crop.height();
222 final IBinder displayToken = SurfaceControl.getInternalDisplayToken();
223 final SurfaceControl.DisplayCaptureArgs captureArgs =
224 new SurfaceControl.DisplayCaptureArgs.Builder(displayToken)
225 .setSourceCrop(crop)
226 .setSize(width, height)
227 .build();
228 final SurfaceControl.ScreenshotHardwareBuffer screenshotBuffer =
229 SurfaceControl.captureDisplay(captureArgs);
230 return screenshotBuffer == null ? null : screenshotBuffer.asBitmap();
231 } finally {
232 Binder.restoreCallingIdentity(identity);
233 }
234 }
235
236 @Nullable
237 @Override
238 public Bitmap takeSurfaceControlScreenshot(@NonNull SurfaceControl surfaceControl) {
239 synchronized (mLock) {
240 throwIfCalledByNotTrustedUidLocked();
241 throwIfShutdownLocked();
242 throwIfNotConnectedLocked();
243 }
244
245 SurfaceControl.ScreenshotHardwareBuffer captureBuffer;
246 final long identity = Binder.clearCallingIdentity();
247 try {
248 captureBuffer = SurfaceControl.captureLayers(
249 new SurfaceControl.LayerCaptureArgs.Builder(surfaceControl)
250 .setChildrenOnly(false)
251 .build());
252 } finally {
253 Binder.restoreCallingIdentity(identity);
254 }
255
256 if (captureBuffer == null) {
257 return null;
258 }
259 return captureBuffer.asBitmap();
260 }
261
262 @Override
263 public boolean clearWindowContentFrameStats(int windowId) throws RemoteException {
264 synchronized (mLock) {
265 throwIfCalledByNotTrustedUidLocked();
266 throwIfShutdownLocked();
267 throwIfNotConnectedLocked();
268 }
269 int callingUserId = UserHandle.getCallingUserId();
270 final long identity = Binder.clearCallingIdentity();
271 try {
272 IBinder token = mAccessibilityManager.getWindowToken(windowId, callingUserId);
273 if (token == null) {
274 return false;
275 }
276 return mWindowManager.clearWindowContentFrameStats(token);
277 } finally {
278 Binder.restoreCallingIdentity(identity);
279 }
280 }
281
282 @Override
283 public WindowContentFrameStats getWindowContentFrameStats(int windowId) throws RemoteException {
284 synchronized (mLock) {
285 throwIfCalledByNotTrustedUidLocked();
286 throwIfShutdownLocked();
287 throwIfNotConnectedLocked();
288 }
289 int callingUserId = UserHandle.getCallingUserId();
290 final long identity = Binder.clearCallingIdentity();
291 try {
292 IBinder token = mAccessibilityManager.getWindowToken(windowId, callingUserId);
293 if (token == null) {
294 return null;
295 }
296 return mWindowManager.getWindowContentFrameStats(token);
297 } finally {
298 Binder.restoreCallingIdentity(identity);
299 }
300 }
301
302 @Override
303 public void clearWindowAnimationFrameStats() {
304 synchronized (mLock) {
305 throwIfCalledByNotTrustedUidLocked();
306 throwIfShutdownLocked();
307 throwIfNotConnectedLocked();
308 }
309 final long identity = Binder.clearCallingIdentity();
310 try {
311 SurfaceControl.clearAnimationFrameStats();
312 } finally {
313 Binder.restoreCallingIdentity(identity);
314 }
315 }
316
317 @Override
318 public WindowAnimationFrameStats getWindowAnimationFrameStats() {
319 synchronized (mLock) {
320 throwIfCalledByNotTrustedUidLocked();
321 throwIfShutdownLocked();
322 throwIfNotConnectedLocked();
323 }
324 final long identity = Binder.clearCallingIdentity();
325 try {
326 WindowAnimationFrameStats stats = new WindowAnimationFrameStats();
327 SurfaceControl.getAnimationFrameStats(stats);
328 return stats;
329 } finally {
330 Binder.restoreCallingIdentity(identity);
331 }
332 }
333
334 @Override
335 public void grantRuntimePermission(String packageName, String permission, int userId)
336 throws RemoteException {
337 synchronized (mLock) {
338 throwIfCalledByNotTrustedUidLocked();
339 throwIfShutdownLocked();
340 throwIfNotConnectedLocked();
341 }
342 final long identity = Binder.clearCallingIdentity();
343 try {
344 mPermissionManager.grantRuntimePermission(packageName, permission, userId);
345 } finally {
346 Binder.restoreCallingIdentity(identity);
347 }
348 }
349
350 @Override
351 public void revokeRuntimePermission(String packageName, String permission, int userId)
352 throws RemoteException {
353 synchronized (mLock) {
354 throwIfCalledByNotTrustedUidLocked();
355 throwIfShutdownLocked();
356 throwIfNotConnectedLocked();
357 }
358 final long identity = Binder.clearCallingIdentity();
359 try {
360 mPermissionManager.revokeRuntimePermission(packageName, permission, userId, null);
361 } finally {
362 Binder.restoreCallingIdentity(identity);
363 }
364 }
365
366 @Override
367 public void adoptShellPermissionIdentity(int uid, @Nullable String[] permissions)
368 throws RemoteException {
369 synchronized (mLock) {
370 throwIfCalledByNotTrustedUidLocked();
371 throwIfShutdownLocked();
372 throwIfNotConnectedLocked();
373 }
374 final long identity = Binder.clearCallingIdentity();
375 try {
376 mActivityManager.startDelegateShellPermissionIdentity(uid, permissions);
377 } finally {
378 Binder.restoreCallingIdentity(identity);
379 }
380 }
381
382 @Override
383 public void dropShellPermissionIdentity() throws RemoteException {
384 synchronized (mLock) {
385 throwIfCalledByNotTrustedUidLocked();
386 throwIfShutdownLocked();
387 throwIfNotConnectedLocked();
388 }
389 final long identity = Binder.clearCallingIdentity();
390 try {
391 mActivityManager.stopDelegateShellPermissionIdentity();
392 } finally {
393 Binder.restoreCallingIdentity(identity);
394 }
395 }
396
397 @Override
398 @Nullable
399 public List<String> getAdoptedShellPermissions() throws RemoteException {
400 synchronized (mLock) {
401 throwIfCalledByNotTrustedUidLocked();
402 throwIfShutdownLocked();
403 throwIfNotConnectedLocked();
404 }
405 final long identity = Binder.clearCallingIdentity();
406 try {
407 return mActivityManager.getDelegatedShellPermissions();
408 } finally {
409 Binder.restoreCallingIdentity(identity);
410 }
411 }
412
413 public class Repeater implements Runnable {
414 // Continuously read readFrom and write back to writeTo until EOF is encountered
415 private final InputStream readFrom;
416 private final OutputStream writeTo;
417 public Repeater (InputStream readFrom, OutputStream writeTo) {
418 this.readFrom = readFrom;
419 this.writeTo = writeTo;
420 }
421 @Override
422 public void run() {
423 try {
424 final byte[] buffer = new byte[8192];
425 int readByteCount;
426 while (true) {
427 readByteCount = readFrom.read(buffer);
428 if (readByteCount < 0) {
429 break;
430 }
431 writeTo.write(buffer, 0, readByteCount);
432 writeTo.flush();
433 }
434 } catch (IOException ioe) {
435 Log.w(TAG, "Error while reading/writing to streams");
436 } finally {
437 IoUtils.closeQuietly(readFrom);
438 IoUtils.closeQuietly(writeTo);
439 }
440 }
441 }
442
443 @Override
444 public void executeShellCommand(final String command, final ParcelFileDescriptor sink,
445 final ParcelFileDescriptor source) throws RemoteException {
446 executeShellCommandWithStderr(command, sink, source, null /* stderrSink */);
447 }
448
449 @Override
450 public void executeShellCommandWithStderr(final String command, final ParcelFileDescriptor sink,
451 final ParcelFileDescriptor source, final ParcelFileDescriptor stderrSink)
452 throws RemoteException {
453 synchronized (mLock) {
454 throwIfCalledByNotTrustedUidLocked();
455 throwIfShutdownLocked();
456 throwIfNotConnectedLocked();
457 }
458 final java.lang.Process process;
459
460 try {
461 process = Runtime.getRuntime().exec(command);
462 } catch (IOException exc) {
463 throw new RuntimeException("Error running shell command '" + command + "'", exc);
464 }
465
466 // Read from process and write to pipe
467 final Thread readFromProcess;
468 if (sink != null) {
469 InputStream sink_in = process.getInputStream();;
470 OutputStream sink_out = new FileOutputStream(sink.getFileDescriptor());
471
472 readFromProcess = new Thread(new Repeater(sink_in, sink_out));
473 readFromProcess.start();
474 } else {
475 readFromProcess = null;
476 }
477
478 // Read from pipe and write to process
479 final Thread writeToProcess;
480 if (source != null) {
481 OutputStream source_out = process.getOutputStream();
482 InputStream source_in = new FileInputStream(source.getFileDescriptor());
483
484 writeToProcess = new Thread(new Repeater(source_in, source_out));
485 writeToProcess.start();
486 } else {
487 writeToProcess = null;
488 }
489
490 // Read from process stderr and write to pipe
491 final Thread readStderrFromProcess;
492 if (stderrSink != null) {
493 InputStream sink_in = process.getErrorStream();
494 OutputStream sink_out = new FileOutputStream(stderrSink.getFileDescriptor());
495
496 readStderrFromProcess = new Thread(new Repeater(sink_in, sink_out));
497 readStderrFromProcess.start();
498 } else {
499 readStderrFromProcess = null;
500 }
501
502 Thread cleanup = new Thread(new Runnable() {
503 @Override
504 public void run() {
505 try {
506 if (writeToProcess != null) {
507 writeToProcess.join();
508 }
509 if (readFromProcess != null) {
510 readFromProcess.join();
511 }
512 if (readStderrFromProcess != null) {
513 readStderrFromProcess.join();
514 }
515 } catch (InterruptedException exc) {
516 Log.e(TAG, "At least one of the threads was interrupted");
517 }
518 IoUtils.closeQuietly(sink);
519 IoUtils.closeQuietly(source);
520 IoUtils.closeQuietly(stderrSink);
521 process.destroy();
522 }
523 });
524 cleanup.start();
525 }
526
527 @Override
528 public void shutdown() {
529 synchronized (mLock) {
530 if (isConnectedLocked()) {
531 throwIfCalledByNotTrustedUidLocked();
532 }
533 throwIfShutdownLocked();
534 mIsShutdown = true;
535 if (isConnectedLocked()) {
536 disconnect();
537 }
538 }
539 }
540
541 private void registerUiTestAutomationServiceLocked(IAccessibilityServiceClient client,
542 int flags) {
543 IAccessibilityManager manager = IAccessibilityManager.Stub.asInterface(
544 ServiceManager.getService(Context.ACCESSIBILITY_SERVICE));
545 final AccessibilityServiceInfo info = new AccessibilityServiceInfo();
546 info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
547 info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
548 info.flags |= AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
549 | AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS
550 | AccessibilityServiceInfo.FLAG_FORCE_DIRECT_BOOT_AWARE;
551 info.setCapabilities(AccessibilityServiceInfo.CAPABILITY_CAN_RETRIEVE_WINDOW_CONTENT
552 | AccessibilityServiceInfo.CAPABILITY_CAN_REQUEST_TOUCH_EXPLORATION
553 | AccessibilityServiceInfo.CAPABILITY_CAN_REQUEST_ENHANCED_WEB_ACCESSIBILITY
554 | AccessibilityServiceInfo.CAPABILITY_CAN_REQUEST_FILTER_KEY_EVENTS);
555 try {
556 // Calling out with a lock held is fine since if the system
557 // process is gone the client calling in will be killed.
558 manager.registerUiTestAutomationService(mToken, client, info, flags);
559 mClient = client;
560 } catch (RemoteException re) {
561 throw new IllegalStateException("Error while registering UiTestAutomationService.", re);
562 }
563 }
564
565 private void unregisterUiTestAutomationServiceLocked() {
566 IAccessibilityManager manager = IAccessibilityManager.Stub.asInterface(
567 ServiceManager.getService(Context.ACCESSIBILITY_SERVICE));
568 try {
569 // Calling out with a lock held is fine since if the system
570 // process is gone the client calling in will be killed.
571 manager.unregisterUiTestAutomationService(mClient);
572 mClient = null;
573 } catch (RemoteException re) {
574 throw new IllegalStateException("Error while unregistering UiTestAutomationService",
575 re);
576 }
577 }
578
579 private void storeRotationStateLocked() {
580 try {
581 if (mWindowManager.isRotationFrozen()) {
582 // Calling out with a lock held is fine since if the system
583 // process is gone the client calling in will be killed.
584 mInitialFrozenRotation = mWindowManager.getDefaultDisplayRotation();
585 }
586 } catch (RemoteException re) {
587 /* ignore */
588 }
589 }
590
591 private void restoreRotationStateLocked() {
592 try {
593 if (mInitialFrozenRotation != INITIAL_FROZEN_ROTATION_UNSPECIFIED) {
594 // Calling out with a lock held is fine since if the system
595 // process is gone the client calling in will be killed.
596 mWindowManager.freezeRotation(mInitialFrozenRotation);
597 } else {
598 // Calling out with a lock held is fine since if the system
599 // process is gone the client calling in will be killed.
600 mWindowManager.thawRotation();
601 }
602 } catch (RemoteException re) {
603 /* ignore */
604 }
605 }
606
607 private boolean isConnectedLocked() {
608 return mClient != null;
609 }
610
611 private void throwIfShutdownLocked() {
612 if (mIsShutdown) {
613 throw new IllegalStateException("Connection shutdown!");
614 }
615 }
616
617 private void throwIfNotConnectedLocked() {
618 if (!isConnectedLocked()) {
619 throw new IllegalStateException("Not connected!");
620 }
621 }
622
623 private void throwIfCalledByNotTrustedUidLocked() {
624 final int callingUid = Binder.getCallingUid();
625 if (callingUid != mOwningUid && mOwningUid != Process.SYSTEM_UID
626 && callingUid != 0 /*root*/) {
627 throw new SecurityException("Calling from not trusted UID!");
628 }
629 }
630 }