1 /*
2  * Copyright (C) 2005 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 #pragma once
18 
19 #include <binder/Binder.h>
20 #include <binder/Common.h>
21 
22 #include <assert.h>
23 
24 namespace android {
25 
26 // ----------------------------------------------------------------------
27 
28 class LIBBINDER_EXPORTED IInterface : public virtual RefBase {
29 public:
30             IInterface();
31             static sp<IBinder>  asBinder(const IInterface*);
32             static sp<IBinder>  asBinder(const sp<IInterface>&);
33 
34 protected:
35     virtual                     ~IInterface();
36     virtual IBinder*            onAsBinder() = 0;
37 };
38 
39 // ----------------------------------------------------------------------
40 
41 /**
42  * If this is a local object and the descriptor matches, this will return the
43  * actual local object which is implementing the interface. Otherwise, this will
44  * return a proxy to the interface without checking the interface descriptor.
45  * This means that subsequent calls may fail with BAD_TYPE.
46  */
47 template<typename INTERFACE>
interface_cast(const sp<IBinder> & obj)48 inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
49 {
50     return INTERFACE::asInterface(obj);
51 }
52 
53 /**
54  * This is the same as interface_cast, except that it always checks to make sure
55  * the descriptor matches, and if it doesn't match, it will return nullptr.
56  */
57 template<typename INTERFACE>
checked_interface_cast(const sp<IBinder> & obj)58 inline sp<INTERFACE> checked_interface_cast(const sp<IBinder>& obj)
59 {
60     if (obj->getInterfaceDescriptor() != INTERFACE::descriptor) {
61         return nullptr;
62     }
63 
64     return interface_cast<INTERFACE>(obj);
65 }
66 
67 // ----------------------------------------------------------------------
68 
69 template <typename INTERFACE>
70 class LIBBINDER_EXPORTED BnInterface : public INTERFACE, public BBinder {
71 public:
72     virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
73     virtual const String16&     getInterfaceDescriptor() const;
74     typedef INTERFACE BaseInterface;
75 
76 protected:
77     virtual IBinder*            onAsBinder();
78 };
79 
80 // ----------------------------------------------------------------------
81 
82 template <typename INTERFACE>
83 class LIBBINDER_EXPORTED BpInterface : public INTERFACE, public BpRefBase {
84 public:
85     explicit                    BpInterface(const sp<IBinder>& remote);
86     typedef INTERFACE BaseInterface;
87 
88 protected:
89     virtual IBinder*            onAsBinder();
90 };
91 
92 // ----------------------------------------------------------------------
93 
94 #define DECLARE_META_INTERFACE(INTERFACE)                                                         \
95 public:                                                                                           \
96     static const ::android::String16 descriptor;                                                  \
97     static ::android::sp<I##INTERFACE> asInterface(const ::android::sp<::android::IBinder>& obj); \
98     virtual const ::android::String16& getInterfaceDescriptor() const;                            \
99     I##INTERFACE();                                                                               \
100     virtual ~I##INTERFACE();                                                                      \
101     static bool setDefaultImpl(::android::sp<I##INTERFACE> impl);                                 \
102     static const ::android::sp<I##INTERFACE>& getDefaultImpl();                                   \
103                                                                                                   \
104 private:                                                                                          \
105     static ::android::sp<I##INTERFACE> default_impl;                                              \
106                                                                                                   \
107 public:
108 
109 #define __IINTF_CONCAT(x, y) (x ## y)
110 
111 #ifndef DO_NOT_CHECK_MANUAL_BINDER_INTERFACES
112 
113 #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
114     static_assert(internal::allowedManualInterface(NAME),               \
115                   "b/64223827: Manually written binder interfaces are " \
116                   "considered error prone and frequently have bugs. "   \
117                   "The preferred way to add interfaces is to define "   \
118                   "an .aidl file to auto-generate the interface. If "   \
119                   "an interface must be manually written, add its "     \
120                   "name to the allowlist.");                            \
121     DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME)
122 
123 #else
124 
125 #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
126     DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME)    \
127 
128 #endif
129 
130 // Macro to be used by both IMPLEMENT_META_INTERFACE and IMPLEMENT_META_NESTED_INTERFACE
131 #define DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE0(ITYPE, INAME, BPTYPE)                     \
132     const ::android::String16& ITYPE::getInterfaceDescriptor() const { return ITYPE::descriptor; } \
133     ::android::sp<ITYPE> ITYPE::asInterface(const ::android::sp<::android::IBinder>& obj) {        \
134         ::android::sp<ITYPE> intr;                                                                 \
135         if (obj != nullptr) {                                                                      \
136             intr = ::android::sp<ITYPE>::cast(obj->queryLocalInterface(ITYPE::descriptor));        \
137             if (intr == nullptr) {                                                                 \
138                 intr = ::android::sp<BPTYPE>::make(obj);                                           \
139             }                                                                                      \
140         }                                                                                          \
141         return intr;                                                                               \
142     }                                                                                              \
143     ::android::sp<ITYPE> ITYPE::default_impl;                                                      \
144     bool ITYPE::setDefaultImpl(::android::sp<ITYPE> impl) {                                        \
145         /* Only one user of this interface can use this function     */                            \
146         /* at a time. This is a heuristic to detect if two different */                            \
147         /* users in the same process use this function.              */                            \
148         assert(!ITYPE::default_impl);                                                              \
149         if (impl) {                                                                                \
150             ITYPE::default_impl = std::move(impl);                                                 \
151             return true;                                                                           \
152         }                                                                                          \
153         return false;                                                                              \
154     }                                                                                              \
155     const ::android::sp<ITYPE>& ITYPE::getDefaultImpl() { return ITYPE::default_impl; }            \
156     ITYPE::INAME() {}                                                                              \
157     ITYPE::~INAME() {}
158 
159 // Macro for an interface type.
160 #define DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                        \
161     const ::android::StaticString16 I##INTERFACE##_descriptor_static_str16(                     \
162             __IINTF_CONCAT(u, NAME));                                                           \
163     const ::android::String16 I##INTERFACE::descriptor(I##INTERFACE##_descriptor_static_str16); \
164     DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE0(I##INTERFACE, I##INTERFACE, Bp##INTERFACE)
165 
166 // Macro for "nested" interface type.
167 // For example,
168 //   class Parent .. { class INested .. { }; };
169 // DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_NESTED_INTERFACE(Parent, Nested, "Parent.INested")
170 #define DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_NESTED_INTERFACE(PARENT, INTERFACE, NAME)  \
171     const ::android::String16 PARENT::I##INTERFACE::descriptor(NAME);                    \
172     DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE0(PARENT::I##INTERFACE, I##INTERFACE, \
173                                                      PARENT::Bp##INTERFACE)
174 
175 #define CHECK_INTERFACE(interface, data, reply)                         \
176     do {                                                                \
177       if (!(data).checkInterface(this)) { return PERMISSION_DENIED; }   \
178     } while (false)                                                     \
179 
180 
181 // ----------------------------------------------------------------------
182 // No user-serviceable parts after this...
183 
184 template<typename INTERFACE>
queryLocalInterface(const String16 & _descriptor)185 inline sp<IInterface> BnInterface<INTERFACE>::queryLocalInterface(
186         const String16& _descriptor)
187 {
188     if (_descriptor == INTERFACE::descriptor) return sp<IInterface>::fromExisting(this);
189     return nullptr;
190 }
191 
192 template<typename INTERFACE>
getInterfaceDescriptor()193 inline const String16& BnInterface<INTERFACE>::getInterfaceDescriptor() const
194 {
195     return INTERFACE::getInterfaceDescriptor();
196 }
197 
198 template<typename INTERFACE>
onAsBinder()199 IBinder* BnInterface<INTERFACE>::onAsBinder()
200 {
201     return this;
202 }
203 
204 template<typename INTERFACE>
BpInterface(const sp<IBinder> & remote)205 inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
206     : BpRefBase(remote)
207 {
208 }
209 
210 template<typename INTERFACE>
onAsBinder()211 inline IBinder* BpInterface<INTERFACE>::onAsBinder()
212 {
213     return remote();
214 }
215 
216 // ----------------------------------------------------------------------
217 
218 namespace internal {
219 constexpr const char* const kManualInterfaces[] = {
220         "android.app.IActivityManager",
221         "android.app.IUidObserver",
222         "android.drm.IDrm",
223         "android.dvr.IVsyncCallback",
224         "android.dvr.IVsyncService",
225         "android.gfx.tests.ICallback",
226         "android.gfx.tests.IIPCTest",
227         "android.gfx.tests.ISafeInterfaceTest",
228         "android.graphicsenv.IGpuService",
229         "android.gui.IConsumerListener",
230         "android.gui.IGraphicBufferConsumer",
231         "android.gui.ITransactionComposerListener",
232         "android.gui.SensorEventConnection",
233         "android.gui.SensorServer",
234         "android.hardware.ICamera",
235         "android.hardware.ICameraClient",
236         "android.hardware.ICameraRecordingProxy",
237         "android.hardware.ICameraRecordingProxyListener",
238         "android.hardware.ICrypto",
239         "android.hardware.IOMXObserver",
240         "android.hardware.IStreamListener",
241         "android.hardware.IStreamSource",
242         "android.media.IAudioService",
243         "android.media.IDataSource",
244         "android.media.IDrmClient",
245         "android.media.IMediaCodecList",
246         "android.media.IMediaDrmService",
247         "android.media.IMediaExtractor",
248         "android.media.IMediaExtractorService",
249         "android.media.IMediaHTTPConnection",
250         "android.media.IMediaHTTPService",
251         "android.media.IMediaLogService",
252         "android.media.IMediaMetadataRetriever",
253         "android.media.IMediaMetricsService",
254         "android.media.IMediaPlayer",
255         "android.media.IMediaPlayerClient",
256         "android.media.IMediaPlayerService",
257         "android.media.IMediaRecorder",
258         "android.media.IMediaRecorderClient",
259         "android.media.IMediaResourceMonitor",
260         "android.media.IMediaSource",
261         "android.media.IRemoteDisplay",
262         "android.media.IRemoteDisplayClient",
263         "android.media.IResourceManagerClient",
264         "android.media.IResourceManagerService",
265         "android.os.IComplexTypeInterface",
266         "android.os.IPermissionController",
267         "android.os.IPingResponder",
268         "android.os.IProcessInfoService",
269         "android.os.ISchedulingPolicyService",
270         "android.os.IStringConstants",
271         "android.os.storage.IObbActionListener",
272         "android.os.storage.IStorageEventListener",
273         "android.os.storage.IStorageManager",
274         "android.os.storage.IStorageShutdownObserver",
275         "android.service.vr.IPersistentVrStateCallbacks",
276         "android.service.vr.IVrManager",
277         "android.service.vr.IVrStateCallbacks",
278         "android.ui.ISurfaceComposer",
279         "android.utils.IMemory",
280         "android.utils.IMemoryHeap",
281         "com.android.car.procfsinspector.IProcfsInspector",
282         "com.android.internal.app.IAppOpsCallback",
283         "com.android.internal.app.IAppOpsService",
284         "com.android.internal.app.IBatteryStats",
285         "com.android.internal.os.IResultReceiver",
286         "com.android.internal.os.IShellCallback",
287         "drm.IDrmManagerService",
288         "drm.IDrmServiceListener",
289         "IAAudioClient",
290         "IAAudioService",
291         "VtsFuzzer",
292         nullptr,
293 };
294 
295 constexpr const char* const kDownstreamManualInterfaces[] = {
296   // Add downstream interfaces here.
297   nullptr,
298 };
299 
equals(const char * a,const char * b)300 constexpr bool equals(const char* a, const char* b) {
301   if (*a != *b) return false;
302   if (*a == '\0') return true;
303   return equals(a + 1, b + 1);
304 }
305 
inList(const char * a,const char * const * allowlist)306 constexpr bool inList(const char* a, const char* const* allowlist) {
307   if (*allowlist == nullptr) return false;
308   if (equals(a, *allowlist)) return true;
309   return inList(a, allowlist + 1);
310 }
311 
allowedManualInterface(const char * name)312 constexpr bool allowedManualInterface(const char* name) {
313   return inList(name, kManualInterfaces) ||
314          inList(name, kDownstreamManualInterfaces);
315 }
316 
317 } // namespace internal
318 } // namespace android
319