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 
17 #pragma once
18 
19 #include <android/binder_ibinder.h>
20 #include <android/binder_shell.h>
21 #include "ibinder_internal.h"
22 
23 #include <atomic>
24 #include <mutex>
25 #include <optional>
26 #include <vector>
27 
28 #include <binder/Binder.h>
29 #include <binder/IBinder.h>
30 #include <utils/Vector.h>
31 
isUserCommand(transaction_code_t code)32 inline bool isUserCommand(transaction_code_t code) {
33     return code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION;
34 }
35 
36 struct ABBinder;
37 struct ABpBinder;
38 
39 struct AIBinder : public virtual ::android::RefBase {
40     explicit AIBinder(const AIBinder_Class* clazz);
41     virtual ~AIBinder();
42 
43     bool associateClass(const AIBinder_Class* clazz);
getClassAIBinder44     const AIBinder_Class* getClass() const { return mClazz; }
45 
46     virtual ::android::sp<::android::IBinder> getBinder() = 0;
asABBinderAIBinder47     virtual ABBinder* asABBinder() { return nullptr; }
asABpBinderAIBinder48     virtual ABpBinder* asABpBinder() { return nullptr; }
49 
isRemoteAIBinder50     bool isRemote() const {
51         ::android::sp<::android::IBinder> binder = const_cast<AIBinder*>(this)->getBinder();
52         return binder->remoteBinder() != nullptr;
53     }
54     virtual void addDeathRecipient(const ::android::sp<AIBinder_DeathRecipient>& recipient,
55                                    void* cookie) = 0;
56 
57    private:
58     // AIBinder instance is instance of this class for a local object. In order to transact on a
59     // remote object, this also must be set for simplicity (although right now, only the
60     // interfaceDescriptor from it is used).
61     //
62     // WARNING: When multiple classes exist with the same interface descriptor in different
63     // linkernamespaces, the first one to be associated with mClazz becomes the canonical one
64     // and the only requirement on this is that the interface descriptors match. If this
65     // is an ABpBinder, no other state can be referenced from mClazz.
66     const AIBinder_Class* mClazz;
67     std::mutex mClazzMutex;
68 };
69 
70 // This is a local AIBinder object with a known class.
71 struct ABBinder : public AIBinder, public ::android::BBinder {
72     virtual ~ABBinder();
73 
getUserDataABBinder74     void* getUserData() { return mUserData; }
75 
getBinderABBinder76     ::android::sp<::android::IBinder> getBinder() override { return this; }
asABBinderABBinder77     ABBinder* asABBinder() override { return this; }
78 
79     const ::android::String16& getInterfaceDescriptor() const override;
80     ::android::status_t dump(int fd, const ::android::Vector<::android::String16>& args) override;
81     ::android::status_t onTransact(uint32_t code, const ::android::Parcel& data,
82                                    ::android::Parcel* reply, binder_flags_t flags) override;
83     void addDeathRecipient(const ::android::sp<AIBinder_DeathRecipient>& /* recipient */,
84                            void* /* cookie */) override;
85 
86    private:
87     ABBinder(const AIBinder_Class* clazz, void* userData);
88 
89     // only thing that should create an ABBinder
90     friend AIBinder* AIBinder_new(const AIBinder_Class*, void*);
91 
92     // Can contain implementation if this is a local binder. This can still be nullptr for a local
93     // binder. If it is nullptr, the implication is the implementation state is entirely external to
94     // this object and the functionality provided in the AIBinder_Class is sufficient.
95     void* mUserData;
96 };
97 
98 // This binder object may be remote or local (even though it is 'Bp'). The implication if it is
99 // local is that it is an IBinder object created outside of the domain of libbinder_ndk.
100 struct ABpBinder : public AIBinder {
101     // Looks up to see if this object has or is an existing ABBinder or ABpBinder object, otherwise
102     // it creates an ABpBinder object.
103     static ::android::sp<AIBinder> lookupOrCreateFromBinder(
104             const ::android::sp<::android::IBinder>& binder);
105 
106     virtual ~ABpBinder();
107 
getBinderABpBinder108     ::android::sp<::android::IBinder> getBinder() override { return mRemote; }
asABpBinderABpBinder109     ABpBinder* asABpBinder() override { return this; }
110 
isServiceFuzzingABpBinder111     bool isServiceFuzzing() const { return mServiceFuzzing; }
setServiceFuzzingABpBinder112     void setServiceFuzzing() { mServiceFuzzing = true; }
113     void addDeathRecipient(const ::android::sp<AIBinder_DeathRecipient>& recipient,
114                            void* cookie) override;
115 
116    private:
117     friend android::sp<ABpBinder>;
118     explicit ABpBinder(const ::android::sp<::android::IBinder>& binder);
119     ::android::sp<::android::IBinder> mRemote;
120     bool mServiceFuzzing = false;
121     struct DeathRecipientInfo {
122         android::wp<AIBinder_DeathRecipient> recipient;
123         void* cookie;
124     };
125     std::mutex mDeathRecipientsMutex;
126     std::vector<DeathRecipientInfo> mDeathRecipients;
127 };
128 
129 struct AIBinder_Class {
130     AIBinder_Class(const char* interfaceDescriptor, AIBinder_Class_onCreate onCreate,
131                    AIBinder_Class_onDestroy onDestroy, AIBinder_Class_onTransact onTransact);
132 
getInterfaceDescriptorAIBinder_Class133     const ::android::String16& getInterfaceDescriptor() const { return mWideInterfaceDescriptor; }
getInterfaceDescriptorUtf8AIBinder_Class134     const char* getInterfaceDescriptorUtf8() const { return mInterfaceDescriptor.c_str(); }
135 
136     // whether a transaction header should be written
137     bool writeHeader = true;
138 
139     // required to be non-null, implemented for every class
140     const AIBinder_Class_onCreate onCreate = nullptr;
141     const AIBinder_Class_onDestroy onDestroy = nullptr;
142     const AIBinder_Class_onTransact onTransact = nullptr;
143 
144     // optional methods for a class
145     AIBinder_onDump onDump = nullptr;
146     AIBinder_handleShellCommand handleShellCommand = nullptr;
147 
148    private:
149     // Copy of the raw char string for when we don't have to return UTF-16
150     const std::string mInterfaceDescriptor;
151     // This must be a String16 since BBinder virtual getInterfaceDescriptor returns a reference to
152     // one.
153     const ::android::String16 mWideInterfaceDescriptor;
154 };
155 
156 // Ownership is like this (when linked to death):
157 //
158 //   AIBinder_DeathRecipient -sp-> TransferDeathRecipient <-wp-> IBinder
159 //
160 // When the AIBinder_DeathRecipient is dropped, so are the actual underlying death recipients. When
161 // the IBinder dies, only a wp to it is kept.
162 struct AIBinder_DeathRecipient : ::android::RefBase {
163     // One of these is created for every linkToDeath. This is to be able to recover data when a
164     // binderDied receipt only gives us information about the IBinder.
165     struct TransferDeathRecipient : ::android::IBinder::DeathRecipient {
TransferDeathRecipientAIBinder_DeathRecipient::TransferDeathRecipient166         TransferDeathRecipient(const ::android::wp<::android::IBinder>& who, void* cookie,
167                                const ::android::wp<AIBinder_DeathRecipient>& parentRecipient,
168                                const AIBinder_DeathRecipient_onBinderDied onDied,
169                                const AIBinder_DeathRecipient_onBinderUnlinked onUnlinked)
170             : mWho(who),
171               mCookie(cookie),
172               mParentRecipient(parentRecipient),
173               mOnDied(onDied),
174               mOnUnlinked(onUnlinked) {}
175         ~TransferDeathRecipient();
176 
177         void binderDied(const ::android::wp<::android::IBinder>& who) override;
178 
getWhoAIBinder_DeathRecipient::TransferDeathRecipient179         const ::android::wp<::android::IBinder>& getWho() { return mWho; }
getCookieAIBinder_DeathRecipient::TransferDeathRecipient180         void* getCookie() { return mCookie; }
181 
182        private:
183         ::android::wp<::android::IBinder> mWho;
184         void* mCookie;
185 
186         ::android::wp<AIBinder_DeathRecipient> mParentRecipient;
187 
188         // This is kept separately from AIBinder_DeathRecipient in case the death recipient is
189         // deleted while the death notification is fired
190         const AIBinder_DeathRecipient_onBinderDied mOnDied;
191         const AIBinder_DeathRecipient_onBinderUnlinked mOnUnlinked;
192     };
193 
194     explicit AIBinder_DeathRecipient(AIBinder_DeathRecipient_onBinderDied onDied);
195     binder_status_t linkToDeath(const ::android::sp<::android::IBinder>&, void* cookie);
196     binder_status_t unlinkToDeath(const ::android::sp<::android::IBinder>& binder, void* cookie);
197     void setOnUnlinked(AIBinder_DeathRecipient_onBinderUnlinked onUnlinked);
198     void pruneThisTransferEntry(const ::android::sp<::android::IBinder>&, void* cookie);
199 
200    private:
201     // When the user of this API deletes a Bp object but not the death recipient, the
202     // TransferDeathRecipient object can't be cleaned up. This is called whenever a new
203     // TransferDeathRecipient is linked, and it ensures that mDeathRecipients can't grow unbounded.
204     void pruneDeadTransferEntriesLocked();
205 
206     std::mutex mDeathRecipientsMutex;
207     std::vector<::android::sp<TransferDeathRecipient>> mDeathRecipients;
208     AIBinder_DeathRecipient_onBinderDied mOnDied;
209     AIBinder_DeathRecipient_onBinderUnlinked mOnUnlinked;
210 };
211