blob: 0755a22ab2eacab7b00162356092d619422333f3 [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 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
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070017#define LOG_TAG "IncrementalService"
18
Songchun Fan3c82a302019-11-29 14:23:45 -080019#include "ServiceWrappers.h"
20
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070021#include <MountRegistry.h>
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070022#include <android-base/logging.h>
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070023#include <android/content/pm/IDataLoaderManager.h>
24#include <android/os/IVold.h>
25#include <binder/AppOpsManager.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080026#include <utils/String16.h>
27
Songchun Fan374f7652020-08-20 08:40:29 -070028#include <filesystem>
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -070029#include <thread>
30
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070031#include "IncrementalServiceValidation.h"
32
Songchun Fan3c82a302019-11-29 14:23:45 -080033using namespace std::literals;
34
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070035namespace android::incremental {
Songchun Fan3c82a302019-11-29 14:23:45 -080036
37static constexpr auto kVoldServiceName = "vold"sv;
Songchun Fan68645c42020-02-27 15:57:35 -080038static constexpr auto kDataLoaderManagerName = "dataloader_manager"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080039
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070040class RealVoldService : public VoldServiceWrapper {
41public:
Yurii Zubrytskyi510037b2020-04-22 15:46:21 -070042 RealVoldService(sp<os::IVold> vold) : mInterface(std::move(vold)) {}
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070043 ~RealVoldService() = default;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070044 binder::Status mountIncFs(
45 const std::string& backingPath, const std::string& targetDir, int32_t flags,
46 os::incremental::IncrementalFileSystemControlParcel* _aidl_return) const final {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070047 return mInterface->mountIncFs(backingPath, targetDir, flags, _aidl_return);
48 }
49 binder::Status unmountIncFs(const std::string& dir) const final {
50 return mInterface->unmountIncFs(dir);
51 }
52 binder::Status bindMount(const std::string& sourceDir,
53 const std::string& targetDir) const final {
54 return mInterface->bindMount(sourceDir, targetDir);
55 }
56 binder::Status setIncFsMountOptions(
57 const ::android::os::incremental::IncrementalFileSystemControlParcel& control,
Alex Buynytskyyc144cc42021-03-31 22:19:42 -070058 bool enableReadLogs, bool enableReadTimeouts) const final {
59 return mInterface->setIncFsMountOptions(control, enableReadLogs, enableReadTimeouts);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070060 }
61
62private:
63 sp<os::IVold> mInterface;
64};
65
66class RealDataLoaderManager : public DataLoaderManagerWrapper {
67public:
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070068 RealDataLoaderManager(sp<content::pm::IDataLoaderManager> manager)
69 : mInterface(std::move(manager)) {}
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070070 ~RealDataLoaderManager() = default;
Alex Buynytskyyea1390f2020-04-22 16:08:50 -070071 binder::Status bindToDataLoader(MountId mountId,
72 const content::pm::DataLoaderParamsParcel& params,
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080073 int bindDelayMs,
Alex Buynytskyyea1390f2020-04-22 16:08:50 -070074 const sp<content::pm::IDataLoaderStatusListener>& listener,
75 bool* _aidl_return) const final {
Alex Buynytskyyb19ee3e2021-02-06 20:31:43 -080076 return mInterface->bindToDataLoader(mountId, params, bindDelayMs, listener, _aidl_return);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070077 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -070078 binder::Status getDataLoader(MountId mountId,
79 sp<content::pm::IDataLoader>* _aidl_return) const final {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070080 return mInterface->getDataLoader(mountId, _aidl_return);
81 }
Alex Buynytskyyea1390f2020-04-22 16:08:50 -070082 binder::Status unbindFromDataLoader(MountId mountId) const final {
83 return mInterface->unbindFromDataLoader(mountId);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -070084 }
85
86private:
87 sp<content::pm::IDataLoaderManager> mInterface;
88};
89
90class RealAppOpsManager : public AppOpsManagerWrapper {
91public:
92 ~RealAppOpsManager() = default;
93 binder::Status checkPermission(const char* permission, const char* operation,
94 const char* package) const final {
95 return android::incremental::CheckPermissionForDataDelivery(permission, operation, package);
96 }
97 void startWatchingMode(int32_t op, const String16& packageName,
98 const sp<IAppOpsCallback>& callback) final {
99 mAppOpsManager.startWatchingMode(op, packageName, callback);
100 }
101 void stopWatchingMode(const sp<IAppOpsCallback>& callback) final {
102 mAppOpsManager.stopWatchingMode(callback);
103 }
104
105private:
106 android::AppOpsManager mAppOpsManager;
107};
108
109class RealJniWrapper final : public JniWrapper {
110public:
111 RealJniWrapper(JavaVM* jvm);
112 void initializeForCurrentThread() const final;
113
114 static JavaVM* getJvm(JNIEnv* env);
115
116private:
117 JavaVM* const mJvm;
118};
119
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700120class RealLooperWrapper final : public LooperWrapper {
121public:
122 int addFd(int fd, int ident, int events, android::Looper_callbackFunc callback,
123 void* data) final {
124 return mLooper.addFd(fd, ident, events, callback, data);
125 }
126 int removeFd(int fd) final { return mLooper.removeFd(fd); }
127 void wake() final { return mLooper.wake(); }
128 int pollAll(int timeoutMillis) final { return mLooper.pollAll(timeoutMillis); }
129
130private:
131 struct Looper : public android::Looper {
132 Looper() : android::Looper(/*allowNonCallbacks=*/false) {}
133 ~Looper() {}
134 } mLooper;
135};
136
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -0700137std::string IncFsWrapper::toString(FileId fileId) {
138 return incfs::toString(fileId);
139}
140
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -0800141class RealIncFs final : public IncFsWrapper {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700142public:
143 RealIncFs() = default;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700144 ~RealIncFs() final = default;
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -0800145 Features features() const final { return incfs::features(); }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700146 void listExistingMounts(const ExistingMountCallback& cb) const final {
147 for (auto mount : incfs::defaultMountRegistry().copyMounts()) {
148 auto binds = mount.binds(); // span() doesn't like rvalue containers, needs to save it.
149 cb(mount.root(), mount.backingDir(), binds);
150 }
151 }
152 Control openMount(std::string_view path) const final { return incfs::open(path); }
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800153 Control createControl(IncFsFd cmd, IncFsFd pendingReads, IncFsFd logs,
154 IncFsFd blocksWritten) const final {
155 return incfs::createControl(cmd, pendingReads, logs, blocksWritten);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700156 }
157 ErrorCode makeFile(const Control& control, std::string_view path, int mode, FileId id,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700158 incfs::NewFileParams params) const final {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700159 return incfs::makeFile(control, path, mode, id, params);
160 }
Yurii Zubrytskyia5946f72021-02-17 14:24:14 -0800161 ErrorCode makeMappedFile(const Control& control, std::string_view path, int mode,
162 incfs::NewMappedFileParams params) const final {
163 return incfs::makeMappedFile(control, path, mode, params);
164 }
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700165 ErrorCode makeDir(const Control& control, std::string_view path, int mode) const final {
166 return incfs::makeDir(control, path, mode);
167 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700168 ErrorCode makeDirs(const Control& control, std::string_view path, int mode) const final {
169 return incfs::makeDirs(control, path, mode);
170 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700171 incfs::RawMetadata getMetadata(const Control& control, FileId fileid) const final {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700172 return incfs::getMetadata(control, fileid);
173 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700174 incfs::RawMetadata getMetadata(const Control& control, std::string_view path) const final {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700175 return incfs::getMetadata(control, path);
176 }
177 FileId getFileId(const Control& control, std::string_view path) const final {
178 return incfs::getFileId(control, path);
179 }
Songchun Fan374f7652020-08-20 08:40:29 -0700180 std::pair<IncFsBlockIndex, IncFsBlockIndex> countFilledBlocks(
181 const Control& control, std::string_view path) const final {
Yurii Zubrytskyi4375a742021-03-18 16:59:47 -0700182 if (incfs::features() & Features::v2) {
183 const auto counts = incfs::getBlockCount(control, path);
184 if (!counts) {
185 return {-errno, -errno};
186 }
187 return {counts->filledDataBlocks + counts->filledHashBlocks,
188 counts->totalDataBlocks + counts->totalHashBlocks};
189 }
Songchun Fan374f7652020-08-20 08:40:29 -0700190 const auto fileId = incfs::getFileId(control, path);
191 const auto fd = incfs::openForSpecialOps(control, fileId);
192 int res = fd.get();
193 if (!fd.ok()) {
194 return {res, res};
195 }
196 const auto ranges = incfs::getFilledRanges(res);
197 res = ranges.first;
198 if (res) {
199 return {res, res};
200 }
201 const auto totalBlocksCount = ranges.second.internalRawRanges().endIndex;
202 int filledBlockCount = 0;
203 for (const auto& dataRange : ranges.second.dataRanges()) {
204 filledBlockCount += dataRange.size();
205 }
206 for (const auto& hashRange : ranges.second.hashRanges()) {
207 filledBlockCount += hashRange.size();
208 }
209 return {filledBlockCount, totalBlocksCount};
210 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -0700211 incfs::LoadingState isFileFullyLoaded(const Control& control,
212 std::string_view path) const final {
213 return incfs::isFullyLoaded(control, path);
214 }
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -0700215 incfs::LoadingState isFileFullyLoaded(const Control& control, FileId id) const final {
216 return incfs::isFullyLoaded(control, id);
217 }
Yurii Zubrytskyi256a1a42021-03-18 14:21:54 -0700218 incfs::LoadingState isEverythingFullyLoaded(const Control& control) const final {
219 return incfs::isEverythingFullyLoaded(control);
220 }
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700221 ErrorCode link(const Control& control, std::string_view from, std::string_view to) const final {
222 return incfs::link(control, from, to);
223 }
224 ErrorCode unlink(const Control& control, std::string_view path) const final {
225 return incfs::unlink(control, path);
226 }
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -0700227 incfs::UniqueFd openForSpecialOps(const Control& control, FileId id) const final {
228 return incfs::openForSpecialOps(control, id);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700229 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700230 ErrorCode writeBlocks(std::span<const incfs::DataBlock> blocks) const final {
231 return incfs::writeBlocks({blocks.data(), size_t(blocks.size())});
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700232 }
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -0700233 ErrorCode reserveSpace(const Control& control, FileId id, IncFsSize size) const final {
234 return incfs::reserveSpace(control, id, size);
Yurii Zubrytskyi65fc38a2021-03-17 13:18:30 -0700235 }
Alex Buynytskyyc144cc42021-03-31 22:19:42 -0700236 WaitResult waitForPendingReads(
237 const Control& control, std::chrono::milliseconds timeout,
238 std::vector<incfs::ReadInfoWithUid>* pendingReadsBuffer) const final {
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700239 return incfs::waitForPendingReads(control, timeout, pendingReadsBuffer);
240 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800241 ErrorCode setUidReadTimeouts(const Control& control,
242 const std::vector<android::os::incremental::PerUidReadTimeouts>&
243 perUidReadTimeouts) const final {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -0700244 std::vector<incfs::UidReadTimeouts> timeouts(perUidReadTimeouts.size());
Alex Buynytskyyfe6b4c02021-01-26 13:29:24 -0800245 for (int i = 0, size = perUidReadTimeouts.size(); i < size; ++i) {
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -0700246 auto& timeout = timeouts[i];
Alex Buynytskyyfe6b4c02021-01-26 13:29:24 -0800247 const auto& perUidTimeout = perUidReadTimeouts[i];
248 timeout.uid = perUidTimeout.uid;
249 timeout.minTimeUs = perUidTimeout.minTimeUs;
250 timeout.minPendingTimeUs = perUidTimeout.minPendingTimeUs;
251 timeout.maxPendingTimeUs = perUidTimeout.maxPendingTimeUs;
252 }
253 return incfs::setUidReadTimeouts(control, timeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800254 }
Yurii Zubrytskyi4cd24922021-03-24 00:46:29 -0700255 ErrorCode forEachFile(const Control& control, FileCallback cb) const final {
256 return incfs::forEachFile(control,
257 [&](auto& control, FileId id) { return cb(control, id); });
258 }
259 ErrorCode forEachIncompleteFile(const Control& control, FileCallback cb) const final {
260 return incfs::forEachIncompleteFile(control, [&](auto& control, FileId id) {
261 return cb(control, id);
262 });
263 }
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700264};
265
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700266static JNIEnv* getOrAttachJniEnv(JavaVM* jvm);
267
Yurii Zubrytskyi0583e7f2021-03-19 17:00:12 -0700268class RealTimedQueueWrapper final : public TimedQueueWrapper {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700269public:
270 RealTimedQueueWrapper(JavaVM* jvm) {
271 mThread = std::thread([this, jvm]() {
272 (void)getOrAttachJniEnv(jvm);
273 runTimers();
274 });
275 }
276 ~RealTimedQueueWrapper() final {
277 CHECK(!mRunning) << "call stop first";
278 CHECK(!mThread.joinable()) << "call stop first";
279 }
280
Yurii Zubrytskyi0583e7f2021-03-19 17:00:12 -0700281 void addJob(MountId id, Milliseconds timeout, Job what) final {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700282 const auto now = Clock::now();
283 {
284 std::unique_lock lock(mMutex);
Yurii Zubrytskyi0583e7f2021-03-19 17:00:12 -0700285 mJobs.insert(TimedJob{id, now + timeout, std::move(what)});
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700286 }
287 mCondition.notify_all();
288 }
289 void removeJobs(MountId id) final {
290 std::unique_lock lock(mMutex);
291 std::erase_if(mJobs, [id](auto&& item) { return item.id == id; });
292 }
293 void stop() final {
294 {
295 std::unique_lock lock(mMutex);
296 mRunning = false;
297 }
298 mCondition.notify_all();
299 mThread.join();
300 mJobs.clear();
301 }
302
303private:
304 void runTimers() {
305 static constexpr TimePoint kInfinityTs{Clock::duration::max()};
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700306 std::unique_lock lock(mMutex);
307 for (;;) {
Yurii Zubrytskyi0583e7f2021-03-19 17:00:12 -0700308 const TimePoint nextJobTs = mJobs.empty() ? kInfinityTs : mJobs.begin()->when;
309 mCondition.wait_until(lock, nextJobTs, [this, oldNextJobTs = nextJobTs]() {
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700310 const auto now = Clock::now();
Yurii Zubrytskyi0583e7f2021-03-19 17:00:12 -0700311 const auto newFirstJobTs = !mJobs.empty() ? mJobs.begin()->when : kInfinityTs;
312 return newFirstJobTs <= now || newFirstJobTs < oldNextJobTs || !mRunning;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700313 });
314 if (!mRunning) {
315 return;
316 }
317
318 const auto now = Clock::now();
Yurii Zubrytskyi0583e7f2021-03-19 17:00:12 -0700319 // Always re-acquire begin(). We can't use it after unlock as mTimedJobs can change.
320 for (auto it = mJobs.begin(); it != mJobs.end() && it->when <= now;
321 it = mJobs.begin()) {
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -0800322 auto jobNode = mJobs.extract(it);
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700323
324 lock.unlock();
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -0800325 jobNode.value().what();
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700326 lock.lock();
327 }
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700328 }
329 }
330
331 struct TimedJob {
332 MountId id;
333 TimePoint when;
334 Job what;
335 friend bool operator<(const TimedJob& lhs, const TimedJob& rhs) {
336 return lhs.when < rhs.when;
337 }
338 };
339 bool mRunning = true;
Yurii Zubrytskyi0583e7f2021-03-19 17:00:12 -0700340 std::multiset<TimedJob> mJobs;
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700341 std::condition_variable mCondition;
342 std::mutex mMutex;
343 std::thread mThread;
344};
345
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -0800346class RealFsWrapper final : public FsWrapper {
Songchun Fan374f7652020-08-20 08:40:29 -0700347public:
348 RealFsWrapper() = default;
349 ~RealFsWrapper() = default;
350
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -0800351 void listFilesRecursive(std::string_view directoryPath, FileCallback onFile) const final {
Songchun Fan374f7652020-08-20 08:40:29 -0700352 for (const auto& entry : std::filesystem::recursive_directory_iterator(directoryPath)) {
353 if (!entry.is_regular_file()) {
354 continue;
355 }
Yurii Zubrytskyi3fde5722021-02-19 00:08:36 -0800356 if (!onFile(entry.path().native())) {
357 break;
358 }
Songchun Fan374f7652020-08-20 08:40:29 -0700359 }
Songchun Fan374f7652020-08-20 08:40:29 -0700360 }
361};
362
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800363class RealClockWrapper final : public ClockWrapper {
364public:
365 RealClockWrapper() = default;
366 ~RealClockWrapper() = default;
367
368 TimePoint now() const final { return Clock::now(); }
369};
370
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700371RealServiceManager::RealServiceManager(sp<IServiceManager> serviceManager, JNIEnv* env)
372 : mServiceManager(std::move(serviceManager)), mJvm(RealJniWrapper::getJvm(env)) {}
Songchun Fan3c82a302019-11-29 14:23:45 -0800373
374template <class INTERFACE>
375sp<INTERFACE> RealServiceManager::getRealService(std::string_view serviceName) const {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800376 sp<IBinder> binder =
377 mServiceManager->getService(String16(serviceName.data(), serviceName.size()));
378 if (!binder) {
379 return nullptr;
Songchun Fan3c82a302019-11-29 14:23:45 -0800380 }
381 return interface_cast<INTERFACE>(binder);
382}
383
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800384std::unique_ptr<VoldServiceWrapper> RealServiceManager::getVoldService() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800385 sp<os::IVold> vold = RealServiceManager::getRealService<os::IVold>(kVoldServiceName);
386 if (vold != 0) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800387 return std::make_unique<RealVoldService>(vold);
Songchun Fan3c82a302019-11-29 14:23:45 -0800388 }
389 return nullptr;
390}
391
Songchun Fan68645c42020-02-27 15:57:35 -0800392std::unique_ptr<DataLoaderManagerWrapper> RealServiceManager::getDataLoaderManager() {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700393 sp<content::pm::IDataLoaderManager> manager =
394 RealServiceManager::getRealService<content::pm::IDataLoaderManager>(
395 kDataLoaderManagerName);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800396 if (manager) {
Songchun Fan68645c42020-02-27 15:57:35 -0800397 return std::make_unique<RealDataLoaderManager>(manager);
Songchun Fan3c82a302019-11-29 14:23:45 -0800398 }
399 return nullptr;
400}
401
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800402std::unique_ptr<IncFsWrapper> RealServiceManager::getIncFs() {
403 return std::make_unique<RealIncFs>();
Songchun Fan3c82a302019-11-29 14:23:45 -0800404}
405
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700406std::unique_ptr<AppOpsManagerWrapper> RealServiceManager::getAppOpsManager() {
407 return std::make_unique<RealAppOpsManager>();
408}
409
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700410std::unique_ptr<JniWrapper> RealServiceManager::getJni() {
411 return std::make_unique<RealJniWrapper>(mJvm);
412}
413
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700414std::unique_ptr<LooperWrapper> RealServiceManager::getLooper() {
415 return std::make_unique<RealLooperWrapper>();
416}
417
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700418std::unique_ptr<TimedQueueWrapper> RealServiceManager::getTimedQueue() {
419 return std::make_unique<RealTimedQueueWrapper>(mJvm);
420}
421
Songchun Fana7098592020-09-03 11:45:53 -0700422std::unique_ptr<TimedQueueWrapper> RealServiceManager::getProgressUpdateJobQueue() {
423 return std::make_unique<RealTimedQueueWrapper>(mJvm);
424}
425
Songchun Fan374f7652020-08-20 08:40:29 -0700426std::unique_ptr<FsWrapper> RealServiceManager::getFs() {
427 return std::make_unique<RealFsWrapper>();
428}
429
Alex Buynytskyy7e06d712021-03-09 19:24:23 -0800430std::unique_ptr<ClockWrapper> RealServiceManager::getClock() {
431 return std::make_unique<RealClockWrapper>();
432}
433
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700434static JavaVM* getJavaVm(JNIEnv* env) {
435 CHECK(env);
436 JavaVM* jvm = nullptr;
437 env->GetJavaVM(&jvm);
438 CHECK(jvm);
439 return jvm;
440}
441
442static JNIEnv* getJniEnv(JavaVM* vm) {
443 JNIEnv* env;
444 if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
445 return nullptr;
446 }
447 return env;
448}
449
450static JNIEnv* getOrAttachJniEnv(JavaVM* jvm) {
451 if (!jvm) {
452 LOG(ERROR) << "No JVM instance";
453 return nullptr;
454 }
455
456 JNIEnv* env = getJniEnv(jvm);
457 if (!env) {
458 int result = jvm->AttachCurrentThread(&env, nullptr);
459 if (result != JNI_OK) {
460 LOG(ERROR) << "JVM thread attach failed: " << result;
461 return nullptr;
462 }
463 struct VmDetacher {
464 VmDetacher(JavaVM* vm) : mVm(vm) {}
465 ~VmDetacher() { mVm->DetachCurrentThread(); }
466
467 private:
468 JavaVM* const mVm;
469 };
470 static thread_local VmDetacher detacher(jvm);
471 }
472
473 return env;
474}
475
476RealJniWrapper::RealJniWrapper(JavaVM* jvm) : mJvm(jvm) {
477 CHECK(!!mJvm) << "JVM is unavailable";
478}
479
480void RealJniWrapper::initializeForCurrentThread() const {
481 (void)getOrAttachJniEnv(mJvm);
482}
483
484JavaVM* RealJniWrapper::getJvm(JNIEnv* env) {
485 return getJavaVm(env);
486}
487
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700488} // namespace android::incremental