blob: 659d6503e11c2212f70b749767782a8461d5d00b [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,
58 bool enableReadLogs) const final {
59 return mInterface->setIncFsMountOptions(control, enableReadLogs);
60 }
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 Zubrytskyi86321402020-04-09 19:22:30 -0700137class RealIncFs : public IncFsWrapper {
138public:
139 RealIncFs() = default;
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700140 ~RealIncFs() final = default;
141 void listExistingMounts(const ExistingMountCallback& cb) const final {
142 for (auto mount : incfs::defaultMountRegistry().copyMounts()) {
143 auto binds = mount.binds(); // span() doesn't like rvalue containers, needs to save it.
144 cb(mount.root(), mount.backingDir(), binds);
145 }
146 }
147 Control openMount(std::string_view path) const final { return incfs::open(path); }
Yurii Zubrytskyi5f692922020-12-08 07:35:24 -0800148 Control createControl(IncFsFd cmd, IncFsFd pendingReads, IncFsFd logs,
149 IncFsFd blocksWritten) const final {
150 return incfs::createControl(cmd, pendingReads, logs, blocksWritten);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700151 }
152 ErrorCode makeFile(const Control& control, std::string_view path, int mode, FileId id,
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700153 incfs::NewFileParams params) const final {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700154 return incfs::makeFile(control, path, mode, id, params);
155 }
156 ErrorCode makeDir(const Control& control, std::string_view path, int mode) const final {
157 return incfs::makeDir(control, path, mode);
158 }
Yurii Zubrytskyiefebb452020-04-22 13:59:06 -0700159 ErrorCode makeDirs(const Control& control, std::string_view path, int mode) const final {
160 return incfs::makeDirs(control, path, mode);
161 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700162 incfs::RawMetadata getMetadata(const Control& control, FileId fileid) const final {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700163 return incfs::getMetadata(control, fileid);
164 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700165 incfs::RawMetadata getMetadata(const Control& control, std::string_view path) const final {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700166 return incfs::getMetadata(control, path);
167 }
168 FileId getFileId(const Control& control, std::string_view path) const final {
169 return incfs::getFileId(control, path);
170 }
Songchun Fan6944f1e2020-11-06 15:24:24 -0800171 std::string toString(FileId fileId) const final { return incfs::toString(fileId); }
Songchun Fan374f7652020-08-20 08:40:29 -0700172 std::pair<IncFsBlockIndex, IncFsBlockIndex> countFilledBlocks(
173 const Control& control, std::string_view path) const final {
174 const auto fileId = incfs::getFileId(control, path);
175 const auto fd = incfs::openForSpecialOps(control, fileId);
176 int res = fd.get();
177 if (!fd.ok()) {
178 return {res, res};
179 }
180 const auto ranges = incfs::getFilledRanges(res);
181 res = ranges.first;
182 if (res) {
183 return {res, res};
184 }
185 const auto totalBlocksCount = ranges.second.internalRawRanges().endIndex;
186 int filledBlockCount = 0;
187 for (const auto& dataRange : ranges.second.dataRanges()) {
188 filledBlockCount += dataRange.size();
189 }
190 for (const auto& hashRange : ranges.second.hashRanges()) {
191 filledBlockCount += hashRange.size();
192 }
193 return {filledBlockCount, totalBlocksCount};
194 }
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700195 ErrorCode link(const Control& control, std::string_view from, std::string_view to) const final {
196 return incfs::link(control, from, to);
197 }
198 ErrorCode unlink(const Control& control, std::string_view path) const final {
199 return incfs::unlink(control, path);
200 }
Alex Buynytskyybc0a7e62020-08-25 12:45:22 -0700201 incfs::UniqueFd openForSpecialOps(const Control& control, FileId id) const final {
202 return incfs::openForSpecialOps(control, id);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700203 }
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700204 ErrorCode writeBlocks(std::span<const incfs::DataBlock> blocks) const final {
205 return incfs::writeBlocks({blocks.data(), size_t(blocks.size())});
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700206 }
Alex Buynytskyy8ef61ae2020-05-08 16:18:52 -0700207 WaitResult waitForPendingReads(const Control& control, std::chrono::milliseconds timeout,
208 std::vector<incfs::ReadInfo>* pendingReadsBuffer) const final {
209 return incfs::waitForPendingReads(control, timeout, pendingReadsBuffer);
210 }
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800211 ErrorCode setUidReadTimeouts(const Control& control,
212 const std::vector<android::os::incremental::PerUidReadTimeouts>&
213 perUidReadTimeouts) const final {
Alex Buynytskyyfe6b4c02021-01-26 13:29:24 -0800214 std::vector<incfs::UidReadTimeouts> timeouts;
215 timeouts.resize(perUidReadTimeouts.size());
216 for (int i = 0, size = perUidReadTimeouts.size(); i < size; ++i) {
217 auto&& timeout = timeouts[i];
218 const auto& perUidTimeout = perUidReadTimeouts[i];
219 timeout.uid = perUidTimeout.uid;
220 timeout.minTimeUs = perUidTimeout.minTimeUs;
221 timeout.minPendingTimeUs = perUidTimeout.minPendingTimeUs;
222 timeout.maxPendingTimeUs = perUidTimeout.maxPendingTimeUs;
223 }
Alex Buynytskyy07694ed2021-01-27 06:58:55 -0800224
Alex Buynytskyyfe6b4c02021-01-26 13:29:24 -0800225 return incfs::setUidReadTimeouts(control, timeouts);
Alex Buynytskyyaa8e95e2020-12-14 21:50:04 -0800226 }
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700227};
228
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700229static JNIEnv* getOrAttachJniEnv(JavaVM* jvm);
230
231class RealTimedQueueWrapper : public TimedQueueWrapper {
232public:
233 RealTimedQueueWrapper(JavaVM* jvm) {
234 mThread = std::thread([this, jvm]() {
235 (void)getOrAttachJniEnv(jvm);
236 runTimers();
237 });
238 }
239 ~RealTimedQueueWrapper() final {
240 CHECK(!mRunning) << "call stop first";
241 CHECK(!mThread.joinable()) << "call stop first";
242 }
243
244 void addJob(MountId id, Milliseconds after, Job what) final {
245 const auto now = Clock::now();
246 {
247 std::unique_lock lock(mMutex);
248 mJobs.insert(TimedJob{id, now + after, std::move(what)});
249 }
250 mCondition.notify_all();
251 }
252 void removeJobs(MountId id) final {
253 std::unique_lock lock(mMutex);
254 std::erase_if(mJobs, [id](auto&& item) { return item.id == id; });
255 }
256 void stop() final {
257 {
258 std::unique_lock lock(mMutex);
259 mRunning = false;
260 }
261 mCondition.notify_all();
262 mThread.join();
263 mJobs.clear();
264 }
265
266private:
267 void runTimers() {
268 static constexpr TimePoint kInfinityTs{Clock::duration::max()};
269 TimePoint nextJobTs = kInfinityTs;
270 std::unique_lock lock(mMutex);
271 for (;;) {
272 mCondition.wait_until(lock, nextJobTs, [this, nextJobTs]() {
273 const auto now = Clock::now();
274 const auto firstJobTs = !mJobs.empty() ? mJobs.begin()->when : kInfinityTs;
275 return !mRunning || firstJobTs <= now || firstJobTs < nextJobTs;
276 });
277 if (!mRunning) {
278 return;
279 }
280
281 const auto now = Clock::now();
282 auto it = mJobs.begin();
283 // Always acquire begin(). We can't use it after unlock as mTimedJobs can change.
284 for (; it != mJobs.end() && it->when <= now; it = mJobs.begin()) {
285 auto job = std::move(it->what);
286 mJobs.erase(it);
287
288 lock.unlock();
289 job();
290 lock.lock();
291 }
292 nextJobTs = it != mJobs.end() ? it->when : kInfinityTs;
293 }
294 }
295
296 struct TimedJob {
297 MountId id;
298 TimePoint when;
299 Job what;
300 friend bool operator<(const TimedJob& lhs, const TimedJob& rhs) {
301 return lhs.when < rhs.when;
302 }
303 };
304 bool mRunning = true;
305 std::set<TimedJob> mJobs;
306 std::condition_variable mCondition;
307 std::mutex mMutex;
308 std::thread mThread;
309};
310
Songchun Fan374f7652020-08-20 08:40:29 -0700311class RealFsWrapper : public FsWrapper {
312public:
313 RealFsWrapper() = default;
314 ~RealFsWrapper() = default;
315
316 std::vector<std::string> listFilesRecursive(std::string_view directoryPath) const final {
317 std::vector<std::string> files;
318 for (const auto& entry : std::filesystem::recursive_directory_iterator(directoryPath)) {
319 if (!entry.is_regular_file()) {
320 continue;
321 }
322 files.push_back(entry.path().c_str());
323 }
324 return files;
325 }
326};
327
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700328RealServiceManager::RealServiceManager(sp<IServiceManager> serviceManager, JNIEnv* env)
329 : mServiceManager(std::move(serviceManager)), mJvm(RealJniWrapper::getJvm(env)) {}
Songchun Fan3c82a302019-11-29 14:23:45 -0800330
331template <class INTERFACE>
332sp<INTERFACE> RealServiceManager::getRealService(std::string_view serviceName) const {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800333 sp<IBinder> binder =
334 mServiceManager->getService(String16(serviceName.data(), serviceName.size()));
335 if (!binder) {
336 return nullptr;
Songchun Fan3c82a302019-11-29 14:23:45 -0800337 }
338 return interface_cast<INTERFACE>(binder);
339}
340
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800341std::unique_ptr<VoldServiceWrapper> RealServiceManager::getVoldService() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800342 sp<os::IVold> vold = RealServiceManager::getRealService<os::IVold>(kVoldServiceName);
343 if (vold != 0) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800344 return std::make_unique<RealVoldService>(vold);
Songchun Fan3c82a302019-11-29 14:23:45 -0800345 }
346 return nullptr;
347}
348
Songchun Fan68645c42020-02-27 15:57:35 -0800349std::unique_ptr<DataLoaderManagerWrapper> RealServiceManager::getDataLoaderManager() {
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700350 sp<content::pm::IDataLoaderManager> manager =
351 RealServiceManager::getRealService<content::pm::IDataLoaderManager>(
352 kDataLoaderManagerName);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800353 if (manager) {
Songchun Fan68645c42020-02-27 15:57:35 -0800354 return std::make_unique<RealDataLoaderManager>(manager);
Songchun Fan3c82a302019-11-29 14:23:45 -0800355 }
356 return nullptr;
357}
358
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800359std::unique_ptr<IncFsWrapper> RealServiceManager::getIncFs() {
360 return std::make_unique<RealIncFs>();
Songchun Fan3c82a302019-11-29 14:23:45 -0800361}
362
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700363std::unique_ptr<AppOpsManagerWrapper> RealServiceManager::getAppOpsManager() {
364 return std::make_unique<RealAppOpsManager>();
365}
366
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700367std::unique_ptr<JniWrapper> RealServiceManager::getJni() {
368 return std::make_unique<RealJniWrapper>(mJvm);
369}
370
Alex Buynytskyycca2c112020-05-05 12:48:41 -0700371std::unique_ptr<LooperWrapper> RealServiceManager::getLooper() {
372 return std::make_unique<RealLooperWrapper>();
373}
374
Alex Buynytskyy46d3ddb2020-05-29 12:05:05 -0700375std::unique_ptr<TimedQueueWrapper> RealServiceManager::getTimedQueue() {
376 return std::make_unique<RealTimedQueueWrapper>(mJvm);
377}
378
Songchun Fana7098592020-09-03 11:45:53 -0700379std::unique_ptr<TimedQueueWrapper> RealServiceManager::getProgressUpdateJobQueue() {
380 return std::make_unique<RealTimedQueueWrapper>(mJvm);
381}
382
Songchun Fan374f7652020-08-20 08:40:29 -0700383std::unique_ptr<FsWrapper> RealServiceManager::getFs() {
384 return std::make_unique<RealFsWrapper>();
385}
386
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700387static JavaVM* getJavaVm(JNIEnv* env) {
388 CHECK(env);
389 JavaVM* jvm = nullptr;
390 env->GetJavaVM(&jvm);
391 CHECK(jvm);
392 return jvm;
393}
394
395static JNIEnv* getJniEnv(JavaVM* vm) {
396 JNIEnv* env;
397 if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
398 return nullptr;
399 }
400 return env;
401}
402
403static JNIEnv* getOrAttachJniEnv(JavaVM* jvm) {
404 if (!jvm) {
405 LOG(ERROR) << "No JVM instance";
406 return nullptr;
407 }
408
409 JNIEnv* env = getJniEnv(jvm);
410 if (!env) {
411 int result = jvm->AttachCurrentThread(&env, nullptr);
412 if (result != JNI_OK) {
413 LOG(ERROR) << "JVM thread attach failed: " << result;
414 return nullptr;
415 }
416 struct VmDetacher {
417 VmDetacher(JavaVM* vm) : mVm(vm) {}
418 ~VmDetacher() { mVm->DetachCurrentThread(); }
419
420 private:
421 JavaVM* const mVm;
422 };
423 static thread_local VmDetacher detacher(jvm);
424 }
425
426 return env;
427}
428
429RealJniWrapper::RealJniWrapper(JavaVM* jvm) : mJvm(jvm) {
430 CHECK(!!mJvm) << "JVM is unavailable";
431}
432
433void RealJniWrapper::initializeForCurrentThread() const {
434 (void)getOrAttachJniEnv(mJvm);
435}
436
437JavaVM* RealJniWrapper::getJvm(JNIEnv* env) {
438 return getJavaVm(env);
439}
440
Yurii Zubrytskyi629051fd2020-04-17 23:13:47 -0700441} // namespace android::incremental