1 /* 2 * Copyright (C) 2024 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.xts.apimapper.helper; 18 19 import java.util.Objects; 20 21 /** 22 * Hook for recording potential API calls. 23 */ 24 public final class DeviceMethodCallHook { 25 26 // Used by method calls that are not triggered in the main test process, e.g. install another 27 // apk and do some actions in that apk. 28 private static final DeviceApiMapperHelperRule sHelpRule = 29 new DeviceApiMapperHelperRule(true); 30 31 private static OnBeforeCallListener sListener = null; 32 33 /** Add the given listener when the test starts. */ addOnBeforeCallListener(OnBeforeCallListener listener)34 public static void addOnBeforeCallListener(OnBeforeCallListener listener) { 35 sListener = Objects.requireNonNull(listener); 36 } 37 38 /** Clear the given listener when the test ends. */ removeOnBeforeCallListener()39 public static void removeOnBeforeCallListener() { 40 sListener = null; 41 } 42 43 /** Called by ASM-generated code. */ onBeforeCall(String callerClass, String callerMethod, int opcode, String methodOwner, String methodName, String descriptor, Object receiverObject)44 public static void onBeforeCall(String callerClass, String callerMethod, int opcode, 45 String methodOwner, String methodName, String descriptor, Object receiverObject) { 46 // Log APIs called by non-test classes, e.g. android activities. 47 if (sListener == null) { 48 sHelpRule.logMethodCall( 49 callerClass, callerMethod, opcode, 50 methodOwner, methodName, descriptor, receiverObject); 51 } else { 52 sListener.onBeforeCall(callerClass, callerMethod, opcode, 53 methodOwner, methodName, descriptor, receiverObject); 54 } 55 } 56 } 57