blob: 5a88fc87857bdd5234e17c5c259db6d86363970e [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
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070020#include "IncrementalServiceValidation.h"
Songchun Fan3c82a302019-11-29 14:23:45 -080021
22#include <android-base/file.h>
23#include <android-base/logging.h>
24#include <android-base/properties.h>
25#include <android-base/stringprintf.h>
26#include <android-base/strings.h>
27#include <android/content/pm/IDataLoaderStatusListener.h>
28#include <android/os/IVold.h>
29#include <androidfw/ZipFileRO.h>
30#include <androidfw/ZipUtils.h>
31#include <binder/BinderService.h>
Jooyung Han66c567a2020-03-07 21:47:09 +090032#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080033#include <binder/ParcelFileDescriptor.h>
34#include <binder/Status.h>
35#include <sys/stat.h>
36#include <uuid/uuid.h>
37#include <zlib.h>
38
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070039#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080040#include <ctime>
Songchun Fan1124fd32020-02-10 12:49:41 -080041#include <filesystem>
Songchun Fan3c82a302019-11-29 14:23:45 -080042#include <iterator>
43#include <span>
44#include <stack>
45#include <thread>
46#include <type_traits>
47
48#include "Metadata.pb.h"
49
50using namespace std::literals;
51using namespace android::content::pm;
Songchun Fan1124fd32020-02-10 12:49:41 -080052namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080053
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070054constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
55constexpr const char* kOpUsage = "android:get_usage_stats";
56
Songchun Fan3c82a302019-11-29 14:23:45 -080057namespace android::incremental {
58
59namespace {
60
61using IncrementalFileSystemControlParcel =
62 ::android::os::incremental::IncrementalFileSystemControlParcel;
63
64struct Constants {
65 static constexpr auto backing = "backing_store"sv;
66 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080067 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080068 static constexpr auto storagePrefix = "st"sv;
69 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
70 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080071 static constexpr auto libDir = "lib"sv;
72 static constexpr auto libSuffix = ".so"sv;
73 static constexpr auto blockSize = 4096;
Songchun Fan3c82a302019-11-29 14:23:45 -080074};
75
76static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070077 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080078 return c;
79}
80
81template <base::LogSeverity level = base::ERROR>
82bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
83 auto cstr = path::c_str(name);
84 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080085 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080086 PLOG(level) << "Can't create directory '" << name << '\'';
87 return false;
88 }
89 struct stat st;
90 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
91 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
92 return false;
93 }
94 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080095 if (::chmod(cstr, mode)) {
96 PLOG(level) << "Changing permission failed for '" << name << '\'';
97 return false;
98 }
99
Songchun Fan3c82a302019-11-29 14:23:45 -0800100 return true;
101}
102
103static std::string toMountKey(std::string_view path) {
104 if (path.empty()) {
105 return "@none";
106 }
107 if (path == "/"sv) {
108 return "@root";
109 }
110 if (path::isAbsolute(path)) {
111 path.remove_prefix(1);
112 }
113 std::string res(path);
114 std::replace(res.begin(), res.end(), '/', '_');
115 std::replace(res.begin(), res.end(), '@', '_');
Songchun Fan1124fd32020-02-10 12:49:41 -0800116 return std::string(constants().mountKeyPrefix) + res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800117}
118
119static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
120 std::string_view path) {
121 auto mountKey = toMountKey(path);
122 const auto prefixSize = mountKey.size();
123 for (int counter = 0; counter < 1000;
124 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
125 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800126 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800127 return {mountKey, mountRoot};
128 }
129 }
130 return {};
131}
132
133template <class ProtoMessage, class Control>
134static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
135 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800136 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800137 ProtoMessage message;
138 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
139}
140
141static bool isValidMountTarget(std::string_view path) {
142 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
143}
144
145std::string makeBindMdName() {
146 static constexpr auto uuidStringSize = 36;
147
148 uuid_t guid;
149 uuid_generate(guid);
150
151 std::string name;
152 const auto prefixSize = constants().mountpointMdPrefix.size();
153 name.reserve(prefixSize + uuidStringSize);
154
155 name = constants().mountpointMdPrefix;
156 name.resize(prefixSize + uuidStringSize);
157 uuid_unparse(guid, name.data() + prefixSize);
158
159 return name;
160}
161} // namespace
162
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700163const bool IncrementalService::sEnablePerfLogging =
164 android::base::GetBoolProperty("incremental.perflogging", false);
165
Songchun Fan3c82a302019-11-29 14:23:45 -0800166IncrementalService::IncFsMount::~IncFsMount() {
Songchun Fan68645c42020-02-27 15:57:35 -0800167 incrementalService.mDataLoaderManager->destroyDataLoader(mountId);
Songchun Fan3c82a302019-11-29 14:23:45 -0800168 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
169 for (auto&& [target, _] : bindPoints) {
170 LOG(INFO) << "\tbind: " << target;
171 incrementalService.mVold->unmountIncFs(target);
172 }
173 LOG(INFO) << "\troot: " << root;
174 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
175 cleanupFilesystem(root);
176}
177
178auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800179 std::string name;
180 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
181 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
182 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800183 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
184 constants().storagePrefix.data(), id, no);
185 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800186 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800187 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800188 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
189 } else if (err != EEXIST) {
190 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
191 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800192 }
193 }
194 nextStorageDirNo = 0;
195 return storages.end();
196}
197
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800198static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
199 return {::opendir(path), ::closedir};
200}
201
202static int rmDirContent(const char* path) {
203 auto dir = openDir(path);
204 if (!dir) {
205 return -EINVAL;
206 }
207 while (auto entry = ::readdir(dir.get())) {
208 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
209 continue;
210 }
211 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
212 if (entry->d_type == DT_DIR) {
213 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
214 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
215 return err;
216 }
217 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
218 PLOG(WARNING) << "Failed to rmdir " << fullPath;
219 return err;
220 }
221 } else {
222 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
223 PLOG(WARNING) << "Failed to delete " << fullPath;
224 return err;
225 }
226 }
227 }
228 return 0;
229}
230
Songchun Fan3c82a302019-11-29 14:23:45 -0800231void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800232 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800233 ::rmdir(path::join(root, constants().backing).c_str());
234 ::rmdir(path::join(root, constants().mount).c_str());
235 ::rmdir(path::c_str(root));
236}
237
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800238IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800239 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800240 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800241 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700242 mAppOpsManager(sm.getAppOpsManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800243 mIncrementalDir(rootDir) {
244 if (!mVold) {
245 LOG(FATAL) << "Vold service is unavailable";
246 }
Songchun Fan68645c42020-02-27 15:57:35 -0800247 if (!mDataLoaderManager) {
248 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800249 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700250 if (!mAppOpsManager) {
251 LOG(FATAL) << "AppOpsManager is unavailable";
252 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800253 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800254}
255
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800256FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800257 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800258}
259
Songchun Fan3c82a302019-11-29 14:23:45 -0800260IncrementalService::~IncrementalService() = default;
261
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800262inline const char* toString(TimePoint t) {
263 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800264 time_t time = SystemClock::to_time_t(
265 SystemClock::now() +
266 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800267 return std::ctime(&time);
268}
269
270inline const char* toString(IncrementalService::BindKind kind) {
271 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800272 case IncrementalService::BindKind::Temporary:
273 return "Temporary";
274 case IncrementalService::BindKind::Permanent:
275 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800276 }
277}
278
279void IncrementalService::onDump(int fd) {
280 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
281 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
282
283 std::unique_lock l(mLock);
284
285 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
286 for (auto&& [id, ifs] : mMounts) {
287 const IncFsMount& mnt = *ifs.get();
288 dprintf(fd, "\t[%d]:\n", id);
289 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700290 dprintf(fd, "\t\troot: %s\n", mnt.root.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800291 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
292 dprintf(fd, "\t\tdataLoaderStatus: %d\n", mnt.dataLoaderStatus.load());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700293 {
294 const auto& params = mnt.dataLoaderParams;
295 dprintf(fd, "\t\tdataLoaderParams:\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800296 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
297 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
298 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
299 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800300 }
301 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
302 for (auto&& [storageId, storage] : mnt.storages) {
303 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
304 }
305
306 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
307 for (auto&& [target, bind] : mnt.bindPoints) {
308 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
309 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
310 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
311 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
312 }
313 }
314
315 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
316 for (auto&& [target, mountPairIt] : mBindsByPath) {
317 const auto& bind = mountPairIt->second;
318 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
319 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
320 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
321 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
322 }
323}
324
Songchun Fan3c82a302019-11-29 14:23:45 -0800325std::optional<std::future<void>> IncrementalService::onSystemReady() {
326 std::promise<void> threadFinished;
327 if (mSystemReady.exchange(true)) {
328 return {};
329 }
330
331 std::vector<IfsMountPtr> mounts;
332 {
333 std::lock_guard l(mLock);
334 mounts.reserve(mMounts.size());
335 for (auto&& [id, ifs] : mMounts) {
336 if (ifs->mountId == id) {
337 mounts.push_back(ifs);
338 }
339 }
340 }
341
342 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700343 /* TODO(b/151241369): restore data loaders on reboot.
Songchun Fan3c82a302019-11-29 14:23:45 -0800344 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800345 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800346 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
347 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800348 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800349 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800350 }
351 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700352 */
Songchun Fan3c82a302019-11-29 14:23:45 -0800353 mPrepareDataLoaders.set_value_at_thread_exit();
354 }).detach();
355 return mPrepareDataLoaders.get_future();
356}
357
358auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
359 for (;;) {
360 if (mNextId == kMaxStorageId) {
361 mNextId = 0;
362 }
363 auto id = ++mNextId;
364 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
365 if (inserted) {
366 return it;
367 }
368 }
369}
370
Songchun Fan1124fd32020-02-10 12:49:41 -0800371StorageId IncrementalService::createStorage(
372 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
373 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800374 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
375 if (!path::isAbsolute(mountPoint)) {
376 LOG(ERROR) << "path is not absolute: " << mountPoint;
377 return kInvalidStorageId;
378 }
379
380 auto mountNorm = path::normalize(mountPoint);
381 {
382 const auto id = findStorageId(mountNorm);
383 if (id != kInvalidStorageId) {
384 if (options & CreateOptions::OpenExisting) {
385 LOG(INFO) << "Opened existing storage " << id;
386 return id;
387 }
388 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
389 return kInvalidStorageId;
390 }
391 }
392
393 if (!(options & CreateOptions::CreateNew)) {
394 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
395 return kInvalidStorageId;
396 }
397
398 if (!path::isEmptyDir(mountNorm)) {
399 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
400 return kInvalidStorageId;
401 }
402 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
403 if (mountRoot.empty()) {
404 LOG(ERROR) << "Bad mount point";
405 return kInvalidStorageId;
406 }
407 // Make sure the code removes all crap it may create while still failing.
408 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
409 auto firstCleanupOnFailure =
410 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
411
412 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800413 const auto backing = path::join(mountRoot, constants().backing);
414 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800415 return kInvalidStorageId;
416 }
417
Songchun Fan3c82a302019-11-29 14:23:45 -0800418 IncFsMount::Control control;
419 {
420 std::lock_guard l(mMountOperationLock);
421 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800422
423 if (auto err = rmDirContent(backing.c_str())) {
424 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
425 return kInvalidStorageId;
426 }
427 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
428 return kInvalidStorageId;
429 }
430 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800431 if (!status.isOk()) {
432 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
433 return kInvalidStorageId;
434 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800435 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
436 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800437 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
438 return kInvalidStorageId;
439 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800440 int cmd = controlParcel.cmd.release().release();
441 int pendingReads = controlParcel.pendingReads.release().release();
442 int logs = controlParcel.log.release().release();
443 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800444 }
445
446 std::unique_lock l(mLock);
447 const auto mountIt = getStorageSlotLocked();
448 const auto mountId = mountIt->first;
449 l.unlock();
450
451 auto ifs =
452 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
453 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
454 // is the removal of the |ifs|.
455 firstCleanupOnFailure.release();
456
457 auto secondCleanup = [this, &l](auto itPtr) {
458 if (!l.owns_lock()) {
459 l.lock();
460 }
461 mMounts.erase(*itPtr);
462 };
463 auto secondCleanupOnFailure =
464 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
465
466 const auto storageIt = ifs->makeStorage(ifs->mountId);
467 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800468 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800469 return kInvalidStorageId;
470 }
471
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700472 ifs->dataLoaderParams = std::move(dataLoaderParams);
473
Songchun Fan3c82a302019-11-29 14:23:45 -0800474 {
475 metadata::Mount m;
476 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700477 m.mutable_loader()->set_type((int)ifs->dataLoaderParams.type);
478 m.mutable_loader()->set_package_name(ifs->dataLoaderParams.packageName);
479 m.mutable_loader()->set_class_name(ifs->dataLoaderParams.className);
480 m.mutable_loader()->set_arguments(ifs->dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800481 const auto metadata = m.SerializeAsString();
482 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800483 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800484 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800485 if (auto err =
486 mIncFs->makeFile(ifs->control,
487 path::join(ifs->root, constants().mount,
488 constants().infoMdName),
489 0777, idFromMetadata(metadata),
490 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800491 LOG(ERROR) << "Saving mount metadata failed: " << -err;
492 return kInvalidStorageId;
493 }
494 }
495
496 const auto bk =
497 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800498 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
499 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800500 err < 0) {
501 LOG(ERROR) << "adding bind mount failed: " << -err;
502 return kInvalidStorageId;
503 }
504
505 // Done here as well, all data structures are in good state.
506 secondCleanupOnFailure.release();
507
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700508 if (!prepareDataLoader(*ifs, &dataLoaderStatusListener)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800509 LOG(ERROR) << "prepareDataLoader() failed";
510 deleteStorageLocked(*ifs, std::move(l));
511 return kInvalidStorageId;
512 }
513
514 mountIt->second = std::move(ifs);
515 l.unlock();
516 LOG(INFO) << "created storage " << mountId;
517 return mountId;
518}
519
520StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
521 StorageId linkedStorage,
522 IncrementalService::CreateOptions options) {
523 if (!isValidMountTarget(mountPoint)) {
524 LOG(ERROR) << "Mount point is invalid or missing";
525 return kInvalidStorageId;
526 }
527
528 std::unique_lock l(mLock);
529 const auto& ifs = getIfsLocked(linkedStorage);
530 if (!ifs) {
531 LOG(ERROR) << "Ifs unavailable";
532 return kInvalidStorageId;
533 }
534
535 const auto mountIt = getStorageSlotLocked();
536 const auto storageId = mountIt->first;
537 const auto storageIt = ifs->makeStorage(storageId);
538 if (storageIt == ifs->storages.end()) {
539 LOG(ERROR) << "Can't create a new storage";
540 mMounts.erase(mountIt);
541 return kInvalidStorageId;
542 }
543
544 l.unlock();
545
546 const auto bk =
547 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800548 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
549 std::string(storageIt->second.name), path::normalize(mountPoint),
550 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800551 err < 0) {
552 LOG(ERROR) << "bindMount failed with error: " << err;
553 return kInvalidStorageId;
554 }
555
556 mountIt->second = ifs;
557 return storageId;
558}
559
560IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
561 std::string_view path) const {
562 auto bindPointIt = mBindsByPath.upper_bound(path);
563 if (bindPointIt == mBindsByPath.begin()) {
564 return mBindsByPath.end();
565 }
566 --bindPointIt;
567 if (!path::startsWith(path, bindPointIt->first)) {
568 return mBindsByPath.end();
569 }
570 return bindPointIt;
571}
572
573StorageId IncrementalService::findStorageId(std::string_view path) const {
574 std::lock_guard l(mLock);
575 auto it = findStorageLocked(path);
576 if (it == mBindsByPath.end()) {
577 return kInvalidStorageId;
578 }
579 return it->second->second.storage;
580}
581
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700582int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
583 const auto ifs = getIfs(storageId);
584 if (!ifs) {
585 return -EINVAL;
586 }
587
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700588 ifs->dataLoaderFilesystemParams.readLogsEnabled = enableReadLogs;
589 if (enableReadLogs) {
590 // We never unregister the callbacks, but given a restricted number of data loaders and even fewer asking for read log access, should be ok.
591 registerAppOpsCallback(ifs->dataLoaderParams.packageName);
592 }
593
594 return applyStorageParams(*ifs);
595}
596
597int IncrementalService::applyStorageParams(IncFsMount& ifs) {
598 const bool enableReadLogs = ifs.dataLoaderFilesystemParams.readLogsEnabled;
599 if (enableReadLogs) {
600 if (auto status = CheckPermissionForDataDelivery(kDataUsageStats, kOpUsage);
601 !status.isOk()) {
602 LOG(ERROR) << "CheckPermissionForDataDelivery failed: " << status.toString8();
603 return fromBinderStatus(status);
604 }
605 }
606
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700607 using unique_fd = ::android::base::unique_fd;
608 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700609 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
610 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
611 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700612 if (logsFd >= 0) {
613 control.log.reset(unique_fd(dup(logsFd)));
614 }
615
616 std::lock_guard l(mMountOperationLock);
617 const auto status = mVold->setIncFsMountOptions(control, enableReadLogs);
618 if (!status.isOk()) {
619 LOG(ERROR) << "Calling Vold::setIncFsMountOptions() failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700620 return fromBinderStatus(status);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700621 }
622
623 return 0;
624}
625
Songchun Fan3c82a302019-11-29 14:23:45 -0800626void IncrementalService::deleteStorage(StorageId storageId) {
627 const auto ifs = getIfs(storageId);
628 if (!ifs) {
629 return;
630 }
631 deleteStorage(*ifs);
632}
633
634void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
635 std::unique_lock l(ifs.lock);
636 deleteStorageLocked(ifs, std::move(l));
637}
638
639void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
640 std::unique_lock<std::mutex>&& ifsLock) {
641 const auto storages = std::move(ifs.storages);
642 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
643 const auto bindPoints = ifs.bindPoints;
644 ifsLock.unlock();
645
646 std::lock_guard l(mLock);
647 for (auto&& [id, _] : storages) {
648 if (id != ifs.mountId) {
649 mMounts.erase(id);
650 }
651 }
652 for (auto&& [path, _] : bindPoints) {
653 mBindsByPath.erase(path);
654 }
655 mMounts.erase(ifs.mountId);
656}
657
658StorageId IncrementalService::openStorage(std::string_view pathInMount) {
659 if (!path::isAbsolute(pathInMount)) {
660 return kInvalidStorageId;
661 }
662
663 return findStorageId(path::normalize(pathInMount));
664}
665
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800666FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800667 const auto ifs = getIfs(storage);
668 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800669 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800670 }
671 std::unique_lock l(ifs->lock);
672 auto storageIt = ifs->storages.find(storage);
673 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800674 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800675 }
676 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800677 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800678 }
679 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
680 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800681 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800682}
683
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800684std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800685 StorageId storage, std::string_view subpath) const {
686 auto name = path::basename(subpath);
687 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800688 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800689 }
690 auto dir = path::dirname(subpath);
691 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800692 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800693 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800694 auto id = nodeFor(storage, dir);
695 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800696}
697
698IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
699 std::lock_guard l(mLock);
700 return getIfsLocked(storage);
701}
702
703const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
704 auto it = mMounts.find(storage);
705 if (it == mMounts.end()) {
706 static const IfsMountPtr kEmpty = {};
707 return kEmpty;
708 }
709 return it->second;
710}
711
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800712int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
713 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800714 if (!isValidMountTarget(target)) {
715 return -EINVAL;
716 }
717
718 const auto ifs = getIfs(storage);
719 if (!ifs) {
720 return -EINVAL;
721 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800722
Songchun Fan3c82a302019-11-29 14:23:45 -0800723 std::unique_lock l(ifs->lock);
724 const auto storageInfo = ifs->storages.find(storage);
725 if (storageInfo == ifs->storages.end()) {
726 return -EINVAL;
727 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700728 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
729 if (normSource.empty()) {
730 return -EINVAL;
731 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800732 l.unlock();
733 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800734 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
735 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800736}
737
738int IncrementalService::unbind(StorageId storage, std::string_view target) {
739 if (!path::isAbsolute(target)) {
740 return -EINVAL;
741 }
742
743 LOG(INFO) << "Removing bind point " << target;
744
745 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
746 // otherwise there's a chance to unmount something completely unrelated
747 const auto norm = path::normalize(target);
748 std::unique_lock l(mLock);
749 const auto storageIt = mBindsByPath.find(norm);
750 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
751 return -EINVAL;
752 }
753 const auto bindIt = storageIt->second;
754 const auto storageId = bindIt->second.storage;
755 const auto ifs = getIfsLocked(storageId);
756 if (!ifs) {
757 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
758 << " is missing";
759 return -EFAULT;
760 }
761 mBindsByPath.erase(storageIt);
762 l.unlock();
763
764 mVold->unmountIncFs(bindIt->first);
765 std::unique_lock l2(ifs->lock);
766 if (ifs->bindPoints.size() <= 1) {
767 ifs->bindPoints.clear();
768 deleteStorageLocked(*ifs, std::move(l2));
769 } else {
770 const std::string savedFile = std::move(bindIt->second.savedFilename);
771 ifs->bindPoints.erase(bindIt);
772 l2.unlock();
773 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800774 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800775 }
776 }
777 return 0;
778}
779
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700780std::string IncrementalService::normalizePathToStorageLocked(
781 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
782 std::string normPath;
783 if (path::isAbsolute(path)) {
784 normPath = path::normalize(path);
785 if (!path::startsWith(normPath, storageIt->second.name)) {
786 return {};
787 }
788 } else {
789 normPath = path::normalize(path::join(storageIt->second.name, path));
790 }
791 return normPath;
792}
793
794std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800795 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700796 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800797 const auto storageInfo = ifs->storages.find(storage);
798 if (storageInfo == ifs->storages.end()) {
799 return {};
800 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700801 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800802}
803
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800804int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
805 incfs::NewFileParams params) {
806 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800807 std::string normPath = normalizePathToStorage(ifs, storage, path);
808 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700809 LOG(ERROR) << "Internal error: storageId " << storage
810 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800811 return -EINVAL;
812 }
813 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800814 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700815 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800816 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800817 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800818 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800819 }
820 return -EINVAL;
821}
822
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800823int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800824 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800825 std::string normPath = normalizePathToStorage(ifs, storageId, path);
826 if (normPath.empty()) {
827 return -EINVAL;
828 }
829 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800830 }
831 return -EINVAL;
832}
833
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800834int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800835 const auto ifs = getIfs(storageId);
836 if (!ifs) {
837 return -EINVAL;
838 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800839 std::string normPath = normalizePathToStorage(ifs, storageId, path);
840 if (normPath.empty()) {
841 return -EINVAL;
842 }
843 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800844 if (err == -EEXIST) {
845 return 0;
846 } else if (err != -ENOENT) {
847 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800848 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800849 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800850 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800851 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800852 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800853}
854
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800855int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
856 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700857 auto ifsSrc = getIfs(sourceStorageId);
858 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
859 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800860 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
861 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
862 if (normOldPath.empty() || normNewPath.empty()) {
863 return -EINVAL;
864 }
865 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800866 }
867 return -EINVAL;
868}
869
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800870int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800871 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800872 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
873 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800874 }
875 return -EINVAL;
876}
877
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800878int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
879 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800880 std::string&& target, BindKind kind,
881 std::unique_lock<std::mutex>& mainLock) {
882 if (!isValidMountTarget(target)) {
883 return -EINVAL;
884 }
885
886 std::string mdFileName;
887 if (kind != BindKind::Temporary) {
888 metadata::BindPoint bp;
889 bp.set_storage_id(storage);
890 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800891 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800892 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800893 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800894 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800895 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800896 auto node =
897 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
898 0444, idFromMetadata(metadata),
899 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
900 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800901 return int(node);
902 }
903 }
904
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800905 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800906 std::move(target), kind, mainLock);
907}
908
909int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800910 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800911 std::string&& target, BindKind kind,
912 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800913 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800914 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800915 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800916 if (!status.isOk()) {
917 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
918 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
919 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
920 : status.serviceSpecificErrorCode() == 0
921 ? -EFAULT
922 : status.serviceSpecificErrorCode()
923 : -EIO;
924 }
925 }
926
927 if (!mainLock.owns_lock()) {
928 mainLock.lock();
929 }
930 std::lock_guard l(ifs.lock);
931 const auto [it, _] =
932 ifs.bindPoints.insert_or_assign(target,
933 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800934 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800935 mBindsByPath[std::move(target)] = it;
936 return 0;
937}
938
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800939RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800940 const auto ifs = getIfs(storage);
941 if (!ifs) {
942 return {};
943 }
944 return mIncFs->getMetadata(ifs->control, node);
945}
946
947std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
948 const auto ifs = getIfs(storage);
949 if (!ifs) {
950 return {};
951 }
952
953 std::unique_lock l(ifs->lock);
954 auto subdirIt = ifs->storages.find(storage);
955 if (subdirIt == ifs->storages.end()) {
956 return {};
957 }
958 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
959 l.unlock();
960
961 const auto prefixSize = dir.size() + 1;
962 std::vector<std::string> todoDirs{std::move(dir)};
963 std::vector<std::string> result;
964 do {
965 auto currDir = std::move(todoDirs.back());
966 todoDirs.pop_back();
967
968 auto d =
969 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
970 while (auto e = ::readdir(d.get())) {
971 if (e->d_type == DT_REG) {
972 result.emplace_back(
973 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
974 continue;
975 }
976 if (e->d_type == DT_DIR) {
977 if (e->d_name == "."sv || e->d_name == ".."sv) {
978 continue;
979 }
980 todoDirs.emplace_back(path::join(currDir, e->d_name));
981 continue;
982 }
983 }
984 } while (!todoDirs.empty());
985 return result;
986}
987
988bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700989 {
990 std::unique_lock l(mLock);
991 const auto& ifs = getIfsLocked(storage);
992 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800993 return false;
994 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700995 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
996 ifs->dataLoaderStartRequested = true;
997 return true;
998 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800999 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001000 return startDataLoader(storage);
1001}
1002
1003bool IncrementalService::startDataLoader(MountId mountId) const {
Songchun Fan68645c42020-02-27 15:57:35 -08001004 sp<IDataLoader> dataloader;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001005 auto status = mDataLoaderManager->getDataLoader(mountId, &dataloader);
Songchun Fan3c82a302019-11-29 14:23:45 -08001006 if (!status.isOk()) {
1007 return false;
1008 }
Songchun Fan68645c42020-02-27 15:57:35 -08001009 if (!dataloader) {
1010 return false;
1011 }
Alex Buynytskyyb6e02f72020-03-17 18:12:23 -07001012 status = dataloader->start(mountId);
Songchun Fan68645c42020-02-27 15:57:35 -08001013 if (!status.isOk()) {
1014 return false;
1015 }
1016 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001017}
1018
1019void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001020 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1021 const auto path = entry.path().u8string();
1022 const auto name = entry.path().filename().u8string();
1023 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001024 continue;
1025 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001026 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001027 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001028 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001029 }
1030 }
1031}
1032
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001033bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001034 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001035 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001036
Songchun Fan3c82a302019-11-29 14:23:45 -08001037 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001038 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001039 if (!status.isOk()) {
1040 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1041 return false;
1042 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001043
1044 int cmd = controlParcel.cmd.release().release();
1045 int pendingReads = controlParcel.pendingReads.release().release();
1046 int logs = controlParcel.log.release().release();
1047 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001048
1049 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1050
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001051 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1052 path::join(mountTarget, constants().infoMdName));
1053 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001054 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1055 return false;
1056 }
1057
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001058 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001059 mNextId = std::max(mNextId, ifs->mountId + 1);
1060
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001061 // DataLoader params
1062 {
1063 auto& dlp = ifs->dataLoaderParams;
1064 const auto& loader = mount.loader();
1065 dlp.type = (android::content::pm::DataLoaderType)loader.type();
1066 dlp.packageName = loader.package_name();
1067 dlp.className = loader.class_name();
1068 dlp.arguments = loader.arguments();
1069 }
1070
Songchun Fan3c82a302019-11-29 14:23:45 -08001071 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001072 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001073 while (auto e = ::readdir(d.get())) {
1074 if (e->d_type == DT_REG) {
1075 auto name = std::string_view(e->d_name);
1076 if (name.starts_with(constants().mountpointMdPrefix)) {
1077 bindPoints.emplace_back(name,
1078 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1079 ifs->control,
1080 path::join(mountTarget,
1081 name)));
1082 if (bindPoints.back().second.dest_path().empty() ||
1083 bindPoints.back().second.source_subdir().empty()) {
1084 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001085 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001086 }
1087 }
1088 } else if (e->d_type == DT_DIR) {
1089 if (e->d_name == "."sv || e->d_name == ".."sv) {
1090 continue;
1091 }
1092 auto name = std::string_view(e->d_name);
1093 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001094 int storageId;
1095 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1096 name.data() + name.size(), storageId);
1097 if (res.ec != std::errc{} || *res.ptr != '_') {
1098 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1099 << root;
1100 continue;
1101 }
1102 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001103 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001104 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001105 << " for mount " << root;
1106 continue;
1107 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001108 ifs->storages.insert_or_assign(storageId,
1109 IncFsMount::Storage{
1110 path::join(root, constants().mount, name)});
1111 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001112 }
1113 }
1114 }
1115
1116 if (ifs->storages.empty()) {
1117 LOG(WARNING) << "No valid storages in mount " << root;
1118 return false;
1119 }
1120
1121 int bindCount = 0;
1122 for (auto&& bp : bindPoints) {
1123 std::unique_lock l(mLock, std::defer_lock);
1124 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1125 std::move(*bp.second.mutable_source_subdir()),
1126 std::move(*bp.second.mutable_dest_path()),
1127 BindKind::Permanent, l);
1128 }
1129
1130 if (bindCount == 0) {
1131 LOG(WARNING) << "No valid bind points for mount " << root;
1132 deleteStorage(*ifs);
1133 return false;
1134 }
1135
Songchun Fan3c82a302019-11-29 14:23:45 -08001136 mMounts[ifs->mountId] = std::move(ifs);
1137 return true;
1138}
1139
1140bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001141 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001142 if (!mSystemReady.load(std::memory_order_relaxed)) {
1143 std::unique_lock l(ifs.lock);
Songchun Fan3c82a302019-11-29 14:23:45 -08001144 return true; // eventually...
1145 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001146
1147 std::unique_lock l(ifs.lock);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001148 if (ifs.dataLoaderStatus != -1) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001149 LOG(INFO) << "Skipped data loader preparation because it already exists";
1150 return true;
1151 }
1152
Songchun Fan3c82a302019-11-29 14:23:45 -08001153 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001154 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001155 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001156 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001157 base::unique_fd(::dup(ifs.control.pendingReads())));
1158 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Songchun Fan1124fd32020-02-10 12:49:41 -08001159 sp<IncrementalDataLoaderListener> listener =
Songchun Fan306b7df2020-03-17 12:37:07 -07001160 new IncrementalDataLoaderListener(*this,
1161 externalListener ? *externalListener
1162 : DataLoaderStatusListener());
Songchun Fan3c82a302019-11-29 14:23:45 -08001163 bool created = false;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001164 auto status = mDataLoaderManager->initializeDataLoader(ifs.mountId, ifs.dataLoaderParams, fsControlParcel, listener, &created);
Songchun Fan3c82a302019-11-29 14:23:45 -08001165 if (!status.isOk() || !created) {
1166 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
1167 return false;
1168 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001169 return true;
1170}
1171
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001172template <class Duration>
1173static long elapsedMcs(Duration start, Duration end) {
1174 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1175}
1176
1177// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001178bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1179 std::string_view libDirRelativePath,
1180 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001181 namespace sc = std::chrono;
1182 using Clock = sc::steady_clock;
1183 auto start = Clock::now();
1184
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001185 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001186 if (!ifs) {
1187 LOG(ERROR) << "Invalid storage " << storage;
1188 return false;
1189 }
1190
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001191 // First prepare target directories if they don't exist yet
1192 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1193 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1194 << " errno: " << res;
1195 return false;
1196 }
1197
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001198 auto mkDirsTs = Clock::now();
1199
1200 std::unique_ptr<ZipFileRO> zipFile(ZipFileRO::open(path::c_str(apkFullPath)));
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001201 if (!zipFile) {
1202 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1203 return false;
1204 }
1205 void* cookie = nullptr;
1206 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001207 if (!zipFile->startIteration(&cookie, libFilePrefix.c_str() /* prefix */,
1208 constants().libSuffix.data() /* suffix */)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001209 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1210 return false;
1211 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001212 auto endIteration = [&zipFile](void* cookie) { zipFile->endIteration(cookie); };
1213 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1214
1215 auto openZipTs = Clock::now();
1216
1217 std::vector<IncFsDataBlock> instructions;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001218 ZipEntryRO entry = nullptr;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001219 while ((entry = zipFile->nextEntry(cookie)) != nullptr) {
1220 auto startFileTs = Clock::now();
1221
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001222 char fileName[PATH_MAX];
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001223 if (zipFile->getEntryFileName(entry, fileName, sizeof(fileName))) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001224 continue;
1225 }
1226 const auto libName = path::basename(fileName);
1227 const auto targetLibPath = path::join(libDirRelativePath, libName);
1228 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1229 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001230 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1231 if (sEnablePerfLogging) {
1232 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1233 << "; skipping extraction, spent "
1234 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1235 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001236 continue;
1237 }
1238
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001239 uint32_t uncompressedLen, compressedLen;
1240 if (!zipFile->getEntryInfo(entry, nullptr, &uncompressedLen, &compressedLen, nullptr,
1241 nullptr, nullptr)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001242 LOG(ERROR) << "Failed to read native lib entry: " << fileName;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001243 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001244 }
1245
1246 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001247 incfs::NewFileParams libFileParams = {
1248 .size = uncompressedLen,
1249 .signature = {},
1250 // Metadata of the new lib file is its relative path
1251 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1252 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001253 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001254 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1255 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001256 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001257 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001258 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001259 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001260
1261 auto makeFileTs = Clock::now();
1262
Songchun Fanafaf6e92020-03-18 14:12:20 -07001263 // If it is a zero-byte file, skip data writing
1264 if (uncompressedLen == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001265 if (sEnablePerfLogging) {
1266 LOG(INFO) << "incfs: Extracted " << libName << "(" << compressedLen << " -> "
1267 << uncompressedLen << " bytes): " << elapsedMcs(startFileTs, makeFileTs)
1268 << "mcs, make: " << elapsedMcs(startFileTs, makeFileTs);
1269 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001270 continue;
1271 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001272
1273 // Write extracted data to new file
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001274 // NOTE: don't zero-initialize memory, it may take a while
1275 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[uncompressedLen]);
1276 if (!zipFile->uncompressEntry(entry, libData.get(), uncompressedLen)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001277 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001278 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001279 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001280
1281 auto extractFileTs = Clock::now();
1282
Yurii Zubrytskyie82cdd72020-04-01 12:19:26 -07001283 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1284 if (!writeFd.ok()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001285 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001286 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001287 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001288
1289 auto openFileTs = Clock::now();
1290
1291 const int numBlocks = (uncompressedLen + constants().blockSize - 1) / constants().blockSize;
1292 instructions.clear();
1293 instructions.reserve(numBlocks);
1294 auto remainingData = std::span(libData.get(), uncompressedLen);
1295 for (int i = 0; i < numBlocks; i++) {
1296 const auto blockSize = std::min<uint16_t>(constants().blockSize, remainingData.size());
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001297 auto inst = IncFsDataBlock{
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001298 .fileFd = writeFd.get(),
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001299 .pageIndex = static_cast<IncFsBlockIndex>(i),
1300 .compression = INCFS_COMPRESSION_KIND_NONE,
1301 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001302 .dataSize = blockSize,
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001303 .data = reinterpret_cast<const char*>(remainingData.data()),
1304 };
1305 instructions.push_back(inst);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001306 remainingData = remainingData.subspan(blockSize);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001307 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001308 auto prepareInstsTs = Clock::now();
1309
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001310 size_t res = mIncFs->writeBlocks(instructions);
1311 if (res != instructions.size()) {
1312 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001313 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001314 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001315
1316 if (sEnablePerfLogging) {
1317 auto endFileTs = Clock::now();
1318 LOG(INFO) << "incfs: Extracted " << libName << "(" << compressedLen << " -> "
1319 << uncompressedLen << " bytes): " << elapsedMcs(startFileTs, endFileTs)
1320 << "mcs, make: " << elapsedMcs(startFileTs, makeFileTs)
1321 << " extract: " << elapsedMcs(makeFileTs, extractFileTs)
1322 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1323 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1324 << " write:" << elapsedMcs(prepareInstsTs, endFileTs);
1325 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001326 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001327
1328 if (sEnablePerfLogging) {
1329 auto end = Clock::now();
1330 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1331 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1332 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
1333 << " extract all: " << elapsedMcs(openZipTs, end);
1334 }
1335
1336 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001337}
1338
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001339void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
1340 if (packageName.empty()) {
1341 return;
1342 }
1343
1344 {
1345 std::unique_lock lock{mCallbacksLock};
1346 if (!mCallbackRegistered.insert(packageName).second) {
1347 return;
1348 }
1349 }
1350
1351 /* TODO(b/152633648): restore callback after it's not crashing Binder anymore.
1352 sp<AppOpsListener> listener = new AppOpsListener(*this, packageName);
1353 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS, String16(packageName.c_str()), listener);
1354 */
1355}
1356
1357void IncrementalService::onAppOppChanged(const std::string& packageName) {
1358 std::vector<IfsMountPtr> affected;
1359 {
1360 std::lock_guard l(mLock);
1361 affected.reserve(mMounts.size());
1362 for (auto&& [id, ifs] : mMounts) {
1363 if (ifs->dataLoaderFilesystemParams.readLogsEnabled && ifs->dataLoaderParams.packageName == packageName) {
1364 affected.push_back(ifs);
1365 }
1366 }
1367 }
1368 /* TODO(b/152633648): restore callback after it's not crashing Kernel anymore.
1369 for (auto&& ifs : affected) {
1370 applyStorageParams(*ifs);
1371 }
1372 */
1373}
1374
Songchun Fan3c82a302019-11-29 14:23:45 -08001375binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1376 int newStatus) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001377 if (externalListener) {
1378 // Give an external listener a chance to act before we destroy something.
1379 externalListener->onStatusChanged(mountId, newStatus);
1380 }
1381
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001382 bool startRequested = false;
1383 {
1384 std::unique_lock l(incrementalService.mLock);
1385 const auto& ifs = incrementalService.getIfsLocked(mountId);
1386 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001387 LOG(WARNING) << "Received data loader status " << int(newStatus)
1388 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001389 return binder::Status::ok();
1390 }
1391 ifs->dataLoaderStatus = newStatus;
1392
1393 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1394 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1395 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1396 return binder::Status::ok();
1397 }
1398
1399 startRequested = ifs->dataLoaderStartRequested;
Songchun Fan3c82a302019-11-29 14:23:45 -08001400 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001401
Songchun Fan3c82a302019-11-29 14:23:45 -08001402 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001403 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001404 if (startRequested) {
1405 incrementalService.startDataLoader(mountId);
1406 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001407 break;
1408 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001409 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001410 break;
1411 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001412 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001413 break;
1414 }
1415 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1416 break;
1417 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001418 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1419 break;
1420 }
1421 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1422 break;
1423 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001424 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1425 // Nothing for now. Rely on externalListener to handle this.
1426 break;
1427 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001428 default: {
1429 LOG(WARNING) << "Unknown data loader status: " << newStatus
1430 << " for mount: " << mountId;
1431 break;
1432 }
1433 }
1434
1435 return binder::Status::ok();
1436}
1437
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001438void IncrementalService::AppOpsListener::opChanged(int32_t op, const String16&) {
1439 incrementalService.onAppOppChanged(packageName);
1440}
1441
Songchun Fan3c82a302019-11-29 14:23:45 -08001442} // namespace android::incremental