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 package android.signature.cts;
17 
18 import java.lang.reflect.Method;
19 import java.lang.reflect.Modifier;
20 import java.util.ArrayList;
21 import java.util.Comparator;
22 import java.util.HashSet;
23 import java.util.LinkedHashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.TreeMap;
28 import java.util.function.Predicate;
29 import java.util.stream.Collectors;
30 import java.util.stream.Stream;
31 
32 /**
33  * Checks that the runtime representation of the interfaces match the API definition.
34  *
35  * <p>Interfaces are treated differently to other classes. Whereas other classes are checked by
36  * making sure that every member in the API is accessible through reflection. Interfaces are
37  * checked to make sure that every method visible through reflection is defined in the API. The
38  * reason for this difference is to ensure that no additional methods have been added to interfaces
39  * that are expected to be implemented by Android developers because that would break backwards
40  * compatibility.
41  *
42  * TODO(b/71886491): This also potentially applies to abstract classes that the App developers are
43  * expected to extend.
44  */
45 class InterfaceChecker {
46 
47     private static final Set<String> HIDDEN_INTERFACE_METHOD_ALLOW_LIST = new HashSet<>();
48     static {
49         // Interfaces that define @hide or @SystemApi or @TestApi methods will by definition contain
50         // methods that do not appear in current.txt but do appear at runtime. That means that those
51         // interfaces will fail compatibility checking because a developer could never implement all
52         // the methods in the interface. However, some interfaces are not intended to be implemented
53         // by a developer and so additional methods in the runtime class will not cause
54         // compatibility errors. Unfortunately, this checker has no way to determine from the
55         // interface whether an interface is intended to be implemented by a developer and for
56         // safety's sake assumes that all interfaces are.
57         //
58         // Additional methods that are provided by the runtime but are not in the API specification
59         // must be listed here to prevent them from being reported as errors.
60         //
61         // TODO(b/71886491): Avoid the need for this allow list.
62         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract boolean android.companion.DeviceFilter.matches(D)");
63         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public static <D> boolean android.companion.DeviceFilter.matches(android.companion.DeviceFilter<D>,D)");
64         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract java.lang.String android.companion.DeviceFilter.getDeviceDisplayName(D)");
65         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract int android.companion.DeviceFilter.getMediumType()");
66         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract void android.nfc.tech.TagTechnology.reconnect() throws java.io.IOException");
67         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract void android.os.IBinder.shellCommand(java.io.FileDescriptor,java.io.FileDescriptor,java.io.FileDescriptor,java.lang.String[],android.os.ShellCallback,android.os.ResultReceiver) throws android.os.RemoteException");
68         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract int android.text.ParcelableSpan.getSpanTypeIdInternal()");
69         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract void android.text.ParcelableSpan.writeToParcelInternal(android.os.Parcel,int)");
70         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract void android.view.WindowManager.requestAppKeyboardShortcuts(android.view.WindowManager$KeyboardShortcutsReceiver,int)");
71         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract boolean javax.microedition.khronos.egl.EGL10.eglReleaseThread()");
72         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract void org.w3c.dom.ls.LSSerializer.setFilter(org.w3c.dom.ls.LSSerializerFilter)");
73         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract org.w3c.dom.ls.LSSerializerFilter org.w3c.dom.ls.LSSerializer.getFilter()");
74         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract android.graphics.Region android.view.WindowManager.getCurrentImeTouchRegion()");
75         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract java.util.Set<android.media.AudioMetadata$Key<?>> android.media.AudioMetadataReadMap.keySet()");
76         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract android.view.InsetsState android.view.WindowInsetsController.getState()");
77         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract boolean android.view.WindowInsetsController.isRequestedVisible(int)");
78         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract void android.view.WindowInsetsController.setAnimationsDisabled(boolean)");
79         HIDDEN_INTERFACE_METHOD_ALLOW_LIST.add("public abstract void android.view.inputmethod.InputMethod.hideSoftInputWithToken(int,android.os.ResultReceiver,android.os.IBinder)");
80     }
81 
82     private final ResultObserver resultObserver;
83 
84     private final Map<Class<?>, JDiffClassDescription> class2Description =
85             new TreeMap<>(Comparator.comparing(Class::getName));
86 
87     private final ClassProvider classProvider;
88 
InterfaceChecker(ResultObserver resultObserver, ClassProvider classProvider)89     InterfaceChecker(ResultObserver resultObserver, ClassProvider classProvider) {
90         this.resultObserver = resultObserver;
91         this.classProvider = classProvider;
92     }
93 
checkQueued()94     public void checkQueued() {
95         for (Map.Entry<Class<?>, JDiffClassDescription> entry : class2Description.entrySet()) {
96             Class<?> runtimeClass = entry.getKey();
97             JDiffClassDescription classDescription = entry.getValue();
98             List<Method> methods = checkInterfaceMethodCompliance(classDescription, runtimeClass);
99             if (methods.size() > 0) {
100                 resultObserver.notifyFailure(FailureType.MISMATCH_INTERFACE_METHOD,
101                         classDescription.getAbsoluteClassName(), "Interfaces cannot be modified: "
102                                 + classDescription.getAbsoluteClassName()
103                                 + " has the following methods that are not present in the API specification:\n\t"
104                                 + methods.stream().map(Method::toGenericString).collect(Collectors.joining("\n\t")));
105             }
106         }
107     }
108 
not(Predicate<T> predicate)109     private static <T> Predicate<T> not(Predicate<T> predicate) {
110         return predicate.negate();
111     }
112 
113     /**
114      * Validate that an interfaces method count is as expected.
115      *
116      * @param classDescription the class's API description.
117      * @param runtimeClass the runtime class corresponding to {@code classDescription}.
118      */
checkInterfaceMethodCompliance( JDiffClassDescription classDescription, Class<?> runtimeClass)119     private List<Method> checkInterfaceMethodCompliance(
120             JDiffClassDescription classDescription, Class<?> runtimeClass) {
121 
122         return Stream.of(runtimeClass.getDeclaredMethods())
123                 .filter(not(Method::isDefault))
124                 .filter(not(Method::isSynthetic))
125                 .filter(not(Method::isBridge))
126                 .filter(m -> !Modifier.isStatic(m.getModifiers()))
127                 .filter(m -> !HIDDEN_INTERFACE_METHOD_ALLOW_LIST.contains(m.toGenericString()))
128                 .filter(m -> !findMethod(classDescription, m))
129                 .collect(Collectors.toCollection(ArrayList::new));
130     }
131 
findMethod(JDiffClassDescription classDescription, Method method)132     private boolean findMethod(JDiffClassDescription classDescription, Method method) {
133         Map<Method, String> matchNameNotSignature = new LinkedHashMap<>();
134         for (JDiffClassDescription.JDiffMethod jdiffMethod : classDescription.getMethods()) {
135             if (ReflectionHelper.matchesSignature(jdiffMethod, method, matchNameNotSignature)) {
136                 return true;
137             }
138         }
139         for (String interfaceName : classDescription.getImplInterfaces()) {
140             Class<?> interfaceClass = null;
141             try {
142                 interfaceClass = ReflectionHelper.findMatchingClass(interfaceName, classProvider);
143             } catch (ClassNotFoundException e) {
144                 LogHelper.loge("ClassNotFoundException for " + classDescription.getAbsoluteClassName(), e);
145             }
146 
147             JDiffClassDescription implInterface = class2Description.get(interfaceClass);
148             if (implInterface == null) {
149                 // Class definition is not in the scope of the API definitions.
150                 continue;
151             }
152 
153             if (findMethod(implInterface, method)) {
154                 return true;
155             }
156         }
157         return false;
158     }
159 
160 
queueForDeferredCheck(JDiffClassDescription classDescription, Class<?> runtimeClass)161     void queueForDeferredCheck(JDiffClassDescription classDescription, Class<?> runtimeClass) {
162 
163         JDiffClassDescription existingDescription = class2Description.get(runtimeClass);
164         if (existingDescription != null) {
165             for (JDiffClassDescription.JDiffMethod method : classDescription.getMethods()) {
166                 existingDescription.addMethod(method);
167             }
168         } else {
169             class2Description.put(runtimeClass, classDescription);
170         }
171     }
172 }
173