blob: 4f64cad1f9d9ef926ab12cede5c0cf9ec0f4c944 [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"
20
21#include <android-base/file.h>
22#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070023#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080024#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";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070055constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070056
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) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700585 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700586 return -EINVAL;
587 }
588
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700589 if (enableReadLogs) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700590 if (auto status =
591 mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
592 ifs->dataLoaderParams.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700593 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700594 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700595 return fromBinderStatus(status);
596 }
597 }
598
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700599 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
600 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
601 return fromBinderStatus(status);
602 }
603
604 if (enableReadLogs) {
605 registerAppOpsCallback(ifs->dataLoaderParams.packageName);
606 }
607
608 return 0;
609}
610
611binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700612 using unique_fd = ::android::base::unique_fd;
613 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700614 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
615 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
616 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700617 if (logsFd >= 0) {
618 control.log.reset(unique_fd(dup(logsFd)));
619 }
620
621 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700622 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700623}
624
Songchun Fan3c82a302019-11-29 14:23:45 -0800625void IncrementalService::deleteStorage(StorageId storageId) {
626 const auto ifs = getIfs(storageId);
627 if (!ifs) {
628 return;
629 }
630 deleteStorage(*ifs);
631}
632
633void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
634 std::unique_lock l(ifs.lock);
635 deleteStorageLocked(ifs, std::move(l));
636}
637
638void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
639 std::unique_lock<std::mutex>&& ifsLock) {
640 const auto storages = std::move(ifs.storages);
641 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
642 const auto bindPoints = ifs.bindPoints;
643 ifsLock.unlock();
644
645 std::lock_guard l(mLock);
646 for (auto&& [id, _] : storages) {
647 if (id != ifs.mountId) {
648 mMounts.erase(id);
649 }
650 }
651 for (auto&& [path, _] : bindPoints) {
652 mBindsByPath.erase(path);
653 }
654 mMounts.erase(ifs.mountId);
655}
656
657StorageId IncrementalService::openStorage(std::string_view pathInMount) {
658 if (!path::isAbsolute(pathInMount)) {
659 return kInvalidStorageId;
660 }
661
662 return findStorageId(path::normalize(pathInMount));
663}
664
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800665FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800666 const auto ifs = getIfs(storage);
667 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800668 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800669 }
670 std::unique_lock l(ifs->lock);
671 auto storageIt = ifs->storages.find(storage);
672 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800673 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800674 }
675 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800676 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800677 }
678 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
679 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800680 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800681}
682
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800683std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800684 StorageId storage, std::string_view subpath) const {
685 auto name = path::basename(subpath);
686 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800687 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800688 }
689 auto dir = path::dirname(subpath);
690 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800691 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800692 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800693 auto id = nodeFor(storage, dir);
694 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800695}
696
697IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
698 std::lock_guard l(mLock);
699 return getIfsLocked(storage);
700}
701
702const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
703 auto it = mMounts.find(storage);
704 if (it == mMounts.end()) {
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700705 static const android::base::NoDestructor<IfsMountPtr> kEmpty{};
706 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800707 }
708 return it->second;
709}
710
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800711int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
712 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800713 if (!isValidMountTarget(target)) {
714 return -EINVAL;
715 }
716
717 const auto ifs = getIfs(storage);
718 if (!ifs) {
719 return -EINVAL;
720 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800721
Songchun Fan3c82a302019-11-29 14:23:45 -0800722 std::unique_lock l(ifs->lock);
723 const auto storageInfo = ifs->storages.find(storage);
724 if (storageInfo == ifs->storages.end()) {
725 return -EINVAL;
726 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700727 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
728 if (normSource.empty()) {
729 return -EINVAL;
730 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800731 l.unlock();
732 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800733 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
734 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800735}
736
737int IncrementalService::unbind(StorageId storage, std::string_view target) {
738 if (!path::isAbsolute(target)) {
739 return -EINVAL;
740 }
741
742 LOG(INFO) << "Removing bind point " << target;
743
744 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
745 // otherwise there's a chance to unmount something completely unrelated
746 const auto norm = path::normalize(target);
747 std::unique_lock l(mLock);
748 const auto storageIt = mBindsByPath.find(norm);
749 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
750 return -EINVAL;
751 }
752 const auto bindIt = storageIt->second;
753 const auto storageId = bindIt->second.storage;
754 const auto ifs = getIfsLocked(storageId);
755 if (!ifs) {
756 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
757 << " is missing";
758 return -EFAULT;
759 }
760 mBindsByPath.erase(storageIt);
761 l.unlock();
762
763 mVold->unmountIncFs(bindIt->first);
764 std::unique_lock l2(ifs->lock);
765 if (ifs->bindPoints.size() <= 1) {
766 ifs->bindPoints.clear();
767 deleteStorageLocked(*ifs, std::move(l2));
768 } else {
769 const std::string savedFile = std::move(bindIt->second.savedFilename);
770 ifs->bindPoints.erase(bindIt);
771 l2.unlock();
772 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800773 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800774 }
775 }
776 return 0;
777}
778
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700779std::string IncrementalService::normalizePathToStorageLocked(
780 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
781 std::string normPath;
782 if (path::isAbsolute(path)) {
783 normPath = path::normalize(path);
784 if (!path::startsWith(normPath, storageIt->second.name)) {
785 return {};
786 }
787 } else {
788 normPath = path::normalize(path::join(storageIt->second.name, path));
789 }
790 return normPath;
791}
792
793std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800794 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700795 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800796 const auto storageInfo = ifs->storages.find(storage);
797 if (storageInfo == ifs->storages.end()) {
798 return {};
799 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700800 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800801}
802
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800803int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
804 incfs::NewFileParams params) {
805 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800806 std::string normPath = normalizePathToStorage(ifs, storage, path);
807 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700808 LOG(ERROR) << "Internal error: storageId " << storage
809 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800810 return -EINVAL;
811 }
812 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800813 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700814 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800815 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800816 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800817 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800818 }
819 return -EINVAL;
820}
821
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800822int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800823 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800824 std::string normPath = normalizePathToStorage(ifs, storageId, path);
825 if (normPath.empty()) {
826 return -EINVAL;
827 }
828 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800829 }
830 return -EINVAL;
831}
832
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800833int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800834 const auto ifs = getIfs(storageId);
835 if (!ifs) {
836 return -EINVAL;
837 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800838 std::string normPath = normalizePathToStorage(ifs, storageId, path);
839 if (normPath.empty()) {
840 return -EINVAL;
841 }
842 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800843 if (err == -EEXIST) {
844 return 0;
845 } else if (err != -ENOENT) {
846 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800847 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800848 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800849 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800850 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800851 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800852}
853
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800854int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
855 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700856 auto ifsSrc = getIfs(sourceStorageId);
857 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
858 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800859 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
860 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
861 if (normOldPath.empty() || normNewPath.empty()) {
862 return -EINVAL;
863 }
864 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800865 }
866 return -EINVAL;
867}
868
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800869int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800870 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800871 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
872 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800873 }
874 return -EINVAL;
875}
876
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800877int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
878 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800879 std::string&& target, BindKind kind,
880 std::unique_lock<std::mutex>& mainLock) {
881 if (!isValidMountTarget(target)) {
882 return -EINVAL;
883 }
884
885 std::string mdFileName;
886 if (kind != BindKind::Temporary) {
887 metadata::BindPoint bp;
888 bp.set_storage_id(storage);
889 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800890 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800891 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800892 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800893 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800894 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800895 auto node =
896 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
897 0444, idFromMetadata(metadata),
898 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
899 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800900 return int(node);
901 }
902 }
903
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800904 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800905 std::move(target), kind, mainLock);
906}
907
908int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800909 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 std::string&& target, BindKind kind,
911 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800912 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800913 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800914 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800915 if (!status.isOk()) {
916 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
917 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
918 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
919 : status.serviceSpecificErrorCode() == 0
920 ? -EFAULT
921 : status.serviceSpecificErrorCode()
922 : -EIO;
923 }
924 }
925
926 if (!mainLock.owns_lock()) {
927 mainLock.lock();
928 }
929 std::lock_guard l(ifs.lock);
930 const auto [it, _] =
931 ifs.bindPoints.insert_or_assign(target,
932 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800933 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800934 mBindsByPath[std::move(target)] = it;
935 return 0;
936}
937
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800938RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800939 const auto ifs = getIfs(storage);
940 if (!ifs) {
941 return {};
942 }
943 return mIncFs->getMetadata(ifs->control, node);
944}
945
946std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
947 const auto ifs = getIfs(storage);
948 if (!ifs) {
949 return {};
950 }
951
952 std::unique_lock l(ifs->lock);
953 auto subdirIt = ifs->storages.find(storage);
954 if (subdirIt == ifs->storages.end()) {
955 return {};
956 }
957 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
958 l.unlock();
959
960 const auto prefixSize = dir.size() + 1;
961 std::vector<std::string> todoDirs{std::move(dir)};
962 std::vector<std::string> result;
963 do {
964 auto currDir = std::move(todoDirs.back());
965 todoDirs.pop_back();
966
967 auto d =
968 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
969 while (auto e = ::readdir(d.get())) {
970 if (e->d_type == DT_REG) {
971 result.emplace_back(
972 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
973 continue;
974 }
975 if (e->d_type == DT_DIR) {
976 if (e->d_name == "."sv || e->d_name == ".."sv) {
977 continue;
978 }
979 todoDirs.emplace_back(path::join(currDir, e->d_name));
980 continue;
981 }
982 }
983 } while (!todoDirs.empty());
984 return result;
985}
986
987bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700988 {
989 std::unique_lock l(mLock);
990 const auto& ifs = getIfsLocked(storage);
991 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800992 return false;
993 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700994 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
995 ifs->dataLoaderStartRequested = true;
996 return true;
997 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800998 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700999 return startDataLoader(storage);
1000}
1001
1002bool IncrementalService::startDataLoader(MountId mountId) const {
Songchun Fan68645c42020-02-27 15:57:35 -08001003 sp<IDataLoader> dataloader;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001004 auto status = mDataLoaderManager->getDataLoader(mountId, &dataloader);
Songchun Fan3c82a302019-11-29 14:23:45 -08001005 if (!status.isOk()) {
1006 return false;
1007 }
Songchun Fan68645c42020-02-27 15:57:35 -08001008 if (!dataloader) {
1009 return false;
1010 }
Alex Buynytskyyb6e02f72020-03-17 18:12:23 -07001011 status = dataloader->start(mountId);
Songchun Fan68645c42020-02-27 15:57:35 -08001012 if (!status.isOk()) {
1013 return false;
1014 }
1015 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001016}
1017
1018void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001019 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1020 const auto path = entry.path().u8string();
1021 const auto name = entry.path().filename().u8string();
1022 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001023 continue;
1024 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001025 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001026 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001027 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001028 }
1029 }
1030}
1031
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001032bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001033 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001034 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001035
Songchun Fan3c82a302019-11-29 14:23:45 -08001036 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001037 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001038 if (!status.isOk()) {
1039 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1040 return false;
1041 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001042
1043 int cmd = controlParcel.cmd.release().release();
1044 int pendingReads = controlParcel.pendingReads.release().release();
1045 int logs = controlParcel.log.release().release();
1046 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001047
1048 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1049
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001050 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1051 path::join(mountTarget, constants().infoMdName));
1052 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001053 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1054 return false;
1055 }
1056
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001057 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001058 mNextId = std::max(mNextId, ifs->mountId + 1);
1059
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001060 // DataLoader params
1061 {
1062 auto& dlp = ifs->dataLoaderParams;
1063 const auto& loader = mount.loader();
1064 dlp.type = (android::content::pm::DataLoaderType)loader.type();
1065 dlp.packageName = loader.package_name();
1066 dlp.className = loader.class_name();
1067 dlp.arguments = loader.arguments();
1068 }
1069
Songchun Fan3c82a302019-11-29 14:23:45 -08001070 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001071 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001072 while (auto e = ::readdir(d.get())) {
1073 if (e->d_type == DT_REG) {
1074 auto name = std::string_view(e->d_name);
1075 if (name.starts_with(constants().mountpointMdPrefix)) {
1076 bindPoints.emplace_back(name,
1077 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1078 ifs->control,
1079 path::join(mountTarget,
1080 name)));
1081 if (bindPoints.back().second.dest_path().empty() ||
1082 bindPoints.back().second.source_subdir().empty()) {
1083 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001084 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001085 }
1086 }
1087 } else if (e->d_type == DT_DIR) {
1088 if (e->d_name == "."sv || e->d_name == ".."sv) {
1089 continue;
1090 }
1091 auto name = std::string_view(e->d_name);
1092 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001093 int storageId;
1094 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1095 name.data() + name.size(), storageId);
1096 if (res.ec != std::errc{} || *res.ptr != '_') {
1097 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1098 << root;
1099 continue;
1100 }
1101 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001102 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001103 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001104 << " for mount " << root;
1105 continue;
1106 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001107 ifs->storages.insert_or_assign(storageId,
1108 IncFsMount::Storage{
1109 path::join(root, constants().mount, name)});
1110 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001111 }
1112 }
1113 }
1114
1115 if (ifs->storages.empty()) {
1116 LOG(WARNING) << "No valid storages in mount " << root;
1117 return false;
1118 }
1119
1120 int bindCount = 0;
1121 for (auto&& bp : bindPoints) {
1122 std::unique_lock l(mLock, std::defer_lock);
1123 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1124 std::move(*bp.second.mutable_source_subdir()),
1125 std::move(*bp.second.mutable_dest_path()),
1126 BindKind::Permanent, l);
1127 }
1128
1129 if (bindCount == 0) {
1130 LOG(WARNING) << "No valid bind points for mount " << root;
1131 deleteStorage(*ifs);
1132 return false;
1133 }
1134
Songchun Fan3c82a302019-11-29 14:23:45 -08001135 mMounts[ifs->mountId] = std::move(ifs);
1136 return true;
1137}
1138
1139bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001140 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001141 if (!mSystemReady.load(std::memory_order_relaxed)) {
1142 std::unique_lock l(ifs.lock);
Songchun Fan3c82a302019-11-29 14:23:45 -08001143 return true; // eventually...
1144 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001145
1146 std::unique_lock l(ifs.lock);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001147 if (ifs.dataLoaderStatus != -1) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001148 LOG(INFO) << "Skipped data loader preparation because it already exists";
1149 return true;
1150 }
1151
Songchun Fan3c82a302019-11-29 14:23:45 -08001152 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001153 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001154 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001155 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001156 base::unique_fd(::dup(ifs.control.pendingReads())));
1157 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001158 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
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) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001340 sp<IAppOpsCallback> listener;
1341 {
1342 std::unique_lock lock{mCallbacksLock};
1343 auto& cb = mCallbackRegistered[packageName];
1344 if (cb) {
1345 return;
1346 }
1347 cb = new AppOpsListener(*this, packageName);
1348 listener = cb;
1349 }
1350
1351 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS, String16(packageName.c_str()), listener);
1352}
1353
1354bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1355 sp<IAppOpsCallback> listener;
1356 {
1357 std::unique_lock lock{mCallbacksLock};
1358 auto found = mCallbackRegistered.find(packageName);
1359 if (found == mCallbackRegistered.end()) {
1360 return false;
1361 }
1362 listener = found->second;
1363 mCallbackRegistered.erase(found);
1364 }
1365
1366 mAppOpsManager->stopWatchingMode(listener);
1367 return true;
1368}
1369
1370void IncrementalService::onAppOpChanged(const std::string& packageName) {
1371 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001372 return;
1373 }
1374
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001375 std::vector<IfsMountPtr> affected;
1376 {
1377 std::lock_guard l(mLock);
1378 affected.reserve(mMounts.size());
1379 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001380 if (ifs->mountId == id && ifs->dataLoaderParams.packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001381 affected.push_back(ifs);
1382 }
1383 }
1384 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001385 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001386 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001387 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001388}
1389
Songchun Fan3c82a302019-11-29 14:23:45 -08001390binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1391 int newStatus) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001392 if (externalListener) {
1393 // Give an external listener a chance to act before we destroy something.
1394 externalListener->onStatusChanged(mountId, newStatus);
1395 }
1396
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001397 bool startRequested = false;
1398 {
1399 std::unique_lock l(incrementalService.mLock);
1400 const auto& ifs = incrementalService.getIfsLocked(mountId);
1401 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001402 LOG(WARNING) << "Received data loader status " << int(newStatus)
1403 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001404 return binder::Status::ok();
1405 }
1406 ifs->dataLoaderStatus = newStatus;
1407
1408 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1409 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1410 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1411 return binder::Status::ok();
1412 }
1413
1414 startRequested = ifs->dataLoaderStartRequested;
Songchun Fan3c82a302019-11-29 14:23:45 -08001415 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001416
Songchun Fan3c82a302019-11-29 14:23:45 -08001417 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001418 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001419 if (startRequested) {
1420 incrementalService.startDataLoader(mountId);
1421 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001422 break;
1423 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001424 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001425 break;
1426 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001427 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001428 break;
1429 }
1430 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1431 break;
1432 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001433 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1434 break;
1435 }
1436 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1437 break;
1438 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001439 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1440 // Nothing for now. Rely on externalListener to handle this.
1441 break;
1442 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001443 default: {
1444 LOG(WARNING) << "Unknown data loader status: " << newStatus
1445 << " for mount: " << mountId;
1446 break;
1447 }
1448 }
1449
1450 return binder::Status::ok();
1451}
1452
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001453void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1454 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001455}
1456
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001457binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1458 bool enableReadLogs, int32_t* _aidl_return) {
1459 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1460 return binder::Status::ok();
1461}
1462
Songchun Fan3c82a302019-11-29 14:23:45 -08001463} // namespace android::incremental