1 /*
2  * Copyright (C) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OHOS_IPC_BINDER_INVOKER_H
17 #define OHOS_IPC_BINDER_INVOKER_H
18 
19 #include <atomic>
20 #include <unistd.h>
21 #include <sys/types.h>
22 #include <unordered_set>
23 #include "binder_connector.h"
24 #include "iremote_invoker.h"
25 #include "invoker_factory.h"
26 #include "process_skeleton.h"
27 #include <securec.h>
28 #ifdef CONFIG_ACTV_BINDER
29 #include "actv_binder.h"
30 #endif
31 
32 namespace OHOS {
33 
34 /* dfx interface,type is 0 for string */
35 extern "C" uintptr_t DFX_SetCrashObj(uint8_t type, uintptr_t addr);
36 extern "C" void DFX_ResetCrashObj(uintptr_t crashObj);
37 
38 struct CrashObjDumper {
39 public:
CrashObjDumperCrashObjDumper40     explicit CrashObjDumper(const char *str)
41     {
42         if (str == nullptr) {
43             return;
44         }
45         ptr_ = DFX_SetCrashObj(0, reinterpret_cast<uintptr_t>(str));
46     }
~CrashObjDumperCrashObjDumper47     ~CrashObjDumper()
48     {
49         DFX_ResetCrashObj(ptr_);
50     }
51 private:
52     uintptr_t ptr_ = 0;
53 };
54 #ifdef CONFIG_IPC_SINGLE
55 namespace IPC_SINGLE {
56 #endif
57 
58 class BinderInvoker : public IRemoteInvoker {
59 public:
60     class BinderAllocator : public DefaultAllocator {
61         void Dealloc(void *data) override;
62 
63         friend BinderInvoker;
64     };
65 
66     BinderInvoker();
67 
68     ~BinderInvoker();
69 
70     bool AcquireHandle(int32_t handle) override;
71 
72     bool ReleaseHandle(int32_t handle) override;
73 
74     bool PingService(int32_t handle) override;
75 
76     bool AddDeathRecipient(int32_t handle, void *cookie) override;
77 
78     bool RemoveDeathRecipient(int32_t handle, void *cookie) override;
79 
80     bool SetMaxWorkThread(int maxThreadNum) override;
81 
82     void JoinThread(bool initiative) override;
83 
84     void JoinProcessThread(bool initiative) override;
85 
86     void FreeBuffer(void *data) override;
87 
88     void StopWorkThread() override;
89 
90     bool SetRegistryObject(sptr<IRemoteObject> &object) override;
91 
92     int SendRequest(int handle, uint32_t code, MessageParcel &data, MessageParcel &reply,
93         MessageOption &option) override;
94 
95     int SendReply(MessageParcel &reply, uint32_t flags, int32_t result) override;
96 
97     bool FlattenObject(Parcel &parcel, const IRemoteObject *object) const override;
98 
99     sptr<IRemoteObject> UnflattenObject(Parcel &parcel) override;
100 
101     int ReadFileDescriptor(Parcel &parcel) override;
102 
103     bool WriteFileDescriptor(Parcel &parcel, int fd, bool takeOwnership) override;
104 
105     std::string GetCallerSid() const override;
106 
107     pid_t GetCallerPid() const override;
108 
109     pid_t GetCallerRealPid() const override;
110 
111     uid_t GetCallerUid() const override;
112 
113     uint64_t GetCallerTokenID() const override;
114 
115     uint64_t GetFirstCallerTokenID() const override;
116 
117     uint64_t GetSelfTokenID() const override;
118 
119     uint64_t GetSelfFirstCallerTokenID() const override;
120 
121     uint32_t GetStatus() override;
122 
123     bool IsLocalCalling() override;
124 
125     void SetStatus(uint32_t status);
126 
127     std::string GetLocalDeviceID() override;
128 
129     std::string GetCallerDeviceID() const override;
130 
131     int FlushCommands(IRemoteObject *object) override;
132 
133     std::string ResetCallingIdentity() override;
134 
135     bool SetCallingIdentity(std::string &identity, bool flag) override;
136 
137     void ExitCurrentThread();
138 
139     uint32_t GetStrongRefCountForStub(uint32_t handle);
140 
141     bool IsSendRequesting();
142 
143 #ifndef CONFIG_IPC_SINGLE
144     int TranslateIRemoteObject(int32_t cmd, const sptr<IRemoteObject> &obj) override;
145 
146     sptr<IRemoteObject> GetSAMgrObject() override;
147 #endif
148 
149 #ifdef CONFIG_ACTV_BINDER
150     static void JoinActvThread(bool initiative);
151     static bool IsActvBinderService();
152 #endif // CONFIG_ACTV_BINDER
153 
154 protected:
155     bool isMainWorkThread;
156     bool stopWorkThread;
157     pid_t callerPid_;
158     pid_t callerRealPid_;
159     pid_t callerUid_;
160     uint64_t callerTokenID_;
161     uint64_t firstTokenID_;
162     std::string callerSid_;
163 
164 private:
165     int TransactWithDriver(bool doRead = true);
166 
167     bool WriteTransaction(int cmd, uint32_t flags, int32_t handle, uint32_t code, const MessageParcel &data,
168         const int *status, size_t totalDBinderBufSize);
169 
170     int WaitForCompletion(MessageParcel *reply = nullptr, int32_t *acquireResult = nullptr);
171 
172     void OnAttemptAcquire();
173 
174     void OnRemoveRecipientDone();
175 
176     void StartWorkLoop();
177 
178     void OnBinderDied();
179 
180     void OnAcquireObject(uint32_t cmd);
181 
182     void OnReleaseObject(uint32_t cmd);
183 
184     void Transaction(binder_transaction_data_secctx& trSecctx);
185 
186     void OnTransaction(uint32_t cmd, int32_t &error);
187 
188     void OnSpawnThread();
189 
190     int HandleCommands(uint32_t cmd);
191 
192     int HandleCommandsInner(uint32_t cmd);
193 
194     int HandleReply(MessageParcel *reply, bool &isStubRet);
195 
196     bool TranslateDBinderProxy(int handle, MessageParcel &data);
197 
198     void GetAccessToken(uint64_t &callerTokenID, uint64_t &firstTokenID);
199 
200     void GetSenderInfo(uint64_t &callerTokenID, uint64_t &firstTokenID, pid_t &realPid);
201 
202     void OnTransactionComplete(MessageParcel *reply,
203         int32_t *acquireResult, bool &continueLoop, int32_t &error, uint32_t cmd);
204 
205     void OnDeadOrFailedReply(MessageParcel *reply,
206         int32_t *acquireResult, bool &continueLoop, int32_t &error, uint32_t cmd);
207 
208     void OnAcquireResult(MessageParcel *reply,
209         int32_t *acquireResult, bool &continueLoop, int32_t &error, uint32_t cmd);
210 
211     void OnReply(MessageParcel *reply,
212         int32_t *acquireResult, bool &continueLoop, int32_t &error, uint32_t cmd);
213 
214     void OnTranslationComplete(MessageParcel *reply,
215         int32_t *acquireResult, bool &continueLoop, int32_t &error, uint32_t cmd);
216 
217     void DealWithCmd(MessageParcel *reply,
218         int32_t *acquireResult, bool &continueLoop, int32_t &error, uint32_t cmd);
219 
220     int32_t TargetStubSendRequest(const binder_transaction_data &tr,
221         MessageParcel &data, MessageParcel &reply, MessageOption &option, uint32_t &flagValue);
222 
223     int32_t GeneralServiceSendRequest(
224         const binder_transaction_data &tr, MessageParcel &data, MessageParcel &reply, MessageOption &option);
225 
226     int32_t SamgrServiceSendRequest(const binder_transaction_data &tr,
227         MessageParcel &data, MessageParcel &reply, MessageOption &option);
228 
229     void AttachInvokerProcInfoWrapper();
230 
231     void RestoreInvokerProcInfo(const InvokerProcInfo &info);
232 
233     void PrintParcelData(Parcel &parcel, const std::string &parcelName);
234 
235     void UpdateConsumedData(const binder_write_read &bwr, const size_t outAvail);
236 
237     void PrintIdentity(bool isPrint, bool isBefore);
238 
239     void ProcDeferredDecRefs();
240 
241 #ifndef CONFIG_IPC_SINGLE
242     bool AddCommAuth(int32_t handle, flat_binder_object *flat);
243 
244     bool TranslateDBinderStub(int handle, MessageParcel &parcel, bool isReply, size_t &totalDBinderBufSize);
245 
246     bool GetDBinderCallingPidUid(int handle, bool isReply, pid_t &pid, uid_t &uid);
247 
248     bool UnFlattenDBinderObject(Parcel &parcel, dbinder_negotiation_data &dbinderData);
249 #endif
250 
251 #ifdef CONFIG_ACTV_BINDER
SetUseActvBinder(bool useActvBinder)252     inline void SetUseActvBinder(bool useActvBinder)
253     {
254         if ((binderConnector_ != nullptr) && binderConnector_->IsActvBinderSupported()) {
255             useActvBinder_ = useActvBinder;
256         }
257     }
258 
GetUseActvBinder()259     inline bool GetUseActvBinder()
260     {
261         return useActvBinder_;
262     }
263 
GetBWRCommand()264     inline uint32_t GetBWRCommand()
265     {
266         return useActvBinder_ ? ACTV_BINDER_WRITE_READ : BINDER_WRITE_READ;
267     }
268 #endif // CONFIG_ACTV_BINDER
269 
270 private:
271     DISALLOW_COPY_AND_MOVE(BinderInvoker);
272     static constexpr int IPC_DEFAULT_PARCEL_SIZE = 256;
273     static constexpr int IPC_CMD_PROCESS_WARN_TIME = 500;
274     static constexpr int ACCESS_TOKEN_MAX_LEN = 10;
275     Parcel input_;
276     Parcel output_;
277     BinderConnector *binderConnector_;
278     uint32_t status_;
279     static inline InvokerDelegator<BinderInvoker> delegator_ = { IRemoteObject::IF_PROT_BINDER };
280     InvokerProcInfo invokerInfo_;
281     std::atomic<int> lastErr_ = 0;
282     std::atomic<int> lastErrCnt_ = 0;
283     std::atomic<int32_t> sendNestCount_ = 0;
284     std::atomic<int32_t> sendRequestCount_ = 0;
285     std::mutex strongRefMutex_;
286     std::vector<IRemoteObject *> decStrongRefs_;
287     std::mutex weakRefMutex_;
288     std::vector<RefCounter *> decWeakRefs_;
289 #ifdef CONFIG_ACTV_BINDER
290     bool useActvBinder_ = false;
291 #endif
292 };
293 #ifdef CONFIG_IPC_SINGLE
294 } // namespace IPC_SINGLE
295 #endif
296 } // namespace OHOS
297 #endif // OHOS_IPC_BINDER_INVOKER_H
298