• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/Common.h>
20 #include <binder/Parcel.h>
21 #include <binder/ProcessState.h>
22 #include <utils/Errors.h>
23 #include <utils/Vector.h>
24 
25 #if defined(_WIN32)
26 typedef  int  uid_t;
27 #endif
28 
29 // ---------------------------------------------------------------------------
30 namespace android {
31 
32 /**
33  * Kernel binder thread state. All operations here refer to kernel binder. This
34  * object is allocated per-thread.
35  */
36 class IPCThreadState {
37 public:
38     using CallRestriction = ProcessState::CallRestriction;
39 
40     LIBBINDER_EXPORTED static IPCThreadState* self();
41     LIBBINDER_EXPORTED static IPCThreadState* selfOrNull(); // self(), but won't instantiate
42 
43     // Freeze or unfreeze the binder interface to a specific process. When freezing, this method
44     // will block up to timeout_ms to process pending transactions directed to pid. Unfreeze
45     // is immediate. Transactions to processes frozen via this method won't be delivered and the
46     // driver will return BR_FROZEN_REPLY to the client sending them. After unfreeze,
47     // transactions will be delivered normally.
48     //
49     // pid: id for the process for which the binder interface is to be frozen
50     // enable: freeze (true) or unfreeze (false)
51     // timeout_ms: maximum time this function is allowed to block the caller waiting for pending
52     // binder transactions to be processed.
53     //
54     // returns: 0 in case of success, a value < 0 in case of error
55     LIBBINDER_EXPORTED static status_t freeze(pid_t pid, bool enabled, uint32_t timeout_ms);
56 
57     // Provide information about the state of a frozen process
58     LIBBINDER_EXPORTED static status_t getProcessFreezeInfo(pid_t pid, uint32_t* sync_received,
59                                                             uint32_t* async_received);
60 
61     LIBBINDER_EXPORTED status_t clearLastError();
62 
63     /**
64      * Returns the PID of the process which has made the current binder
65      * call. If not in a binder call, this will return getpid.
66      *
67      * Warning: oneway transactions do not receive PID. Even if you expect
68      * a transaction to be synchronous, a misbehaving client could send it
69      * as an asynchronous call and result in a 0 PID here. Additionally, if
70      * there is a race and the calling process dies, the PID may still be
71      * 0 for a synchronous call.
72      */
73     [[nodiscard]] LIBBINDER_EXPORTED pid_t getCallingPid() const;
74 
75     /**
76      * Returns the SELinux security identifier of the process which has
77      * made the current binder call. If not in a binder call this will
78      * return nullptr. If this isn't requested with
79      * Binder::setRequestingSid, it will also return nullptr.
80      *
81      * This can't be restored once it's cleared, and it does not return the
82      * context of the current process when not in a binder call.
83      */
84     [[nodiscard]] LIBBINDER_EXPORTED const char* getCallingSid() const;
85 
86     /**
87      * Returns the UID of the process which has made the current binder
88      * call. If not in a binder call, this will return 0.
89      */
90     [[nodiscard]] LIBBINDER_EXPORTED uid_t getCallingUid() const;
91 
92     /**
93      * Make it an abort to rely on getCalling* for a section of
94      * execution.
95      *
96      * Usage:
97      *     IPCThreadState::SpGuard guard {
98      *        .address = __builtin_frame_address(0),
99      *        .context = "...",
100      *     };
101      *     const auto* orig = pushGetCallingSpGuard(&guard);
102      *     {
103      *         // will abort if you call getCalling*, unless you are
104      *         // serving a nested binder transaction
105      *     }
106      *     restoreCallingSpGuard(orig);
107      */
108     struct SpGuard {
109         const void* address;
110         const char* context;
111     };
112     LIBBINDER_EXPORTED const SpGuard* pushGetCallingSpGuard(const SpGuard* guard);
113     LIBBINDER_EXPORTED void restoreGetCallingSpGuard(const SpGuard* guard);
114     /**
115      * Used internally by getCalling*. Can also be used to assert that
116      * you are in a binder context (getCalling* is valid). This is
117      * intentionally not exposed as a boolean API since code should be
118      * written to know its environment.
119      */
120     LIBBINDER_EXPORTED void checkContextIsBinderForUse(const char* use) const;
121 
122     LIBBINDER_EXPORTED void setStrictModePolicy(int32_t policy);
123     LIBBINDER_EXPORTED int32_t getStrictModePolicy() const;
124 
125     // See Binder#setCallingWorkSourceUid in Binder.java.
126     LIBBINDER_EXPORTED int64_t setCallingWorkSourceUid(uid_t uid);
127     // Internal only. Use setCallingWorkSourceUid(uid) instead.
128     LIBBINDER_EXPORTED int64_t setCallingWorkSourceUidWithoutPropagation(uid_t uid);
129     // See Binder#getCallingWorkSourceUid in Binder.java.
130     LIBBINDER_EXPORTED uid_t getCallingWorkSourceUid() const;
131     // See Binder#clearCallingWorkSource in Binder.java.
132     LIBBINDER_EXPORTED int64_t clearCallingWorkSource();
133     // See Binder#restoreCallingWorkSource in Binder.java.
134     LIBBINDER_EXPORTED void restoreCallingWorkSource(int64_t token);
135     LIBBINDER_EXPORTED void clearPropagateWorkSource();
136     LIBBINDER_EXPORTED bool shouldPropagateWorkSource() const;
137 
138     LIBBINDER_EXPORTED void setLastTransactionBinderFlags(int32_t flags);
139     LIBBINDER_EXPORTED int32_t getLastTransactionBinderFlags() const;
140 
141     LIBBINDER_EXPORTED void setCallRestriction(CallRestriction restriction);
142     LIBBINDER_EXPORTED CallRestriction getCallRestriction() const;
143 
144     LIBBINDER_EXPORTED int64_t clearCallingIdentity();
145     // Restores PID/UID (not SID)
146     LIBBINDER_EXPORTED void restoreCallingIdentity(int64_t token);
147     LIBBINDER_EXPORTED bool hasExplicitIdentity();
148 
149     // For main functions - dangerous for libraries to use
150     LIBBINDER_EXPORTED status_t setupPolling(int* fd);
151     LIBBINDER_EXPORTED status_t handlePolledCommands();
152     LIBBINDER_EXPORTED void flushCommands();
153     LIBBINDER_EXPORTED bool flushIfNeeded();
154 
155     // Adds the current thread into the binder threadpool.
156     //
157     // This is in addition to any threads which are started
158     // with startThreadPool. Libraries should not call this
159     // function, as they may be loaded into processes which
160     // try to configure the threadpool differently.
161     LIBBINDER_EXPORTED void joinThreadPool(bool isMain = true);
162 
163     // Stop the local process.
164     LIBBINDER_EXPORTED void stopProcess(bool immediate = true);
165 
166     LIBBINDER_EXPORTED status_t transact(int32_t handle, uint32_t code, const Parcel& data,
167                                          Parcel* reply, uint32_t flags);
168 
169     LIBBINDER_EXPORTED void incStrongHandle(int32_t handle, BpBinder* proxy);
170     LIBBINDER_EXPORTED void decStrongHandle(int32_t handle);
171     LIBBINDER_EXPORTED void incWeakHandle(int32_t handle, BpBinder* proxy);
172     LIBBINDER_EXPORTED void decWeakHandle(int32_t handle);
173     LIBBINDER_EXPORTED status_t attemptIncStrongHandle(int32_t handle);
174     LIBBINDER_EXPORTED static void expungeHandle(int32_t handle, IBinder* binder);
175     LIBBINDER_EXPORTED status_t requestDeathNotification(int32_t handle, BpBinder* proxy);
176     LIBBINDER_EXPORTED status_t clearDeathNotification(int32_t handle, BpBinder* proxy);
177 
178     LIBBINDER_EXPORTED static void shutdown();
179 
180     // Call this to disable switching threads to background scheduling when
181     // receiving incoming IPC calls.  This is specifically here for the
182     // Android system process, since it expects to have background apps calling
183     // in to it but doesn't want to acquire locks in its services while in
184     // the background.
185     LIBBINDER_EXPORTED static void disableBackgroundScheduling(bool disable);
186     LIBBINDER_EXPORTED bool backgroundSchedulingDisabled();
187 
188     // Call blocks until the number of executing binder threads is less than
189     // the maximum number of binder threads threads allowed for this process.
190     LIBBINDER_EXPORTED void blockUntilThreadAvailable();
191 
192     // Service manager registration
193     LIBBINDER_EXPORTED void setTheContextObject(const sp<BBinder>& obj);
194 
195     // WARNING: DO NOT USE THIS API
196     //
197     // Returns a pointer to the stack from the last time a transaction
198     // was initiated by the kernel. Used to compare when making nested
199     // calls between multiple different transports.
200     LIBBINDER_EXPORTED const void* getServingStackPointer() const;
201 
202     // The work source represents the UID of the process we should attribute the transaction
203     // to. We use -1 to specify that the work source was not set using #setWorkSource.
204     //
205     // This constant needs to be kept in sync with Binder.UNSET_WORKSOURCE from the Java
206     // side.
207     LIBBINDER_EXPORTED static const int32_t kUnsetWorkSource = -1;
208 
209 private:
210     IPCThreadState();
211     ~IPCThreadState();
212 
213     status_t sendReply(const Parcel& reply, uint32_t flags);
214     status_t waitForResponse(Parcel* reply, status_t* acquireResult = nullptr);
215     status_t talkWithDriver(bool doReceive = true);
216     status_t writeTransactionData(int32_t cmd, uint32_t binderFlags, int32_t handle, uint32_t code,
217                                   const Parcel& data, status_t* statusBuffer);
218     status_t getAndExecuteCommand();
219     status_t executeCommand(int32_t command);
220     void processPendingDerefs();
221     void processPostWriteDerefs();
222 
223     void clearCaller();
224 
225     static  void                threadDestructor(void *st);
226     static void freeBuffer(const uint8_t* data, size_t dataSize, const binder_size_t* objects,
227                            size_t objectsSize);
228     static  void                logExtendedError();
229 
230     const   sp<ProcessState>    mProcess;
231             Vector<BBinder*>    mPendingStrongDerefs;
232             Vector<RefBase::weakref_type*> mPendingWeakDerefs;
233             Vector<RefBase*>    mPostWriteStrongDerefs;
234             Vector<RefBase::weakref_type*> mPostWriteWeakDerefs;
235             Parcel              mIn;
236             Parcel              mOut;
237             status_t            mLastError;
238             const void*         mServingStackPointer;
239             const SpGuard* mServingStackPointerGuard;
240             pid_t               mCallingPid;
241             const char*         mCallingSid;
242             uid_t               mCallingUid;
243             // The UID of the process who is responsible for this transaction.
244             // This is used for resource attribution.
245             int32_t             mWorkSource;
246             // Whether the work source should be propagated.
247             bool                mPropagateWorkSource;
248             bool                mIsLooper;
249             bool mIsFlushing;
250             bool mHasExplicitIdentity;
251             int32_t             mStrictModePolicy;
252             int32_t             mLastTransactionBinderFlags;
253             CallRestriction     mCallRestriction;
254 };
255 
256 } // namespace android
257 
258 // ---------------------------------------------------------------------------
259