1 /* 2 * Copyright (C) 2018 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.server.testing.shadows; 18 19 import android.os.Binder; 20 import android.os.UserHandle; 21 22 import org.robolectric.annotation.Implementation; 23 import org.robolectric.annotation.Implements; 24 import org.robolectric.annotation.Resetter; 25 26 /** 27 * Extends {@link org.robolectric.shadows.ShadowBinder} with {@link Binder#clearCallingIdentity()} 28 * and {@link Binder#restoreCallingIdentity(long)}. Uses a hardcoded default {@link #LOCAL_UID} to 29 * mimic the local process uid. 30 */ 31 @Implements(Binder.class) 32 public class ShadowBinder extends org.robolectric.shadows.ShadowBinder { 33 public static final Integer LOCAL_UID = 1000; 34 private static Integer originalCallingUid; 35 private static UserHandle sCallingUserHandle; 36 37 @Implementation clearCallingIdentity()38 protected static long clearCallingIdentity() { 39 originalCallingUid = getCallingUid(); 40 setCallingUid(LOCAL_UID); 41 return 1L; 42 } 43 44 @Implementation restoreCallingIdentity(long token)45 protected static void restoreCallingIdentity(long token) { 46 setCallingUid(originalCallingUid); 47 } 48 setCallingUserHandle(UserHandle userHandle)49 public static void setCallingUserHandle(UserHandle userHandle) { 50 sCallingUserHandle = userHandle; 51 } 52 53 /** 54 * Shadows {@link Binder#getCallingUserHandle()}. If {@link ShadowBinder#sCallingUserHandle} 55 * is set, return that; otherwise mimic the default implementation. 56 */ 57 @Implementation getCallingUserHandle()58 public static UserHandle getCallingUserHandle() { 59 if (sCallingUserHandle != null) { 60 return sCallingUserHandle; 61 } else { 62 return UserHandle.of(UserHandle.getUserId(getCallingUid())); 63 } 64 } 65 66 /** 67 * Clean up and reset state that was created for testing. 68 */ 69 @Resetter reset()70 public static void reset() { 71 sCallingUserHandle = null; 72 org.robolectric.shadows.ShadowBinder.reset(); 73 } 74 } 75