• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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/Common.h>
20 #include <binder/unique_fd.h>
21 #include <utils/Errors.h>
22 #include <utils/RefBase.h>
23 #include <utils/String16.h>
24 #include <utils/Vector.h>
25 
26 #include <functional>
27 
28 // linux/binder.h defines this, but we don't want to include it here in order to
29 // avoid exporting the kernel headers
30 #ifndef B_PACK_CHARS
31 #define B_PACK_CHARS(c1, c2, c3, c4) \
32     ((((c1)<<24)) | (((c2)<<16)) | (((c3)<<8)) | (c4))
33 #endif  // B_PACK_CHARS
34 
35 // ---------------------------------------------------------------------------
36 namespace android {
37 
38 class BBinder;
39 class BpBinder;
40 class IInterface;
41 class Parcel;
42 class IResultReceiver;
43 class IShellCallback;
44 
45 /**
46  * Base class and low-level protocol for a remotable object.
47  * You can derive from this class to create an object for which other
48  * processes can hold references to it.  Communication between processes
49  * (method calls, property get and set) is down through a low-level
50  * protocol implemented on top of the transact() API.
51  */
52 class [[clang::lto_visibility_public]] LIBBINDER_EXPORTED IBinder : public virtual RefBase {
53 public:
54     enum {
55         FIRST_CALL_TRANSACTION = 0x00000001,
56         LAST_CALL_TRANSACTION = 0x00ffffff,
57 
58         PING_TRANSACTION = B_PACK_CHARS('_', 'P', 'N', 'G'),
59         START_RECORDING_TRANSACTION = B_PACK_CHARS('_', 'S', 'R', 'D'),
60         STOP_RECORDING_TRANSACTION = B_PACK_CHARS('_', 'E', 'R', 'D'),
61         DUMP_TRANSACTION = B_PACK_CHARS('_', 'D', 'M', 'P'),
62         SHELL_COMMAND_TRANSACTION = B_PACK_CHARS('_', 'C', 'M', 'D'),
63         INTERFACE_TRANSACTION = B_PACK_CHARS('_', 'N', 'T', 'F'),
64         SYSPROPS_TRANSACTION = B_PACK_CHARS('_', 'S', 'P', 'R'),
65         EXTENSION_TRANSACTION = B_PACK_CHARS('_', 'E', 'X', 'T'),
66         DEBUG_PID_TRANSACTION = B_PACK_CHARS('_', 'P', 'I', 'D'),
67         SET_RPC_CLIENT_TRANSACTION = B_PACK_CHARS('_', 'R', 'P', 'C'),
68 
69         // See android.os.IBinder.TWEET_TRANSACTION
70         // Most importantly, messages can be anything not exceeding 130 UTF-8
71         // characters, and callees should exclaim "jolly good message old boy!"
72         TWEET_TRANSACTION = B_PACK_CHARS('_', 'T', 'W', 'T'),
73 
74         // See android.os.IBinder.LIKE_TRANSACTION
75         // Improve binder self-esteem.
76         LIKE_TRANSACTION = B_PACK_CHARS('_', 'L', 'I', 'K'),
77 
78         // Corresponds to TF_ONE_WAY -- an asynchronous call.
79         FLAG_ONEWAY = 0x00000001,
80 
81         // Corresponds to TF_CLEAR_BUF -- clear transaction buffers after call
82         // is made
83         FLAG_CLEAR_BUF = 0x00000020,
84 
85         // Private userspace flag for transaction which is being requested from
86         // a vendor context.
87         FLAG_PRIVATE_VENDOR = 0x10000000,
88     };
89 
90     IBinder();
91 
92     /**
93      * Check if this IBinder implements the interface named by
94      * @a descriptor.  If it does, the base pointer to it is returned,
95      * which you can safely static_cast<> to the concrete C++ interface.
96      */
97     virtual sp<IInterface>  queryLocalInterface(const String16& descriptor);
98 
99     /**
100      * Return the canonical name of the interface provided by this IBinder
101      * object.
102      */
103     virtual const String16& getInterfaceDescriptor() const = 0;
104 
105     virtual bool            isBinderAlive() const = 0;
106     virtual status_t        pingBinder() = 0;
107     virtual status_t        dump(int fd, const Vector<String16>& args) = 0;
108     static  status_t        shellCommand(const sp<IBinder>& target, int in, int out, int err,
109                                          Vector<String16>& args, const sp<IShellCallback>& callback,
110                                          const sp<IResultReceiver>& resultReceiver);
111 
112     /**
113      * This allows someone to add their own additions to an interface without
114      * having to modify the original interface.
115      *
116      * For instance, imagine if we have this interface:
117      *     interface IFoo { void doFoo(); }
118      *
119      * If an unrelated owner (perhaps in a downstream codebase) wants to make a
120      * change to the interface, they have two options:
121      *
122      * A). Historical option that has proven to be BAD! Only the original
123      *     author of an interface should change an interface. If someone
124      *     downstream wants additional functionality, they should not ever
125      *     change the interface or use this method.
126      *
127      *    BAD TO DO:  interface IFoo {                       BAD TO DO
128      *    BAD TO DO:      void doFoo();                      BAD TO DO
129      *    BAD TO DO: +    void doBar(); // adding a method   BAD TO DO
130      *    BAD TO DO:  }                                      BAD TO DO
131      *
132      * B). Option that this method enables!
133      *     Leave the original interface unchanged (do not change IFoo!).
134      *     Instead, create a new interface in a downstream package:
135      *
136      *         package com.<name>; // new functionality in a new package
137      *         interface IBar { void doBar(); }
138      *
139      *     When registering the interface, add:
140      *         sp<MyFoo> foo = new MyFoo; // class in AOSP codebase
141      *         sp<MyBar> bar = new MyBar; // custom extension class
142      *         foo->setExtension(bar);    // use method in BBinder
143      *
144      *     Then, clients of IFoo can get this extension:
145      *         sp<IBinder> binder = ...;
146      *         sp<IFoo> foo = interface_cast<IFoo>(binder); // handle if null
147      *         sp<IBinder> barBinder;
148      *         ... handle error ... = binder->getExtension(&barBinder);
149      *         sp<IBar> bar = interface_cast<IBar>(barBinder);
150      *         // if bar is null, then there is no extension or a different
151      *         // type of extension
152      */
153     status_t                getExtension(sp<IBinder>* out);
154 
155     /**
156      * Dump PID for a binder, for debugging.
157      */
158     status_t                getDebugPid(pid_t* outPid);
159 
160     /**
161      * Set the RPC client fd to this binder service, for debugging. This is only available on
162      * debuggable builds.
163      *
164      * When this is called on a binder service, the service:
165      * 1. sets up RPC server
166      * 2. spawns 1 new thread that calls RpcServer::join()
167      *    - join() spawns some number of threads that accept() connections; see RpcServer
168      *
169      * setRpcClientDebug() may be called multiple times. Each call will add a new RpcServer
170      * and opens up a TCP port.
171      *
172      * Note: A thread is spawned for each accept()'ed fd, which may call into functions of the
173      * interface freely. See RpcServer::join(). To avoid such race conditions, implement the service
174      * functions with multithreading support.
175      *
176      * On death of @a keepAliveBinder, the RpcServer shuts down.
177      */
178     [[nodiscard]] status_t setRpcClientDebug(binder::unique_fd socketFd,
179                                              const sp<IBinder>& keepAliveBinder);
180 
181     // NOLINTNEXTLINE(google-default-arguments)
182     virtual status_t        transact(   uint32_t code,
183                                         const Parcel& data,
184                                         Parcel* reply,
185                                         uint32_t flags = 0) = 0;
186 
187     // DeathRecipient is pure abstract, there is no virtual method
188     // implementation to put in a translation unit in order to silence the
189     // weak vtables warning.
190     #if defined(__clang__)
191     #pragma clang diagnostic push
192     #pragma clang diagnostic ignored "-Wweak-vtables"
193     #endif
194 
195     class DeathRecipient : public virtual RefBase
196     {
197     public:
198         virtual void binderDied(const wp<IBinder>& who) = 0;
199     };
200 
201     #if defined(__clang__)
202     #pragma clang diagnostic pop
203     #endif
204 
205     /**
206      * Register the @a recipient for a notification if this binder
207      * goes away.  If this binder object unexpectedly goes away
208      * (typically because its hosting process has been killed),
209      * then DeathRecipient::binderDied() will be called with a reference
210      * to this.
211      *
212      * The @a cookie is optional -- if non-NULL, it should be a
213      * memory address that you own (that is, you know it is unique).
214      *
215      * @note When all references to the binder being linked to are dropped, the
216      * recipient is automatically unlinked. So, you must hold onto a binder in
217      * order to receive death notifications about it.
218      *
219      * @note You will only receive death notifications for remote binders,
220      * as local binders by definition can't die without you dying as well.
221      * Trying to use this function on a local binder will result in an
222      * INVALID_OPERATION code being returned and nothing happening.
223      *
224      * @note This link always holds a weak reference to its recipient.
225      *
226      * @note You will only receive a weak reference to the dead
227      * binder.  You should not try to promote this to a strong reference.
228      * (Nor should you need to, as there is nothing useful you can
229      * directly do with it now that it has passed on.)
230      */
231     // NOLINTNEXTLINE(google-default-arguments)
232     virtual status_t        linkToDeath(const sp<DeathRecipient>& recipient,
233                                         void* cookie = nullptr,
234                                         uint32_t flags = 0) = 0;
235 
236     /**
237      * Remove a previously registered death notification.
238      * The @a recipient will no longer be called if this object
239      * dies.  The @a cookie is optional.  If non-NULL, you can
240      * supply a NULL @a recipient, and the recipient previously
241      * added with that cookie will be unlinked.
242      *
243      * If the binder is dead, this will return DEAD_OBJECT. Deleting
244      * the object will also unlink all death recipients.
245      */
246     // NOLINTNEXTLINE(google-default-arguments)
247     virtual status_t        unlinkToDeath(  const wp<DeathRecipient>& recipient,
248                                             void* cookie = nullptr,
249                                             uint32_t flags = 0,
250                                             wp<DeathRecipient>* outRecipient = nullptr) = 0;
251 
252     virtual bool            checkSubclass(const void* subclassID) const;
253 
254     typedef void (*object_cleanup_func)(const void* id, void* obj, void* cleanupCookie);
255 
256     /**
257      * This object is attached for the lifetime of this binder object. When
258      * this binder object is destructed, the cleanup function of all attached
259      * objects are invoked with their respective objectID, object, and
260      * cleanupCookie. Access to these APIs can be made from multiple threads,
261      * but calls from different threads are allowed to be interleaved.
262      *
263      * This returns the object which is already attached. If this returns a
264      * non-null value, it means that attachObject failed (a given objectID can
265      * only be used once).
266      */
267     [[nodiscard]] virtual void* attachObject(const void* objectID, void* object,
268                                              void* cleanupCookie, object_cleanup_func func) = 0;
269     /**
270      * Returns object attached with attachObject.
271      */
272     [[nodiscard]] virtual void* findObject(const void* objectID) const = 0;
273     /**
274      * Returns object attached with attachObject, and detaches it. This does not
275      * delete the object.
276      */
277     [[nodiscard]] virtual void* detachObject(const void* objectID) = 0;
278 
279     /**
280      * Use the lock that this binder contains internally. For instance, this can
281      * be used to modify an attached object without needing to add an additional
282      * lock (though, that attached object must be retrieved before calling this
283      * method). Calling (most) IBinder methods inside this will deadlock.
284      */
285     void withLock(const std::function<void()>& doWithLock);
286 
287     virtual BBinder*        localBinder();
288     virtual BpBinder*       remoteBinder();
289     typedef sp<IBinder> (*object_make_func)(const void* makeArgs);
290     sp<IBinder> lookupOrCreateWeak(const void* objectID, object_make_func make,
291                                    const void* makeArgs);
292 
293 protected:
294     virtual          ~IBinder();
295 
296 private:
297 };
298 
299 } // namespace android
300 
301 // ---------------------------------------------------------------------------
302