blob: 92366e51eb47a8b35f0fb5fd5868ac0fd187334f [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>
23#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
25#include <android-base/strings.h>
26#include <android/content/pm/IDataLoaderStatusListener.h>
27#include <android/os/IVold.h>
28#include <androidfw/ZipFileRO.h>
29#include <androidfw/ZipUtils.h>
30#include <binder/BinderService.h>
Jooyung Han66c567a2020-03-07 21:47:09 +090031#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080032#include <binder/ParcelFileDescriptor.h>
33#include <binder/Status.h>
34#include <sys/stat.h>
35#include <uuid/uuid.h>
36#include <zlib.h>
37
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070038#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080039#include <ctime>
Songchun Fan1124fd32020-02-10 12:49:41 -080040#include <filesystem>
Songchun Fan3c82a302019-11-29 14:23:45 -080041#include <iterator>
42#include <span>
43#include <stack>
44#include <thread>
45#include <type_traits>
46
47#include "Metadata.pb.h"
48
49using namespace std::literals;
50using namespace android::content::pm;
Songchun Fan1124fd32020-02-10 12:49:41 -080051namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080052
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070053constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070054constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070055
Songchun Fan3c82a302019-11-29 14:23:45 -080056namespace android::incremental {
57
58namespace {
59
60using IncrementalFileSystemControlParcel =
61 ::android::os::incremental::IncrementalFileSystemControlParcel;
62
63struct Constants {
64 static constexpr auto backing = "backing_store"sv;
65 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080066 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080067 static constexpr auto storagePrefix = "st"sv;
68 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
69 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080070 static constexpr auto libDir = "lib"sv;
71 static constexpr auto libSuffix = ".so"sv;
72 static constexpr auto blockSize = 4096;
Songchun Fan3c82a302019-11-29 14:23:45 -080073};
74
75static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070076 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080077 return c;
78}
79
80template <base::LogSeverity level = base::ERROR>
81bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
82 auto cstr = path::c_str(name);
83 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080084 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080085 PLOG(level) << "Can't create directory '" << name << '\'';
86 return false;
87 }
88 struct stat st;
89 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
90 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
91 return false;
92 }
93 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080094 if (::chmod(cstr, mode)) {
95 PLOG(level) << "Changing permission failed for '" << name << '\'';
96 return false;
97 }
98
Songchun Fan3c82a302019-11-29 14:23:45 -080099 return true;
100}
101
102static std::string toMountKey(std::string_view path) {
103 if (path.empty()) {
104 return "@none";
105 }
106 if (path == "/"sv) {
107 return "@root";
108 }
109 if (path::isAbsolute(path)) {
110 path.remove_prefix(1);
111 }
112 std::string res(path);
113 std::replace(res.begin(), res.end(), '/', '_');
114 std::replace(res.begin(), res.end(), '@', '_');
Songchun Fan1124fd32020-02-10 12:49:41 -0800115 return std::string(constants().mountKeyPrefix) + res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800116}
117
118static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
119 std::string_view path) {
120 auto mountKey = toMountKey(path);
121 const auto prefixSize = mountKey.size();
122 for (int counter = 0; counter < 1000;
123 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
124 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800125 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800126 return {mountKey, mountRoot};
127 }
128 }
129 return {};
130}
131
132template <class ProtoMessage, class Control>
133static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
134 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800135 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800136 ProtoMessage message;
137 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
138}
139
140static bool isValidMountTarget(std::string_view path) {
141 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
142}
143
144std::string makeBindMdName() {
145 static constexpr auto uuidStringSize = 36;
146
147 uuid_t guid;
148 uuid_generate(guid);
149
150 std::string name;
151 const auto prefixSize = constants().mountpointMdPrefix.size();
152 name.reserve(prefixSize + uuidStringSize);
153
154 name = constants().mountpointMdPrefix;
155 name.resize(prefixSize + uuidStringSize);
156 uuid_unparse(guid, name.data() + prefixSize);
157
158 return name;
159}
160} // namespace
161
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700162const bool IncrementalService::sEnablePerfLogging =
163 android::base::GetBoolProperty("incremental.perflogging", false);
164
Songchun Fan3c82a302019-11-29 14:23:45 -0800165IncrementalService::IncFsMount::~IncFsMount() {
Songchun Fan68645c42020-02-27 15:57:35 -0800166 incrementalService.mDataLoaderManager->destroyDataLoader(mountId);
Songchun Fan3c82a302019-11-29 14:23:45 -0800167 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
168 for (auto&& [target, _] : bindPoints) {
169 LOG(INFO) << "\tbind: " << target;
170 incrementalService.mVold->unmountIncFs(target);
171 }
172 LOG(INFO) << "\troot: " << root;
173 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
174 cleanupFilesystem(root);
175}
176
177auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800178 std::string name;
179 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
180 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
181 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800182 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
183 constants().storagePrefix.data(), id, no);
184 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800185 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800186 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800187 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
188 } else if (err != EEXIST) {
189 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
190 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800191 }
192 }
193 nextStorageDirNo = 0;
194 return storages.end();
195}
196
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800197static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
198 return {::opendir(path), ::closedir};
199}
200
201static int rmDirContent(const char* path) {
202 auto dir = openDir(path);
203 if (!dir) {
204 return -EINVAL;
205 }
206 while (auto entry = ::readdir(dir.get())) {
207 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
208 continue;
209 }
210 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
211 if (entry->d_type == DT_DIR) {
212 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
213 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
214 return err;
215 }
216 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
217 PLOG(WARNING) << "Failed to rmdir " << fullPath;
218 return err;
219 }
220 } else {
221 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
222 PLOG(WARNING) << "Failed to delete " << fullPath;
223 return err;
224 }
225 }
226 }
227 return 0;
228}
229
Songchun Fan3c82a302019-11-29 14:23:45 -0800230void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800231 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800232 ::rmdir(path::join(root, constants().backing).c_str());
233 ::rmdir(path::join(root, constants().mount).c_str());
234 ::rmdir(path::c_str(root));
235}
236
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800237IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800238 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800239 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800240 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700241 mAppOpsManager(sm.getAppOpsManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800242 mIncrementalDir(rootDir) {
243 if (!mVold) {
244 LOG(FATAL) << "Vold service is unavailable";
245 }
Songchun Fan68645c42020-02-27 15:57:35 -0800246 if (!mDataLoaderManager) {
247 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800248 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700249 if (!mAppOpsManager) {
250 LOG(FATAL) << "AppOpsManager is unavailable";
251 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800252 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800253}
254
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800255FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800256 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800257}
258
Songchun Fan3c82a302019-11-29 14:23:45 -0800259IncrementalService::~IncrementalService() = default;
260
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800261inline const char* toString(TimePoint t) {
262 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800263 time_t time = SystemClock::to_time_t(
264 SystemClock::now() +
265 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800266 return std::ctime(&time);
267}
268
269inline const char* toString(IncrementalService::BindKind kind) {
270 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800271 case IncrementalService::BindKind::Temporary:
272 return "Temporary";
273 case IncrementalService::BindKind::Permanent:
274 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800275 }
276}
277
278void IncrementalService::onDump(int fd) {
279 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
280 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
281
282 std::unique_lock l(mLock);
283
284 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
285 for (auto&& [id, ifs] : mMounts) {
286 const IncFsMount& mnt = *ifs.get();
287 dprintf(fd, "\t[%d]:\n", id);
288 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700289 dprintf(fd, "\t\troot: %s\n", mnt.root.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800290 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
291 dprintf(fd, "\t\tdataLoaderStatus: %d\n", mnt.dataLoaderStatus.load());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700292 {
293 const auto& params = mnt.dataLoaderParams;
294 dprintf(fd, "\t\tdataLoaderParams:\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800295 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
296 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
297 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
298 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800299 }
300 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
301 for (auto&& [storageId, storage] : mnt.storages) {
302 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
303 }
304
305 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
306 for (auto&& [target, bind] : mnt.bindPoints) {
307 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
308 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
309 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
310 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
311 }
312 }
313
314 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
315 for (auto&& [target, mountPairIt] : mBindsByPath) {
316 const auto& bind = mountPairIt->second;
317 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
318 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
319 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
320 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
321 }
322}
323
Songchun Fan3c82a302019-11-29 14:23:45 -0800324std::optional<std::future<void>> IncrementalService::onSystemReady() {
325 std::promise<void> threadFinished;
326 if (mSystemReady.exchange(true)) {
327 return {};
328 }
329
330 std::vector<IfsMountPtr> mounts;
331 {
332 std::lock_guard l(mLock);
333 mounts.reserve(mMounts.size());
334 for (auto&& [id, ifs] : mMounts) {
335 if (ifs->mountId == id) {
336 mounts.push_back(ifs);
337 }
338 }
339 }
340
341 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700342 /* TODO(b/151241369): restore data loaders on reboot.
Songchun Fan3c82a302019-11-29 14:23:45 -0800343 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800344 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800345 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
346 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800347 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800348 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800349 }
350 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700351 */
Songchun Fan3c82a302019-11-29 14:23:45 -0800352 mPrepareDataLoaders.set_value_at_thread_exit();
353 }).detach();
354 return mPrepareDataLoaders.get_future();
355}
356
357auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
358 for (;;) {
359 if (mNextId == kMaxStorageId) {
360 mNextId = 0;
361 }
362 auto id = ++mNextId;
363 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
364 if (inserted) {
365 return it;
366 }
367 }
368}
369
Songchun Fan1124fd32020-02-10 12:49:41 -0800370StorageId IncrementalService::createStorage(
371 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
372 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800373 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
374 if (!path::isAbsolute(mountPoint)) {
375 LOG(ERROR) << "path is not absolute: " << mountPoint;
376 return kInvalidStorageId;
377 }
378
379 auto mountNorm = path::normalize(mountPoint);
380 {
381 const auto id = findStorageId(mountNorm);
382 if (id != kInvalidStorageId) {
383 if (options & CreateOptions::OpenExisting) {
384 LOG(INFO) << "Opened existing storage " << id;
385 return id;
386 }
387 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
388 return kInvalidStorageId;
389 }
390 }
391
392 if (!(options & CreateOptions::CreateNew)) {
393 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
394 return kInvalidStorageId;
395 }
396
397 if (!path::isEmptyDir(mountNorm)) {
398 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
399 return kInvalidStorageId;
400 }
401 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
402 if (mountRoot.empty()) {
403 LOG(ERROR) << "Bad mount point";
404 return kInvalidStorageId;
405 }
406 // Make sure the code removes all crap it may create while still failing.
407 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
408 auto firstCleanupOnFailure =
409 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
410
411 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800412 const auto backing = path::join(mountRoot, constants().backing);
413 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800414 return kInvalidStorageId;
415 }
416
Songchun Fan3c82a302019-11-29 14:23:45 -0800417 IncFsMount::Control control;
418 {
419 std::lock_guard l(mMountOperationLock);
420 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800421
422 if (auto err = rmDirContent(backing.c_str())) {
423 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
424 return kInvalidStorageId;
425 }
426 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
427 return kInvalidStorageId;
428 }
429 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800430 if (!status.isOk()) {
431 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
432 return kInvalidStorageId;
433 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800434 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
435 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800436 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
437 return kInvalidStorageId;
438 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800439 int cmd = controlParcel.cmd.release().release();
440 int pendingReads = controlParcel.pendingReads.release().release();
441 int logs = controlParcel.log.release().release();
442 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800443 }
444
445 std::unique_lock l(mLock);
446 const auto mountIt = getStorageSlotLocked();
447 const auto mountId = mountIt->first;
448 l.unlock();
449
450 auto ifs =
451 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
452 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
453 // is the removal of the |ifs|.
454 firstCleanupOnFailure.release();
455
456 auto secondCleanup = [this, &l](auto itPtr) {
457 if (!l.owns_lock()) {
458 l.lock();
459 }
460 mMounts.erase(*itPtr);
461 };
462 auto secondCleanupOnFailure =
463 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
464
465 const auto storageIt = ifs->makeStorage(ifs->mountId);
466 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800467 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800468 return kInvalidStorageId;
469 }
470
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700471 ifs->dataLoaderParams = std::move(dataLoaderParams);
472
Songchun Fan3c82a302019-11-29 14:23:45 -0800473 {
474 metadata::Mount m;
475 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700476 m.mutable_loader()->set_type((int)ifs->dataLoaderParams.type);
477 m.mutable_loader()->set_package_name(ifs->dataLoaderParams.packageName);
478 m.mutable_loader()->set_class_name(ifs->dataLoaderParams.className);
479 m.mutable_loader()->set_arguments(ifs->dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800480 const auto metadata = m.SerializeAsString();
481 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800482 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800483 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800484 if (auto err =
485 mIncFs->makeFile(ifs->control,
486 path::join(ifs->root, constants().mount,
487 constants().infoMdName),
488 0777, idFromMetadata(metadata),
489 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800490 LOG(ERROR) << "Saving mount metadata failed: " << -err;
491 return kInvalidStorageId;
492 }
493 }
494
495 const auto bk =
496 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800497 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
498 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800499 err < 0) {
500 LOG(ERROR) << "adding bind mount failed: " << -err;
501 return kInvalidStorageId;
502 }
503
504 // Done here as well, all data structures are in good state.
505 secondCleanupOnFailure.release();
506
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700507 if (!prepareDataLoader(*ifs, &dataLoaderStatusListener)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800508 LOG(ERROR) << "prepareDataLoader() failed";
509 deleteStorageLocked(*ifs, std::move(l));
510 return kInvalidStorageId;
511 }
512
513 mountIt->second = std::move(ifs);
514 l.unlock();
515 LOG(INFO) << "created storage " << mountId;
516 return mountId;
517}
518
519StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
520 StorageId linkedStorage,
521 IncrementalService::CreateOptions options) {
522 if (!isValidMountTarget(mountPoint)) {
523 LOG(ERROR) << "Mount point is invalid or missing";
524 return kInvalidStorageId;
525 }
526
527 std::unique_lock l(mLock);
528 const auto& ifs = getIfsLocked(linkedStorage);
529 if (!ifs) {
530 LOG(ERROR) << "Ifs unavailable";
531 return kInvalidStorageId;
532 }
533
534 const auto mountIt = getStorageSlotLocked();
535 const auto storageId = mountIt->first;
536 const auto storageIt = ifs->makeStorage(storageId);
537 if (storageIt == ifs->storages.end()) {
538 LOG(ERROR) << "Can't create a new storage";
539 mMounts.erase(mountIt);
540 return kInvalidStorageId;
541 }
542
543 l.unlock();
544
545 const auto bk =
546 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800547 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
548 std::string(storageIt->second.name), path::normalize(mountPoint),
549 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800550 err < 0) {
551 LOG(ERROR) << "bindMount failed with error: " << err;
552 return kInvalidStorageId;
553 }
554
555 mountIt->second = ifs;
556 return storageId;
557}
558
559IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
560 std::string_view path) const {
561 auto bindPointIt = mBindsByPath.upper_bound(path);
562 if (bindPointIt == mBindsByPath.begin()) {
563 return mBindsByPath.end();
564 }
565 --bindPointIt;
566 if (!path::startsWith(path, bindPointIt->first)) {
567 return mBindsByPath.end();
568 }
569 return bindPointIt;
570}
571
572StorageId IncrementalService::findStorageId(std::string_view path) const {
573 std::lock_guard l(mLock);
574 auto it = findStorageLocked(path);
575 if (it == mBindsByPath.end()) {
576 return kInvalidStorageId;
577 }
578 return it->second->second.storage;
579}
580
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700581int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
582 const auto ifs = getIfs(storageId);
583 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700584 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700585 return -EINVAL;
586 }
587
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700588 if (enableReadLogs) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700589 if (auto status =
590 mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
591 ifs->dataLoaderParams.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700592 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700593 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700594 return fromBinderStatus(status);
595 }
596 }
597
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700598 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
599 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
600 return fromBinderStatus(status);
601 }
602
603 if (enableReadLogs) {
604 registerAppOpsCallback(ifs->dataLoaderParams.packageName);
605 }
606
607 return 0;
608}
609
610binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700611 using unique_fd = ::android::base::unique_fd;
612 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700613 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
614 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
615 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700616 if (logsFd >= 0) {
617 control.log.reset(unique_fd(dup(logsFd)));
618 }
619
620 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700621 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700622}
623
Songchun Fan3c82a302019-11-29 14:23:45 -0800624void IncrementalService::deleteStorage(StorageId storageId) {
625 const auto ifs = getIfs(storageId);
626 if (!ifs) {
627 return;
628 }
629 deleteStorage(*ifs);
630}
631
632void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
633 std::unique_lock l(ifs.lock);
634 deleteStorageLocked(ifs, std::move(l));
635}
636
637void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
638 std::unique_lock<std::mutex>&& ifsLock) {
639 const auto storages = std::move(ifs.storages);
640 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
641 const auto bindPoints = ifs.bindPoints;
642 ifsLock.unlock();
643
644 std::lock_guard l(mLock);
645 for (auto&& [id, _] : storages) {
646 if (id != ifs.mountId) {
647 mMounts.erase(id);
648 }
649 }
650 for (auto&& [path, _] : bindPoints) {
651 mBindsByPath.erase(path);
652 }
653 mMounts.erase(ifs.mountId);
654}
655
656StorageId IncrementalService::openStorage(std::string_view pathInMount) {
657 if (!path::isAbsolute(pathInMount)) {
658 return kInvalidStorageId;
659 }
660
661 return findStorageId(path::normalize(pathInMount));
662}
663
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800664FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800665 const auto ifs = getIfs(storage);
666 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800667 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800668 }
669 std::unique_lock l(ifs->lock);
670 auto storageIt = ifs->storages.find(storage);
671 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800672 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800673 }
674 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800675 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800676 }
677 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
678 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800679 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800680}
681
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800682std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800683 StorageId storage, std::string_view subpath) const {
684 auto name = path::basename(subpath);
685 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800686 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800687 }
688 auto dir = path::dirname(subpath);
689 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800690 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800691 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800692 auto id = nodeFor(storage, dir);
693 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800694}
695
696IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
697 std::lock_guard l(mLock);
698 return getIfsLocked(storage);
699}
700
701const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
702 auto it = mMounts.find(storage);
703 if (it == mMounts.end()) {
704 static const IfsMountPtr kEmpty = {};
705 return kEmpty;
706 }
707 return it->second;
708}
709
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800710int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
711 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800712 if (!isValidMountTarget(target)) {
713 return -EINVAL;
714 }
715
716 const auto ifs = getIfs(storage);
717 if (!ifs) {
718 return -EINVAL;
719 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800720
Songchun Fan3c82a302019-11-29 14:23:45 -0800721 std::unique_lock l(ifs->lock);
722 const auto storageInfo = ifs->storages.find(storage);
723 if (storageInfo == ifs->storages.end()) {
724 return -EINVAL;
725 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700726 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
727 if (normSource.empty()) {
728 return -EINVAL;
729 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800730 l.unlock();
731 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800732 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
733 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800734}
735
736int IncrementalService::unbind(StorageId storage, std::string_view target) {
737 if (!path::isAbsolute(target)) {
738 return -EINVAL;
739 }
740
741 LOG(INFO) << "Removing bind point " << target;
742
743 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
744 // otherwise there's a chance to unmount something completely unrelated
745 const auto norm = path::normalize(target);
746 std::unique_lock l(mLock);
747 const auto storageIt = mBindsByPath.find(norm);
748 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
749 return -EINVAL;
750 }
751 const auto bindIt = storageIt->second;
752 const auto storageId = bindIt->second.storage;
753 const auto ifs = getIfsLocked(storageId);
754 if (!ifs) {
755 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
756 << " is missing";
757 return -EFAULT;
758 }
759 mBindsByPath.erase(storageIt);
760 l.unlock();
761
762 mVold->unmountIncFs(bindIt->first);
763 std::unique_lock l2(ifs->lock);
764 if (ifs->bindPoints.size() <= 1) {
765 ifs->bindPoints.clear();
766 deleteStorageLocked(*ifs, std::move(l2));
767 } else {
768 const std::string savedFile = std::move(bindIt->second.savedFilename);
769 ifs->bindPoints.erase(bindIt);
770 l2.unlock();
771 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800772 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800773 }
774 }
775 return 0;
776}
777
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700778std::string IncrementalService::normalizePathToStorageLocked(
779 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
780 std::string normPath;
781 if (path::isAbsolute(path)) {
782 normPath = path::normalize(path);
783 if (!path::startsWith(normPath, storageIt->second.name)) {
784 return {};
785 }
786 } else {
787 normPath = path::normalize(path::join(storageIt->second.name, path));
788 }
789 return normPath;
790}
791
792std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800793 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700794 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800795 const auto storageInfo = ifs->storages.find(storage);
796 if (storageInfo == ifs->storages.end()) {
797 return {};
798 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700799 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800800}
801
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800802int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
803 incfs::NewFileParams params) {
804 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800805 std::string normPath = normalizePathToStorage(ifs, storage, path);
806 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700807 LOG(ERROR) << "Internal error: storageId " << storage
808 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800809 return -EINVAL;
810 }
811 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800812 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700813 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800814 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800815 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800816 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800817 }
818 return -EINVAL;
819}
820
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800821int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800822 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800823 std::string normPath = normalizePathToStorage(ifs, storageId, path);
824 if (normPath.empty()) {
825 return -EINVAL;
826 }
827 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800828 }
829 return -EINVAL;
830}
831
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800832int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800833 const auto ifs = getIfs(storageId);
834 if (!ifs) {
835 return -EINVAL;
836 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800837 std::string normPath = normalizePathToStorage(ifs, storageId, path);
838 if (normPath.empty()) {
839 return -EINVAL;
840 }
841 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800842 if (err == -EEXIST) {
843 return 0;
844 } else if (err != -ENOENT) {
845 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800846 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800847 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800848 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800849 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800850 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800851}
852
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800853int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
854 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700855 auto ifsSrc = getIfs(sourceStorageId);
856 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
857 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800858 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
859 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
860 if (normOldPath.empty() || normNewPath.empty()) {
861 return -EINVAL;
862 }
863 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800864 }
865 return -EINVAL;
866}
867
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800868int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800869 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800870 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
871 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800872 }
873 return -EINVAL;
874}
875
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800876int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
877 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800878 std::string&& target, BindKind kind,
879 std::unique_lock<std::mutex>& mainLock) {
880 if (!isValidMountTarget(target)) {
881 return -EINVAL;
882 }
883
884 std::string mdFileName;
885 if (kind != BindKind::Temporary) {
886 metadata::BindPoint bp;
887 bp.set_storage_id(storage);
888 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800889 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800890 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800891 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800892 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800893 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800894 auto node =
895 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
896 0444, idFromMetadata(metadata),
897 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
898 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800899 return int(node);
900 }
901 }
902
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800903 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800904 std::move(target), kind, mainLock);
905}
906
907int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800908 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800909 std::string&& target, BindKind kind,
910 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800911 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800912 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800913 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800914 if (!status.isOk()) {
915 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
916 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
917 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
918 : status.serviceSpecificErrorCode() == 0
919 ? -EFAULT
920 : status.serviceSpecificErrorCode()
921 : -EIO;
922 }
923 }
924
925 if (!mainLock.owns_lock()) {
926 mainLock.lock();
927 }
928 std::lock_guard l(ifs.lock);
929 const auto [it, _] =
930 ifs.bindPoints.insert_or_assign(target,
931 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800932 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800933 mBindsByPath[std::move(target)] = it;
934 return 0;
935}
936
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800937RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800938 const auto ifs = getIfs(storage);
939 if (!ifs) {
940 return {};
941 }
942 return mIncFs->getMetadata(ifs->control, node);
943}
944
945std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
946 const auto ifs = getIfs(storage);
947 if (!ifs) {
948 return {};
949 }
950
951 std::unique_lock l(ifs->lock);
952 auto subdirIt = ifs->storages.find(storage);
953 if (subdirIt == ifs->storages.end()) {
954 return {};
955 }
956 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
957 l.unlock();
958
959 const auto prefixSize = dir.size() + 1;
960 std::vector<std::string> todoDirs{std::move(dir)};
961 std::vector<std::string> result;
962 do {
963 auto currDir = std::move(todoDirs.back());
964 todoDirs.pop_back();
965
966 auto d =
967 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
968 while (auto e = ::readdir(d.get())) {
969 if (e->d_type == DT_REG) {
970 result.emplace_back(
971 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
972 continue;
973 }
974 if (e->d_type == DT_DIR) {
975 if (e->d_name == "."sv || e->d_name == ".."sv) {
976 continue;
977 }
978 todoDirs.emplace_back(path::join(currDir, e->d_name));
979 continue;
980 }
981 }
982 } while (!todoDirs.empty());
983 return result;
984}
985
986bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700987 {
988 std::unique_lock l(mLock);
989 const auto& ifs = getIfsLocked(storage);
990 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800991 return false;
992 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700993 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
994 ifs->dataLoaderStartRequested = true;
995 return true;
996 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800997 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700998 return startDataLoader(storage);
999}
1000
1001bool IncrementalService::startDataLoader(MountId mountId) const {
Songchun Fan68645c42020-02-27 15:57:35 -08001002 sp<IDataLoader> dataloader;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001003 auto status = mDataLoaderManager->getDataLoader(mountId, &dataloader);
Songchun Fan3c82a302019-11-29 14:23:45 -08001004 if (!status.isOk()) {
1005 return false;
1006 }
Songchun Fan68645c42020-02-27 15:57:35 -08001007 if (!dataloader) {
1008 return false;
1009 }
Alex Buynytskyyb6e02f72020-03-17 18:12:23 -07001010 status = dataloader->start(mountId);
Songchun Fan68645c42020-02-27 15:57:35 -08001011 if (!status.isOk()) {
1012 return false;
1013 }
1014 return true;
Songchun Fan3c82a302019-11-29 14:23:45 -08001015}
1016
1017void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001018 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1019 const auto path = entry.path().u8string();
1020 const auto name = entry.path().filename().u8string();
1021 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001022 continue;
1023 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001024 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001025 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001026 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001027 }
1028 }
1029}
1030
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001031bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001032 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001033 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001034
Songchun Fan3c82a302019-11-29 14:23:45 -08001035 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001036 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001037 if (!status.isOk()) {
1038 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1039 return false;
1040 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001041
1042 int cmd = controlParcel.cmd.release().release();
1043 int pendingReads = controlParcel.pendingReads.release().release();
1044 int logs = controlParcel.log.release().release();
1045 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001046
1047 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1048
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001049 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1050 path::join(mountTarget, constants().infoMdName));
1051 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001052 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1053 return false;
1054 }
1055
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001056 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001057 mNextId = std::max(mNextId, ifs->mountId + 1);
1058
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001059 // DataLoader params
1060 {
1061 auto& dlp = ifs->dataLoaderParams;
1062 const auto& loader = mount.loader();
1063 dlp.type = (android::content::pm::DataLoaderType)loader.type();
1064 dlp.packageName = loader.package_name();
1065 dlp.className = loader.class_name();
1066 dlp.arguments = loader.arguments();
1067 }
1068
Songchun Fan3c82a302019-11-29 14:23:45 -08001069 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001070 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001071 while (auto e = ::readdir(d.get())) {
1072 if (e->d_type == DT_REG) {
1073 auto name = std::string_view(e->d_name);
1074 if (name.starts_with(constants().mountpointMdPrefix)) {
1075 bindPoints.emplace_back(name,
1076 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1077 ifs->control,
1078 path::join(mountTarget,
1079 name)));
1080 if (bindPoints.back().second.dest_path().empty() ||
1081 bindPoints.back().second.source_subdir().empty()) {
1082 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001083 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001084 }
1085 }
1086 } else if (e->d_type == DT_DIR) {
1087 if (e->d_name == "."sv || e->d_name == ".."sv) {
1088 continue;
1089 }
1090 auto name = std::string_view(e->d_name);
1091 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001092 int storageId;
1093 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1094 name.data() + name.size(), storageId);
1095 if (res.ec != std::errc{} || *res.ptr != '_') {
1096 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1097 << root;
1098 continue;
1099 }
1100 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001101 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001102 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001103 << " for mount " << root;
1104 continue;
1105 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001106 ifs->storages.insert_or_assign(storageId,
1107 IncFsMount::Storage{
1108 path::join(root, constants().mount, name)});
1109 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001110 }
1111 }
1112 }
1113
1114 if (ifs->storages.empty()) {
1115 LOG(WARNING) << "No valid storages in mount " << root;
1116 return false;
1117 }
1118
1119 int bindCount = 0;
1120 for (auto&& bp : bindPoints) {
1121 std::unique_lock l(mLock, std::defer_lock);
1122 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1123 std::move(*bp.second.mutable_source_subdir()),
1124 std::move(*bp.second.mutable_dest_path()),
1125 BindKind::Permanent, l);
1126 }
1127
1128 if (bindCount == 0) {
1129 LOG(WARNING) << "No valid bind points for mount " << root;
1130 deleteStorage(*ifs);
1131 return false;
1132 }
1133
Songchun Fan3c82a302019-11-29 14:23:45 -08001134 mMounts[ifs->mountId] = std::move(ifs);
1135 return true;
1136}
1137
1138bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001139 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001140 if (!mSystemReady.load(std::memory_order_relaxed)) {
1141 std::unique_lock l(ifs.lock);
Songchun Fan3c82a302019-11-29 14:23:45 -08001142 return true; // eventually...
1143 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001144
1145 std::unique_lock l(ifs.lock);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001146 if (ifs.dataLoaderStatus != -1) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001147 LOG(INFO) << "Skipped data loader preparation because it already exists";
1148 return true;
1149 }
1150
Songchun Fan3c82a302019-11-29 14:23:45 -08001151 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001152 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001153 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001154 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001155 base::unique_fd(::dup(ifs.control.pendingReads())));
1156 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001157 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Songchun Fan1124fd32020-02-10 12:49:41 -08001158 sp<IncrementalDataLoaderListener> listener =
Songchun Fan306b7df2020-03-17 12:37:07 -07001159 new IncrementalDataLoaderListener(*this,
1160 externalListener ? *externalListener
1161 : DataLoaderStatusListener());
Songchun Fan3c82a302019-11-29 14:23:45 -08001162 bool created = false;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001163 auto status = mDataLoaderManager->initializeDataLoader(ifs.mountId, ifs.dataLoaderParams, fsControlParcel, listener, &created);
Songchun Fan3c82a302019-11-29 14:23:45 -08001164 if (!status.isOk() || !created) {
1165 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
1166 return false;
1167 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001168 return true;
1169}
1170
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001171template <class Duration>
1172static long elapsedMcs(Duration start, Duration end) {
1173 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1174}
1175
1176// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001177bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1178 std::string_view libDirRelativePath,
1179 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001180 namespace sc = std::chrono;
1181 using Clock = sc::steady_clock;
1182 auto start = Clock::now();
1183
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001184 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001185 if (!ifs) {
1186 LOG(ERROR) << "Invalid storage " << storage;
1187 return false;
1188 }
1189
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001190 // First prepare target directories if they don't exist yet
1191 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1192 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1193 << " errno: " << res;
1194 return false;
1195 }
1196
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001197 auto mkDirsTs = Clock::now();
1198
1199 std::unique_ptr<ZipFileRO> zipFile(ZipFileRO::open(path::c_str(apkFullPath)));
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001200 if (!zipFile) {
1201 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1202 return false;
1203 }
1204 void* cookie = nullptr;
1205 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001206 if (!zipFile->startIteration(&cookie, libFilePrefix.c_str() /* prefix */,
1207 constants().libSuffix.data() /* suffix */)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001208 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1209 return false;
1210 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001211 auto endIteration = [&zipFile](void* cookie) { zipFile->endIteration(cookie); };
1212 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1213
1214 auto openZipTs = Clock::now();
1215
1216 std::vector<IncFsDataBlock> instructions;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001217 ZipEntryRO entry = nullptr;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001218 while ((entry = zipFile->nextEntry(cookie)) != nullptr) {
1219 auto startFileTs = Clock::now();
1220
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001221 char fileName[PATH_MAX];
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001222 if (zipFile->getEntryFileName(entry, fileName, sizeof(fileName))) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001223 continue;
1224 }
1225 const auto libName = path::basename(fileName);
1226 const auto targetLibPath = path::join(libDirRelativePath, libName);
1227 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1228 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001229 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1230 if (sEnablePerfLogging) {
1231 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1232 << "; skipping extraction, spent "
1233 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1234 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001235 continue;
1236 }
1237
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001238 uint32_t uncompressedLen, compressedLen;
1239 if (!zipFile->getEntryInfo(entry, nullptr, &uncompressedLen, &compressedLen, nullptr,
1240 nullptr, nullptr)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001241 LOG(ERROR) << "Failed to read native lib entry: " << fileName;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001242 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001243 }
1244
1245 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001246 incfs::NewFileParams libFileParams = {
1247 .size = uncompressedLen,
1248 .signature = {},
1249 // Metadata of the new lib file is its relative path
1250 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1251 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001252 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001253 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1254 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001255 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001256 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001257 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001258 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001259
1260 auto makeFileTs = Clock::now();
1261
Songchun Fanafaf6e92020-03-18 14:12:20 -07001262 // If it is a zero-byte file, skip data writing
1263 if (uncompressedLen == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001264 if (sEnablePerfLogging) {
1265 LOG(INFO) << "incfs: Extracted " << libName << "(" << compressedLen << " -> "
1266 << uncompressedLen << " bytes): " << elapsedMcs(startFileTs, makeFileTs)
1267 << "mcs, make: " << elapsedMcs(startFileTs, makeFileTs);
1268 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001269 continue;
1270 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001271
1272 // Write extracted data to new file
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001273 // NOTE: don't zero-initialize memory, it may take a while
1274 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[uncompressedLen]);
1275 if (!zipFile->uncompressEntry(entry, libData.get(), uncompressedLen)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001276 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001277 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001278 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001279
1280 auto extractFileTs = Clock::now();
1281
Yurii Zubrytskyie82cdd72020-04-01 12:19:26 -07001282 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1283 if (!writeFd.ok()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001284 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001285 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001286 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001287
1288 auto openFileTs = Clock::now();
1289
1290 const int numBlocks = (uncompressedLen + constants().blockSize - 1) / constants().blockSize;
1291 instructions.clear();
1292 instructions.reserve(numBlocks);
1293 auto remainingData = std::span(libData.get(), uncompressedLen);
1294 for (int i = 0; i < numBlocks; i++) {
1295 const auto blockSize = std::min<uint16_t>(constants().blockSize, remainingData.size());
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001296 auto inst = IncFsDataBlock{
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001297 .fileFd = writeFd.get(),
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001298 .pageIndex = static_cast<IncFsBlockIndex>(i),
1299 .compression = INCFS_COMPRESSION_KIND_NONE,
1300 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001301 .dataSize = blockSize,
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001302 .data = reinterpret_cast<const char*>(remainingData.data()),
1303 };
1304 instructions.push_back(inst);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001305 remainingData = remainingData.subspan(blockSize);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001306 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001307 auto prepareInstsTs = Clock::now();
1308
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001309 size_t res = mIncFs->writeBlocks(instructions);
1310 if (res != instructions.size()) {
1311 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001312 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001313 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001314
1315 if (sEnablePerfLogging) {
1316 auto endFileTs = Clock::now();
1317 LOG(INFO) << "incfs: Extracted " << libName << "(" << compressedLen << " -> "
1318 << uncompressedLen << " bytes): " << elapsedMcs(startFileTs, endFileTs)
1319 << "mcs, make: " << elapsedMcs(startFileTs, makeFileTs)
1320 << " extract: " << elapsedMcs(makeFileTs, extractFileTs)
1321 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1322 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1323 << " write:" << elapsedMcs(prepareInstsTs, endFileTs);
1324 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001325 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001326
1327 if (sEnablePerfLogging) {
1328 auto end = Clock::now();
1329 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1330 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1331 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
1332 << " extract all: " << elapsedMcs(openZipTs, end);
1333 }
1334
1335 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001336}
1337
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001338void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001339 sp<IAppOpsCallback> listener;
1340 {
1341 std::unique_lock lock{mCallbacksLock};
1342 auto& cb = mCallbackRegistered[packageName];
1343 if (cb) {
1344 return;
1345 }
1346 cb = new AppOpsListener(*this, packageName);
1347 listener = cb;
1348 }
1349
1350 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS, String16(packageName.c_str()), listener);
1351}
1352
1353bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1354 sp<IAppOpsCallback> listener;
1355 {
1356 std::unique_lock lock{mCallbacksLock};
1357 auto found = mCallbackRegistered.find(packageName);
1358 if (found == mCallbackRegistered.end()) {
1359 return false;
1360 }
1361 listener = found->second;
1362 mCallbackRegistered.erase(found);
1363 }
1364
1365 mAppOpsManager->stopWatchingMode(listener);
1366 return true;
1367}
1368
1369void IncrementalService::onAppOpChanged(const std::string& packageName) {
1370 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001371 return;
1372 }
1373
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001374 std::vector<IfsMountPtr> affected;
1375 {
1376 std::lock_guard l(mLock);
1377 affected.reserve(mMounts.size());
1378 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001379 if (ifs->mountId == id && ifs->dataLoaderParams.packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001380 affected.push_back(ifs);
1381 }
1382 }
1383 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001384 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001385 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001386 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001387}
1388
Songchun Fan3c82a302019-11-29 14:23:45 -08001389binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1390 int newStatus) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001391 if (externalListener) {
1392 // Give an external listener a chance to act before we destroy something.
1393 externalListener->onStatusChanged(mountId, newStatus);
1394 }
1395
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001396 bool startRequested = false;
1397 {
1398 std::unique_lock l(incrementalService.mLock);
1399 const auto& ifs = incrementalService.getIfsLocked(mountId);
1400 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001401 LOG(WARNING) << "Received data loader status " << int(newStatus)
1402 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001403 return binder::Status::ok();
1404 }
1405 ifs->dataLoaderStatus = newStatus;
1406
1407 if (newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1408 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1409 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1410 return binder::Status::ok();
1411 }
1412
1413 startRequested = ifs->dataLoaderStartRequested;
Songchun Fan3c82a302019-11-29 14:23:45 -08001414 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001415
Songchun Fan3c82a302019-11-29 14:23:45 -08001416 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001417 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001418 if (startRequested) {
1419 incrementalService.startDataLoader(mountId);
1420 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001421 break;
1422 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001423 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001424 break;
1425 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001426 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001427 break;
1428 }
1429 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1430 break;
1431 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001432 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1433 break;
1434 }
1435 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1436 break;
1437 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001438 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1439 // Nothing for now. Rely on externalListener to handle this.
1440 break;
1441 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001442 default: {
1443 LOG(WARNING) << "Unknown data loader status: " << newStatus
1444 << " for mount: " << mountId;
1445 break;
1446 }
1447 }
1448
1449 return binder::Status::ok();
1450}
1451
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001452void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1453 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001454}
1455
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001456binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1457 bool enableReadLogs, int32_t* _aidl_return) {
1458 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1459 return binder::Status::ok();
1460}
1461
Songchun Fan3c82a302019-11-29 14:23:45 -08001462} // namespace android::incremental