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