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 
21 #include <assert.h>
22 
23 namespace android {
24 
25 // ----------------------------------------------------------------------
26 
27 class IInterface : public virtual RefBase
28 {
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 BnInterface : public INTERFACE, public BBinder
71 {
72 public:
73     virtual sp<IInterface>      queryLocalInterface(const String16& _descriptor);
74     virtual const String16&     getInterfaceDescriptor() const;
75 
76 protected:
77     typedef INTERFACE           BaseInterface;
78     virtual IBinder*            onAsBinder();
79 };
80 
81 // ----------------------------------------------------------------------
82 
83 template<typename INTERFACE>
84 class BpInterface : public INTERFACE, public BpRefBase
85 {
86 public:
87     explicit                    BpInterface(const sp<IBinder>& remote);
88 
89 protected:
90     typedef INTERFACE           BaseInterface;
91     virtual IBinder*            onAsBinder();
92 };
93 
94 // ----------------------------------------------------------------------
95 
96 #define DECLARE_META_INTERFACE(INTERFACE)                               \
97 public:                                                                 \
98     static const ::android::String16 descriptor;                        \
99     static ::android::sp<I##INTERFACE> asInterface(                     \
100             const ::android::sp<::android::IBinder>& obj);              \
101     virtual const ::android::String16& getInterfaceDescriptor() const;  \
102     I##INTERFACE();                                                     \
103     virtual ~I##INTERFACE();                                            \
104     static bool setDefaultImpl(std::unique_ptr<I##INTERFACE> impl);     \
105     static const std::unique_ptr<I##INTERFACE>& getDefaultImpl();       \
106 private:                                                                \
107     static std::unique_ptr<I##INTERFACE> default_impl;                  \
108 public:                                                                 \
109 
110 
111 #define __IINTF_CONCAT(x, y) (x ## y)
112 
113 #ifndef DO_NOT_CHECK_MANUAL_BINDER_INTERFACES
114 
115 #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
116     static_assert(internal::allowedManualInterface(NAME),               \
117                   "b/64223827: Manually written binder interfaces are " \
118                   "considered error prone and frequently have bugs. "   \
119                   "The preferred way to add interfaces is to define "   \
120                   "an .aidl file to auto-generate the interface. If "   \
121                   "an interface must be manually written, add its "     \
122                   "name to the whitelist.");                            \
123     DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME)    \
124 
125 #else
126 
127 #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \
128     DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME)    \
129 
130 #endif
131 
132 #define DO_NOT_DIRECTLY_USE_ME_IMPLEMENT_META_INTERFACE(INTERFACE, NAME)\
133     const ::android::StaticString16                                     \
134         I##INTERFACE##_descriptor_static_str16(__IINTF_CONCAT(u, NAME));\
135     const ::android::String16 I##INTERFACE::descriptor(                 \
136         I##INTERFACE##_descriptor_static_str16);                        \
137     const ::android::String16&                                          \
138             I##INTERFACE::getInterfaceDescriptor() const {              \
139         return I##INTERFACE::descriptor;                                \
140     }                                                                   \
141     ::android::sp<I##INTERFACE> I##INTERFACE::asInterface(              \
142             const ::android::sp<::android::IBinder>& obj)               \
143     {                                                                   \
144         ::android::sp<I##INTERFACE> intr;                               \
145         if (obj != nullptr) {                                           \
146             intr = ::android::sp<I##INTERFACE>::cast(                   \
147                 obj->queryLocalInterface(I##INTERFACE::descriptor));    \
148             if (intr == nullptr) {                                      \
149                 intr = ::android::sp<Bp##INTERFACE>::make(obj);         \
150             }                                                           \
151         }                                                               \
152         return intr;                                                    \
153     }                                                                   \
154     std::unique_ptr<I##INTERFACE> I##INTERFACE::default_impl;           \
155     bool I##INTERFACE::setDefaultImpl(std::unique_ptr<I##INTERFACE> impl)\
156     {                                                                   \
157         /* Only one user of this interface can use this function     */ \
158         /* at a time. This is a heuristic to detect if two different */ \
159         /* users in the same process use this function.              */ \
160         assert(!I##INTERFACE::default_impl);                            \
161         if (impl) {                                                     \
162             I##INTERFACE::default_impl = std::move(impl);               \
163             return true;                                                \
164         }                                                               \
165         return false;                                                   \
166     }                                                                   \
167     const std::unique_ptr<I##INTERFACE>& I##INTERFACE::getDefaultImpl() \
168     {                                                                   \
169         return I##INTERFACE::default_impl;                              \
170     }                                                                   \
171     I##INTERFACE::I##INTERFACE() { }                                    \
172     I##INTERFACE::~I##INTERFACE() { }                                   \
173 
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.DisplayEventConnection",
230   "android.gui.IConsumerListener",
231   "android.gui.IGraphicBufferConsumer",
232   "android.gui.IRegionSamplingListener",
233   "android.gui.ITransactionComposerListener",
234   "android.gui.SensorEventConnection",
235   "android.gui.SensorServer",
236   "android.hardware.ICamera",
237   "android.hardware.ICameraClient",
238   "android.hardware.ICameraRecordingProxy",
239   "android.hardware.ICameraRecordingProxyListener",
240   "android.hardware.ICrypto",
241   "android.hardware.IOMXObserver",
242   "android.hardware.IStreamListener",
243   "android.hardware.IStreamSource",
244   "android.media.IAudioService",
245   "android.media.IDataSource",
246   "android.media.IDrmClient",
247   "android.media.IMediaCodecList",
248   "android.media.IMediaDrmService",
249   "android.media.IMediaExtractor",
250   "android.media.IMediaExtractorService",
251   "android.media.IMediaHTTPConnection",
252   "android.media.IMediaHTTPService",
253   "android.media.IMediaLogService",
254   "android.media.IMediaMetadataRetriever",
255   "android.media.IMediaMetricsService",
256   "android.media.IMediaPlayer",
257   "android.media.IMediaPlayerClient",
258   "android.media.IMediaPlayerService",
259   "android.media.IMediaRecorder",
260   "android.media.IMediaRecorderClient",
261   "android.media.IMediaResourceMonitor",
262   "android.media.IMediaSource",
263   "android.media.IRemoteDisplay",
264   "android.media.IRemoteDisplayClient",
265   "android.media.IResourceManagerClient",
266   "android.media.IResourceManagerService",
267   "android.os.IComplexTypeInterface",
268   "android.os.IPermissionController",
269   "android.os.IPingResponder",
270   "android.os.IProcessInfoService",
271   "android.os.ISchedulingPolicyService",
272   "android.os.IStringConstants",
273   "android.os.storage.IObbActionListener",
274   "android.os.storage.IStorageEventListener",
275   "android.os.storage.IStorageManager",
276   "android.os.storage.IStorageShutdownObserver",
277   "android.service.vr.IPersistentVrStateCallbacks",
278   "android.service.vr.IVrManager",
279   "android.service.vr.IVrStateCallbacks",
280   "android.ui.ISurfaceComposer",
281   "android.ui.ISurfaceComposerClient",
282   "android.utils.IMemory",
283   "android.utils.IMemoryHeap",
284   "com.android.car.procfsinspector.IProcfsInspector",
285   "com.android.internal.app.IAppOpsCallback",
286   "com.android.internal.app.IAppOpsService",
287   "com.android.internal.app.IBatteryStats",
288   "com.android.internal.os.IResultReceiver",
289   "com.android.internal.os.IShellCallback",
290   "drm.IDrmManagerService",
291   "drm.IDrmServiceListener",
292   "IAAudioClient",
293   "IAAudioService",
294   "VtsFuzzer",
295   nullptr,
296 };
297 
298 constexpr const char* const kDownstreamManualInterfaces[] = {
299   // Add downstream interfaces here.
300   nullptr,
301 };
302 
equals(const char * a,const char * b)303 constexpr bool equals(const char* a, const char* b) {
304   if (*a != *b) return false;
305   if (*a == '\0') return true;
306   return equals(a + 1, b + 1);
307 }
308 
inList(const char * a,const char * const * whitelist)309 constexpr bool inList(const char* a, const char* const* whitelist) {
310   if (*whitelist == nullptr) return false;
311   if (equals(a, *whitelist)) return true;
312   return inList(a, whitelist + 1);
313 }
314 
allowedManualInterface(const char * name)315 constexpr bool allowedManualInterface(const char* name) {
316   return inList(name, kManualInterfaces) ||
317          inList(name, kDownstreamManualInterfaces);
318 }
319 
320 } // namespace internal
321 } // namespace android
322