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/IBinder.h>
21 #include <utils/String16.h>
22 #include <utils/String8.h>
23 
24 #include <pthread.h>
25 
26 #include <atomic>
27 #include <chrono>
28 #include <condition_variable>
29 #include <mutex>
30 
31 // ---------------------------------------------------------------------------
32 namespace android {
33 
34 class IPCThreadState;
35 
36 /**
37  * Kernel binder process state. All operations here refer to kernel binder. This
38  * object is allocated per process.
39  */
40 class ProcessState : public virtual RefBase {
41 public:
42     LIBBINDER_EXPORTED static sp<ProcessState> self();
43     LIBBINDER_EXPORTED static sp<ProcessState> selfOrNull();
44 
45     LIBBINDER_EXPORTED static bool isVndservicemanagerEnabled();
46 
47     /* initWithDriver() can be used to configure libbinder to use
48      * a different binder driver dev node. It must be called *before*
49      * any call to ProcessState::self(). The default is /dev/vndbinder
50      * for processes built with the VNDK and /dev/binder for those
51      * which are not.
52      *
53      * If this is called with nullptr, the behavior is the same as selfOrNull.
54      */
55     LIBBINDER_EXPORTED static sp<ProcessState> initWithDriver(const char* driver);
56 
57     LIBBINDER_EXPORTED sp<IBinder> getContextObject(const sp<IBinder>& caller);
58 
59     // This should be called before startThreadPool at the beginning
60     // of a program, and libraries should never call it because programs
61     // should configure their own threadpools. The threadpool size can
62     // never be decreased.
63     //
64     // The 'maxThreads' value refers to the total number of threads
65     // that will be started by the kernel. This is in addition to any
66     // threads started by 'startThreadPool' or 'joinRpcThreadpool'.
67     LIBBINDER_EXPORTED status_t setThreadPoolMaxThreadCount(size_t maxThreads);
68 
69     // Libraries should not call this, as processes should configure
70     // threadpools themselves. Should be called in the main function
71     // directly before any code executes or joins the threadpool.
72     //
73     // Starts one thread, PLUS those requested in setThreadPoolMaxThreadCount,
74     // PLUS those manually requested in joinThreadPool.
75     //
76     // For instance, if setThreadPoolMaxCount(3) is called and
77     // startThreadpPool (+1 thread) and joinThreadPool (+1 thread)
78     // are all called, then up to 5 threads can be started.
79     LIBBINDER_EXPORTED void startThreadPool();
80 
81     [[nodiscard]] LIBBINDER_EXPORTED bool becomeContextManager();
82 
83     LIBBINDER_EXPORTED sp<IBinder> getStrongProxyForHandle(int32_t handle);
84     LIBBINDER_EXPORTED void expungeHandle(int32_t handle, IBinder* binder);
85 
86     // TODO: deprecate.
87     LIBBINDER_EXPORTED void spawnPooledThread(bool isMain);
88 
89     LIBBINDER_EXPORTED status_t enableOnewaySpamDetection(bool enable);
90 
91     // Set the name of the current thread to look like a threadpool
92     // thread. Typically this is called before joinThreadPool.
93     //
94     // TODO: remove this API, and automatically set it intelligently.
95     LIBBINDER_EXPORTED void giveThreadPoolName();
96 
97     LIBBINDER_EXPORTED String8 getDriverName();
98 
99     LIBBINDER_EXPORTED ssize_t getKernelReferences(size_t count, uintptr_t* buf);
100 
101     // Only usable by the context manager.
102     // This refcount includes:
103     // 1. Strong references to the node by this and other processes
104     // 2. Temporary strong references held by the kernel during a
105     //    transaction on the node.
106     // It does NOT include local strong references to the node
107     LIBBINDER_EXPORTED ssize_t getStrongRefCountForNode(const sp<BpBinder>& binder);
108 
109     enum class CallRestriction {
110         // all calls okay
111         NONE,
112         // log when calls are blocking
113         ERROR_IF_NOT_ONEWAY,
114         // abort process on blocking calls
115         FATAL_IF_NOT_ONEWAY,
116     };
117     // Sets calling restrictions for all transactions in this process. This must be called
118     // before any threads are spawned.
119     LIBBINDER_EXPORTED void setCallRestriction(CallRestriction restriction);
120 
121     /**
122      * Get the max number of threads that have joined the thread pool.
123      * This includes kernel started threads, user joined threads and polling
124      * threads if used.
125      */
126     LIBBINDER_EXPORTED size_t getThreadPoolMaxTotalThreadCount() const;
127 
128     /**
129      * Check to see if the thread pool has started.
130      */
131     LIBBINDER_EXPORTED bool isThreadPoolStarted() const;
132 
133     enum class DriverFeature {
134         ONEWAY_SPAM_DETECTION,
135         EXTENDED_ERROR,
136         FREEZE_NOTIFICATION,
137     };
138     // Determine whether a feature is supported by the binder driver.
139     LIBBINDER_EXPORTED static bool isDriverFeatureEnabled(const DriverFeature feature);
140 
141 private:
142     static sp<ProcessState> init(const char* defaultDriver, bool requireDefault);
143 
144     static void onFork();
145     static void parentPostFork();
146     static void childPostFork();
147 
148     friend class IPCThreadState;
149     friend class sp<ProcessState>;
150 
151     explicit ProcessState(const char* driver);
152     ~ProcessState();
153 
154     ProcessState(const ProcessState& o);
155     ProcessState& operator=(const ProcessState& o);
156     String8 makeBinderThreadName();
157 
158     struct handle_entry {
159         IBinder* binder;
160         RefBase::weakref_type* refs;
161     };
162 
163     handle_entry* lookupHandleLocked(int32_t handle);
164 
165     String8 mDriverName;
166     int mDriverFD;
167     void* mVMStart;
168 
169     mutable std::mutex mOnThreadAvailableLock;
170     std::condition_variable mOnThreadAvailableCondVar;
171     // Number of threads waiting on `mOnThreadAvailableCondVar`.
172     std::atomic_int64_t mOnThreadAvailableWaiting = 0;
173 
174     // Number of binder threads current executing a command.
175     std::atomic_size_t mExecutingThreadsCount;
176     // Maximum number of lazy threads to be started in the threadpool by the kernel.
177     std::atomic_size_t mMaxThreads;
178     // Current number of threads inside the thread pool.
179     std::atomic_size_t mCurrentThreads;
180     // Current number of pooled threads inside the thread pool.
181     std::atomic_size_t mKernelStartedThreads;
182     // Time when thread pool was emptied
183     std::atomic<std::chrono::steady_clock::time_point> mStarvationStartTime;
184 
185     static constexpr auto never = &std::chrono::steady_clock::time_point::min;
186 
187     mutable std::mutex mLock; // protects everything below.
188 
189     Vector<handle_entry> mHandleToObject;
190 
191     bool mForked;
192     std::atomic_bool mThreadPoolStarted;
193     std::atomic_int32_t mThreadPoolSeq;
194 
195     CallRestriction mCallRestriction;
196 };
197 
198 } // namespace android
199 
200 // ---------------------------------------------------------------------------
201