blob: 30c2cfd49adff75cf20db47311e4e965bc9c2181 [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() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700166 if (dataLoaderStub) {
167 dataLoaderStub->destroy();
168 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800169 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
170 for (auto&& [target, _] : bindPoints) {
171 LOG(INFO) << "\tbind: " << target;
172 incrementalService.mVold->unmountIncFs(target);
173 }
174 LOG(INFO) << "\troot: " << root;
175 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
176 cleanupFilesystem(root);
177}
178
179auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800180 std::string name;
181 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
182 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
183 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800184 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
185 constants().storagePrefix.data(), id, no);
186 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800187 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800188 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800189 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
190 } else if (err != EEXIST) {
191 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
192 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800193 }
194 }
195 nextStorageDirNo = 0;
196 return storages.end();
197}
198
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800199static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
200 return {::opendir(path), ::closedir};
201}
202
203static int rmDirContent(const char* path) {
204 auto dir = openDir(path);
205 if (!dir) {
206 return -EINVAL;
207 }
208 while (auto entry = ::readdir(dir.get())) {
209 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
210 continue;
211 }
212 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
213 if (entry->d_type == DT_DIR) {
214 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
215 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
216 return err;
217 }
218 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
219 PLOG(WARNING) << "Failed to rmdir " << fullPath;
220 return err;
221 }
222 } else {
223 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
224 PLOG(WARNING) << "Failed to delete " << fullPath;
225 return err;
226 }
227 }
228 }
229 return 0;
230}
231
Songchun Fan3c82a302019-11-29 14:23:45 -0800232void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800233 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800234 ::rmdir(path::join(root, constants().backing).c_str());
235 ::rmdir(path::join(root, constants().mount).c_str());
236 ::rmdir(path::c_str(root));
237}
238
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800239IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800240 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800241 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800242 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700243 mAppOpsManager(sm.getAppOpsManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800244 mIncrementalDir(rootDir) {
245 if (!mVold) {
246 LOG(FATAL) << "Vold service is unavailable";
247 }
Songchun Fan68645c42020-02-27 15:57:35 -0800248 if (!mDataLoaderManager) {
249 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800250 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700251 if (!mAppOpsManager) {
252 LOG(FATAL) << "AppOpsManager is unavailable";
253 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800254 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800255}
256
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800257FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800258 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800259}
260
Songchun Fan3c82a302019-11-29 14:23:45 -0800261IncrementalService::~IncrementalService() = default;
262
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800263inline const char* toString(TimePoint t) {
264 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800265 time_t time = SystemClock::to_time_t(
266 SystemClock::now() +
267 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800268 return std::ctime(&time);
269}
270
271inline const char* toString(IncrementalService::BindKind kind) {
272 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800273 case IncrementalService::BindKind::Temporary:
274 return "Temporary";
275 case IncrementalService::BindKind::Permanent:
276 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800277 }
278}
279
280void IncrementalService::onDump(int fd) {
281 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
282 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
283
284 std::unique_lock l(mLock);
285
286 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
287 for (auto&& [id, ifs] : mMounts) {
288 const IncFsMount& mnt = *ifs.get();
289 dprintf(fd, "\t[%d]:\n", id);
290 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700291 dprintf(fd, "\t\troot: %s\n", mnt.root.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800292 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700293 if (mnt.dataLoaderStub) {
294 const auto& dataLoaderStub = *mnt.dataLoaderStub;
295 dprintf(fd, "\t\tdataLoaderStatus: %d\n", dataLoaderStub.status());
296 dprintf(fd, "\t\tdataLoaderStartRequested: %s\n",
297 dataLoaderStub.startRequested() ? "true" : "false");
298 const auto& params = dataLoaderStub.params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700299 dprintf(fd, "\t\tdataLoaderParams:\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800300 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
301 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
302 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
303 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800304 }
305 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
306 for (auto&& [storageId, storage] : mnt.storages) {
307 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
308 }
309
310 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
311 for (auto&& [target, bind] : mnt.bindPoints) {
312 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
313 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
314 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
315 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
316 }
317 }
318
319 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
320 for (auto&& [target, mountPairIt] : mBindsByPath) {
321 const auto& bind = mountPairIt->second;
322 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
323 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
324 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
325 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
326 }
327}
328
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700329void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800330 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700331 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800332 }
333
334 std::vector<IfsMountPtr> mounts;
335 {
336 std::lock_guard l(mLock);
337 mounts.reserve(mMounts.size());
338 for (auto&& [id, ifs] : mMounts) {
339 if (ifs->mountId == id) {
340 mounts.push_back(ifs);
341 }
342 }
343 }
344
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700345 /* TODO(b/151241369): restore data loaders on reboot.
Songchun Fan3c82a302019-11-29 14:23:45 -0800346 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800347 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800348 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800349 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
350 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800351 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800352 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800353 }
354 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800355 }).detach();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700356 */
Songchun Fan3c82a302019-11-29 14:23:45 -0800357}
358
359auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
360 for (;;) {
361 if (mNextId == kMaxStorageId) {
362 mNextId = 0;
363 }
364 auto id = ++mNextId;
365 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
366 if (inserted) {
367 return it;
368 }
369 }
370}
371
Songchun Fan1124fd32020-02-10 12:49:41 -0800372StorageId IncrementalService::createStorage(
373 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
374 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800375 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
376 if (!path::isAbsolute(mountPoint)) {
377 LOG(ERROR) << "path is not absolute: " << mountPoint;
378 return kInvalidStorageId;
379 }
380
381 auto mountNorm = path::normalize(mountPoint);
382 {
383 const auto id = findStorageId(mountNorm);
384 if (id != kInvalidStorageId) {
385 if (options & CreateOptions::OpenExisting) {
386 LOG(INFO) << "Opened existing storage " << id;
387 return id;
388 }
389 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
390 return kInvalidStorageId;
391 }
392 }
393
394 if (!(options & CreateOptions::CreateNew)) {
395 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
396 return kInvalidStorageId;
397 }
398
399 if (!path::isEmptyDir(mountNorm)) {
400 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
401 return kInvalidStorageId;
402 }
403 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
404 if (mountRoot.empty()) {
405 LOG(ERROR) << "Bad mount point";
406 return kInvalidStorageId;
407 }
408 // Make sure the code removes all crap it may create while still failing.
409 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
410 auto firstCleanupOnFailure =
411 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
412
413 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800414 const auto backing = path::join(mountRoot, constants().backing);
415 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800416 return kInvalidStorageId;
417 }
418
Songchun Fan3c82a302019-11-29 14:23:45 -0800419 IncFsMount::Control control;
420 {
421 std::lock_guard l(mMountOperationLock);
422 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800423
424 if (auto err = rmDirContent(backing.c_str())) {
425 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
426 return kInvalidStorageId;
427 }
428 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
429 return kInvalidStorageId;
430 }
431 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800432 if (!status.isOk()) {
433 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
434 return kInvalidStorageId;
435 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800436 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
437 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800438 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
439 return kInvalidStorageId;
440 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800441 int cmd = controlParcel.cmd.release().release();
442 int pendingReads = controlParcel.pendingReads.release().release();
443 int logs = controlParcel.log.release().release();
444 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800445 }
446
447 std::unique_lock l(mLock);
448 const auto mountIt = getStorageSlotLocked();
449 const auto mountId = mountIt->first;
450 l.unlock();
451
452 auto ifs =
453 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
454 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
455 // is the removal of the |ifs|.
456 firstCleanupOnFailure.release();
457
458 auto secondCleanup = [this, &l](auto itPtr) {
459 if (!l.owns_lock()) {
460 l.lock();
461 }
462 mMounts.erase(*itPtr);
463 };
464 auto secondCleanupOnFailure =
465 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
466
467 const auto storageIt = ifs->makeStorage(ifs->mountId);
468 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800469 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800470 return kInvalidStorageId;
471 }
472
473 {
474 metadata::Mount m;
475 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700476 m.mutable_loader()->set_type((int)dataLoaderParams.type);
477 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
478 m.mutable_loader()->set_class_name(dataLoaderParams.className);
479 m.mutable_loader()->set_arguments(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 Buynytskyy0ea4ff42020-04-09 17:25:42 -0700507 auto dataLoaderStub =
508 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
509 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800510
511 mountIt->second = std::move(ifs);
512 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700513
514 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->create()) {
515 // failed to create data loader
516 LOG(ERROR) << "initializeDataLoader() failed";
517 deleteStorage(dataLoaderStub->id());
518 return kInvalidStorageId;
519 }
520
Songchun Fan3c82a302019-11-29 14:23:45 -0800521 LOG(INFO) << "created storage " << mountId;
522 return mountId;
523}
524
525StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
526 StorageId linkedStorage,
527 IncrementalService::CreateOptions options) {
528 if (!isValidMountTarget(mountPoint)) {
529 LOG(ERROR) << "Mount point is invalid or missing";
530 return kInvalidStorageId;
531 }
532
533 std::unique_lock l(mLock);
534 const auto& ifs = getIfsLocked(linkedStorage);
535 if (!ifs) {
536 LOG(ERROR) << "Ifs unavailable";
537 return kInvalidStorageId;
538 }
539
540 const auto mountIt = getStorageSlotLocked();
541 const auto storageId = mountIt->first;
542 const auto storageIt = ifs->makeStorage(storageId);
543 if (storageIt == ifs->storages.end()) {
544 LOG(ERROR) << "Can't create a new storage";
545 mMounts.erase(mountIt);
546 return kInvalidStorageId;
547 }
548
549 l.unlock();
550
551 const auto bk =
552 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800553 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
554 std::string(storageIt->second.name), path::normalize(mountPoint),
555 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800556 err < 0) {
557 LOG(ERROR) << "bindMount failed with error: " << err;
558 return kInvalidStorageId;
559 }
560
561 mountIt->second = ifs;
562 return storageId;
563}
564
565IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
566 std::string_view path) const {
567 auto bindPointIt = mBindsByPath.upper_bound(path);
568 if (bindPointIt == mBindsByPath.begin()) {
569 return mBindsByPath.end();
570 }
571 --bindPointIt;
572 if (!path::startsWith(path, bindPointIt->first)) {
573 return mBindsByPath.end();
574 }
575 return bindPointIt;
576}
577
578StorageId IncrementalService::findStorageId(std::string_view path) const {
579 std::lock_guard l(mLock);
580 auto it = findStorageLocked(path);
581 if (it == mBindsByPath.end()) {
582 return kInvalidStorageId;
583 }
584 return it->second->second.storage;
585}
586
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700587int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
588 const auto ifs = getIfs(storageId);
589 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700590 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700591 return -EINVAL;
592 }
593
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700594 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700595 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700596 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
597 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700598 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700599 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700600 return fromBinderStatus(status);
601 }
602 }
603
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700604 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
605 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
606 return fromBinderStatus(status);
607 }
608
609 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700610 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700611 }
612
613 return 0;
614}
615
616binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700617 using unique_fd = ::android::base::unique_fd;
618 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700619 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
620 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
621 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700622 if (logsFd >= 0) {
623 control.log.reset(unique_fd(dup(logsFd)));
624 }
625
626 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700627 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700628}
629
Songchun Fan3c82a302019-11-29 14:23:45 -0800630void IncrementalService::deleteStorage(StorageId storageId) {
631 const auto ifs = getIfs(storageId);
632 if (!ifs) {
633 return;
634 }
635 deleteStorage(*ifs);
636}
637
638void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
639 std::unique_lock l(ifs.lock);
640 deleteStorageLocked(ifs, std::move(l));
641}
642
643void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
644 std::unique_lock<std::mutex>&& ifsLock) {
645 const auto storages = std::move(ifs.storages);
646 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
647 const auto bindPoints = ifs.bindPoints;
648 ifsLock.unlock();
649
650 std::lock_guard l(mLock);
651 for (auto&& [id, _] : storages) {
652 if (id != ifs.mountId) {
653 mMounts.erase(id);
654 }
655 }
656 for (auto&& [path, _] : bindPoints) {
657 mBindsByPath.erase(path);
658 }
659 mMounts.erase(ifs.mountId);
660}
661
662StorageId IncrementalService::openStorage(std::string_view pathInMount) {
663 if (!path::isAbsolute(pathInMount)) {
664 return kInvalidStorageId;
665 }
666
667 return findStorageId(path::normalize(pathInMount));
668}
669
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800670FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800671 const auto ifs = getIfs(storage);
672 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800673 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800674 }
675 std::unique_lock l(ifs->lock);
676 auto storageIt = ifs->storages.find(storage);
677 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800678 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800679 }
680 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800681 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800682 }
683 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
684 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800685 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800686}
687
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800688std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800689 StorageId storage, std::string_view subpath) const {
690 auto name = path::basename(subpath);
691 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800692 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800693 }
694 auto dir = path::dirname(subpath);
695 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800696 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800697 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800698 auto id = nodeFor(storage, dir);
699 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800700}
701
702IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
703 std::lock_guard l(mLock);
704 return getIfsLocked(storage);
705}
706
707const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
708 auto it = mMounts.find(storage);
709 if (it == mMounts.end()) {
710 static const IfsMountPtr kEmpty = {};
711 return kEmpty;
712 }
713 return it->second;
714}
715
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800716int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
717 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800718 if (!isValidMountTarget(target)) {
719 return -EINVAL;
720 }
721
722 const auto ifs = getIfs(storage);
723 if (!ifs) {
724 return -EINVAL;
725 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800726
Songchun Fan3c82a302019-11-29 14:23:45 -0800727 std::unique_lock l(ifs->lock);
728 const auto storageInfo = ifs->storages.find(storage);
729 if (storageInfo == ifs->storages.end()) {
730 return -EINVAL;
731 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700732 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
733 if (normSource.empty()) {
734 return -EINVAL;
735 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800736 l.unlock();
737 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800738 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
739 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800740}
741
742int IncrementalService::unbind(StorageId storage, std::string_view target) {
743 if (!path::isAbsolute(target)) {
744 return -EINVAL;
745 }
746
747 LOG(INFO) << "Removing bind point " << target;
748
749 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
750 // otherwise there's a chance to unmount something completely unrelated
751 const auto norm = path::normalize(target);
752 std::unique_lock l(mLock);
753 const auto storageIt = mBindsByPath.find(norm);
754 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
755 return -EINVAL;
756 }
757 const auto bindIt = storageIt->second;
758 const auto storageId = bindIt->second.storage;
759 const auto ifs = getIfsLocked(storageId);
760 if (!ifs) {
761 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
762 << " is missing";
763 return -EFAULT;
764 }
765 mBindsByPath.erase(storageIt);
766 l.unlock();
767
768 mVold->unmountIncFs(bindIt->first);
769 std::unique_lock l2(ifs->lock);
770 if (ifs->bindPoints.size() <= 1) {
771 ifs->bindPoints.clear();
772 deleteStorageLocked(*ifs, std::move(l2));
773 } else {
774 const std::string savedFile = std::move(bindIt->second.savedFilename);
775 ifs->bindPoints.erase(bindIt);
776 l2.unlock();
777 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800778 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800779 }
780 }
781 return 0;
782}
783
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700784std::string IncrementalService::normalizePathToStorageLocked(
785 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
786 std::string normPath;
787 if (path::isAbsolute(path)) {
788 normPath = path::normalize(path);
789 if (!path::startsWith(normPath, storageIt->second.name)) {
790 return {};
791 }
792 } else {
793 normPath = path::normalize(path::join(storageIt->second.name, path));
794 }
795 return normPath;
796}
797
798std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800799 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700800 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800801 const auto storageInfo = ifs->storages.find(storage);
802 if (storageInfo == ifs->storages.end()) {
803 return {};
804 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700805 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800806}
807
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800808int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
809 incfs::NewFileParams params) {
810 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800811 std::string normPath = normalizePathToStorage(ifs, storage, path);
812 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700813 LOG(ERROR) << "Internal error: storageId " << storage
814 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800815 return -EINVAL;
816 }
817 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800818 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700819 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800820 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800821 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800822 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800823 }
824 return -EINVAL;
825}
826
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800827int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800828 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800829 std::string normPath = normalizePathToStorage(ifs, storageId, path);
830 if (normPath.empty()) {
831 return -EINVAL;
832 }
833 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800834 }
835 return -EINVAL;
836}
837
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800838int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800839 const auto ifs = getIfs(storageId);
840 if (!ifs) {
841 return -EINVAL;
842 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800843 std::string normPath = normalizePathToStorage(ifs, storageId, path);
844 if (normPath.empty()) {
845 return -EINVAL;
846 }
847 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800848 if (err == -EEXIST) {
849 return 0;
850 } else if (err != -ENOENT) {
851 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800852 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800853 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800854 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800855 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800856 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800857}
858
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800859int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
860 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700861 auto ifsSrc = getIfs(sourceStorageId);
862 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
863 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800864 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
865 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
866 if (normOldPath.empty() || normNewPath.empty()) {
867 return -EINVAL;
868 }
869 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800870 }
871 return -EINVAL;
872}
873
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800874int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800875 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800876 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
877 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800878 }
879 return -EINVAL;
880}
881
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800882int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
883 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800884 std::string&& target, BindKind kind,
885 std::unique_lock<std::mutex>& mainLock) {
886 if (!isValidMountTarget(target)) {
887 return -EINVAL;
888 }
889
890 std::string mdFileName;
891 if (kind != BindKind::Temporary) {
892 metadata::BindPoint bp;
893 bp.set_storage_id(storage);
894 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800895 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800896 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800897 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800898 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800899 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800900 auto node =
901 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
902 0444, idFromMetadata(metadata),
903 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
904 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800905 return int(node);
906 }
907 }
908
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800909 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 std::move(target), kind, mainLock);
911}
912
913int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800914 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800915 std::string&& target, BindKind kind,
916 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800917 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800918 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800919 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800920 if (!status.isOk()) {
921 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
922 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
923 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
924 : status.serviceSpecificErrorCode() == 0
925 ? -EFAULT
926 : status.serviceSpecificErrorCode()
927 : -EIO;
928 }
929 }
930
931 if (!mainLock.owns_lock()) {
932 mainLock.lock();
933 }
934 std::lock_guard l(ifs.lock);
935 const auto [it, _] =
936 ifs.bindPoints.insert_or_assign(target,
937 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800938 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800939 mBindsByPath[std::move(target)] = it;
940 return 0;
941}
942
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800943RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800944 const auto ifs = getIfs(storage);
945 if (!ifs) {
946 return {};
947 }
948 return mIncFs->getMetadata(ifs->control, node);
949}
950
951std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
952 const auto ifs = getIfs(storage);
953 if (!ifs) {
954 return {};
955 }
956
957 std::unique_lock l(ifs->lock);
958 auto subdirIt = ifs->storages.find(storage);
959 if (subdirIt == ifs->storages.end()) {
960 return {};
961 }
962 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
963 l.unlock();
964
965 const auto prefixSize = dir.size() + 1;
966 std::vector<std::string> todoDirs{std::move(dir)};
967 std::vector<std::string> result;
968 do {
969 auto currDir = std::move(todoDirs.back());
970 todoDirs.pop_back();
971
972 auto d =
973 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
974 while (auto e = ::readdir(d.get())) {
975 if (e->d_type == DT_REG) {
976 result.emplace_back(
977 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
978 continue;
979 }
980 if (e->d_type == DT_DIR) {
981 if (e->d_name == "."sv || e->d_name == ".."sv) {
982 continue;
983 }
984 todoDirs.emplace_back(path::join(currDir, e->d_name));
985 continue;
986 }
987 }
988 } while (!todoDirs.empty());
989 return result;
990}
991
992bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700993 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700994 {
995 std::unique_lock l(mLock);
996 const auto& ifs = getIfsLocked(storage);
997 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800998 return false;
999 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001000 dataLoaderStub = ifs->dataLoaderStub;
1001 if (!dataLoaderStub) {
1002 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001003 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001004 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001005 return dataLoaderStub->start();
Songchun Fan3c82a302019-11-29 14:23:45 -08001006}
1007
1008void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001009 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1010 const auto path = entry.path().u8string();
1011 const auto name = entry.path().filename().u8string();
1012 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001013 continue;
1014 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001015 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001016 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001017 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001018 }
1019 }
1020}
1021
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001022bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001023 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001024 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001025
Songchun Fan3c82a302019-11-29 14:23:45 -08001026 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001027 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001028 if (!status.isOk()) {
1029 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1030 return false;
1031 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001032
1033 int cmd = controlParcel.cmd.release().release();
1034 int pendingReads = controlParcel.pendingReads.release().release();
1035 int logs = controlParcel.log.release().release();
1036 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001037
1038 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1039
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001040 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1041 path::join(mountTarget, constants().infoMdName));
1042 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001043 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1044 return false;
1045 }
1046
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001047 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001048 mNextId = std::max(mNextId, ifs->mountId + 1);
1049
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001050 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001051 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001052 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001053 const auto& loader = mount.loader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001054 dataLoaderParams.type = (android::content::pm::DataLoaderType)loader.type();
1055 dataLoaderParams.packageName = loader.package_name();
1056 dataLoaderParams.className = loader.class_name();
1057 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001058 }
1059
Songchun Fan3c82a302019-11-29 14:23:45 -08001060 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001061 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 while (auto e = ::readdir(d.get())) {
1063 if (e->d_type == DT_REG) {
1064 auto name = std::string_view(e->d_name);
1065 if (name.starts_with(constants().mountpointMdPrefix)) {
1066 bindPoints.emplace_back(name,
1067 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1068 ifs->control,
1069 path::join(mountTarget,
1070 name)));
1071 if (bindPoints.back().second.dest_path().empty() ||
1072 bindPoints.back().second.source_subdir().empty()) {
1073 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001074 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001075 }
1076 }
1077 } else if (e->d_type == DT_DIR) {
1078 if (e->d_name == "."sv || e->d_name == ".."sv) {
1079 continue;
1080 }
1081 auto name = std::string_view(e->d_name);
1082 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001083 int storageId;
1084 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1085 name.data() + name.size(), storageId);
1086 if (res.ec != std::errc{} || *res.ptr != '_') {
1087 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1088 << root;
1089 continue;
1090 }
1091 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001092 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001093 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001094 << " for mount " << root;
1095 continue;
1096 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001097 ifs->storages.insert_or_assign(storageId,
1098 IncFsMount::Storage{
1099 path::join(root, constants().mount, name)});
1100 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001101 }
1102 }
1103 }
1104
1105 if (ifs->storages.empty()) {
1106 LOG(WARNING) << "No valid storages in mount " << root;
1107 return false;
1108 }
1109
1110 int bindCount = 0;
1111 for (auto&& bp : bindPoints) {
1112 std::unique_lock l(mLock, std::defer_lock);
1113 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1114 std::move(*bp.second.mutable_source_subdir()),
1115 std::move(*bp.second.mutable_dest_path()),
1116 BindKind::Permanent, l);
1117 }
1118
1119 if (bindCount == 0) {
1120 LOG(WARNING) << "No valid bind points for mount " << root;
1121 deleteStorage(*ifs);
1122 return false;
1123 }
1124
Songchun Fan3c82a302019-11-29 14:23:45 -08001125 mMounts[ifs->mountId] = std::move(ifs);
1126 return true;
1127}
1128
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001129IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
1130 IncrementalService::IncFsMount& ifs, DataLoaderParamsParcel&& params,
1131 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001132 std::unique_lock l(ifs.lock);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001133 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001134 LOG(INFO) << "Skipped data loader preparation because it already exists";
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001135 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001136 }
1137
Songchun Fan3c82a302019-11-29 14:23:45 -08001138 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001139 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001140 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001141 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001142 base::unique_fd(::dup(ifs.control.pendingReads())));
1143 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001144 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001145
1146 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1147 std::move(fsControlParcel), externalListener);
1148 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001149}
1150
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001151template <class Duration>
1152static long elapsedMcs(Duration start, Duration end) {
1153 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1154}
1155
1156// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001157bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1158 std::string_view libDirRelativePath,
1159 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001160 namespace sc = std::chrono;
1161 using Clock = sc::steady_clock;
1162 auto start = Clock::now();
1163
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001164 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001165 if (!ifs) {
1166 LOG(ERROR) << "Invalid storage " << storage;
1167 return false;
1168 }
1169
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001170 // First prepare target directories if they don't exist yet
1171 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1172 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1173 << " errno: " << res;
1174 return false;
1175 }
1176
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001177 auto mkDirsTs = Clock::now();
1178
1179 std::unique_ptr<ZipFileRO> zipFile(ZipFileRO::open(path::c_str(apkFullPath)));
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001180 if (!zipFile) {
1181 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1182 return false;
1183 }
1184 void* cookie = nullptr;
1185 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001186 if (!zipFile->startIteration(&cookie, libFilePrefix.c_str() /* prefix */,
1187 constants().libSuffix.data() /* suffix */)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001188 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1189 return false;
1190 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001191 auto endIteration = [&zipFile](void* cookie) { zipFile->endIteration(cookie); };
1192 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1193
1194 auto openZipTs = Clock::now();
1195
1196 std::vector<IncFsDataBlock> instructions;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001197 ZipEntryRO entry = nullptr;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001198 while ((entry = zipFile->nextEntry(cookie)) != nullptr) {
1199 auto startFileTs = Clock::now();
1200
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001201 char fileName[PATH_MAX];
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001202 if (zipFile->getEntryFileName(entry, fileName, sizeof(fileName))) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001203 continue;
1204 }
1205 const auto libName = path::basename(fileName);
1206 const auto targetLibPath = path::join(libDirRelativePath, libName);
1207 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1208 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001209 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1210 if (sEnablePerfLogging) {
1211 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1212 << "; skipping extraction, spent "
1213 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1214 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001215 continue;
1216 }
1217
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001218 uint32_t uncompressedLen, compressedLen;
1219 if (!zipFile->getEntryInfo(entry, nullptr, &uncompressedLen, &compressedLen, nullptr,
1220 nullptr, nullptr)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001221 LOG(ERROR) << "Failed to read native lib entry: " << fileName;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001222 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001223 }
1224
1225 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001226 incfs::NewFileParams libFileParams = {
1227 .size = uncompressedLen,
1228 .signature = {},
1229 // Metadata of the new lib file is its relative path
1230 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1231 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001232 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001233 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1234 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001235 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001236 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001237 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001238 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001239
1240 auto makeFileTs = Clock::now();
1241
Songchun Fanafaf6e92020-03-18 14:12:20 -07001242 // If it is a zero-byte file, skip data writing
1243 if (uncompressedLen == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001244 if (sEnablePerfLogging) {
1245 LOG(INFO) << "incfs: Extracted " << libName << "(" << compressedLen << " -> "
1246 << uncompressedLen << " bytes): " << elapsedMcs(startFileTs, makeFileTs)
1247 << "mcs, make: " << elapsedMcs(startFileTs, makeFileTs);
1248 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001249 continue;
1250 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001251
1252 // Write extracted data to new file
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001253 // NOTE: don't zero-initialize memory, it may take a while
1254 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[uncompressedLen]);
1255 if (!zipFile->uncompressEntry(entry, libData.get(), uncompressedLen)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001256 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
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 extractFileTs = Clock::now();
1261
Yurii Zubrytskyie82cdd72020-04-01 12:19:26 -07001262 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1263 if (!writeFd.ok()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001264 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001265 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001266 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001267
1268 auto openFileTs = Clock::now();
1269
1270 const int numBlocks = (uncompressedLen + constants().blockSize - 1) / constants().blockSize;
1271 instructions.clear();
1272 instructions.reserve(numBlocks);
1273 auto remainingData = std::span(libData.get(), uncompressedLen);
1274 for (int i = 0; i < numBlocks; i++) {
1275 const auto blockSize = std::min<uint16_t>(constants().blockSize, remainingData.size());
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001276 auto inst = IncFsDataBlock{
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001277 .fileFd = writeFd.get(),
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001278 .pageIndex = static_cast<IncFsBlockIndex>(i),
1279 .compression = INCFS_COMPRESSION_KIND_NONE,
1280 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001281 .dataSize = blockSize,
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001282 .data = reinterpret_cast<const char*>(remainingData.data()),
1283 };
1284 instructions.push_back(inst);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001285 remainingData = remainingData.subspan(blockSize);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001286 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001287 auto prepareInstsTs = Clock::now();
1288
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001289 size_t res = mIncFs->writeBlocks(instructions);
1290 if (res != instructions.size()) {
1291 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001292 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001293 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001294
1295 if (sEnablePerfLogging) {
1296 auto endFileTs = Clock::now();
1297 LOG(INFO) << "incfs: Extracted " << libName << "(" << compressedLen << " -> "
1298 << uncompressedLen << " bytes): " << elapsedMcs(startFileTs, endFileTs)
1299 << "mcs, make: " << elapsedMcs(startFileTs, makeFileTs)
1300 << " extract: " << elapsedMcs(makeFileTs, extractFileTs)
1301 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1302 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1303 << " write:" << elapsedMcs(prepareInstsTs, endFileTs);
1304 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001305 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001306
1307 if (sEnablePerfLogging) {
1308 auto end = Clock::now();
1309 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1310 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1311 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
1312 << " extract all: " << elapsedMcs(openZipTs, end);
1313 }
1314
1315 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001316}
1317
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001318void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001319 sp<IAppOpsCallback> listener;
1320 {
1321 std::unique_lock lock{mCallbacksLock};
1322 auto& cb = mCallbackRegistered[packageName];
1323 if (cb) {
1324 return;
1325 }
1326 cb = new AppOpsListener(*this, packageName);
1327 listener = cb;
1328 }
1329
1330 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS, String16(packageName.c_str()), listener);
1331}
1332
1333bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1334 sp<IAppOpsCallback> listener;
1335 {
1336 std::unique_lock lock{mCallbacksLock};
1337 auto found = mCallbackRegistered.find(packageName);
1338 if (found == mCallbackRegistered.end()) {
1339 return false;
1340 }
1341 listener = found->second;
1342 mCallbackRegistered.erase(found);
1343 }
1344
1345 mAppOpsManager->stopWatchingMode(listener);
1346 return true;
1347}
1348
1349void IncrementalService::onAppOpChanged(const std::string& packageName) {
1350 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001351 return;
1352 }
1353
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001354 std::vector<IfsMountPtr> affected;
1355 {
1356 std::lock_guard l(mLock);
1357 affected.reserve(mMounts.size());
1358 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001359 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001360 affected.push_back(ifs);
1361 }
1362 }
1363 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001364 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001365 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001366 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001367}
1368
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001369IncrementalService::DataLoaderStub::~DataLoaderStub() {
1370 CHECK(mStatus == -1 || mStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED)
1371 << "Dataloader has to be destroyed prior to destructor: " << mId
1372 << ", status: " << mStatus;
1373}
1374
1375bool IncrementalService::DataLoaderStub::create() {
1376 bool created = false;
1377 auto status = mService.mDataLoaderManager->initializeDataLoader(mId, mParams, mControl, this,
1378 &created);
1379 if (!status.isOk() || !created) {
1380 LOG(ERROR) << "Failed to create a data loader for mount " << mId;
1381 return false;
1382 }
1383 return true;
1384}
1385
1386bool IncrementalService::DataLoaderStub::start() {
1387 if (mStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
1388 mStartRequested = true;
1389 return true;
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001390 }
1391
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001392 sp<IDataLoader> dataloader;
1393 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1394 if (!status.isOk()) {
1395 return false;
1396 }
1397 if (!dataloader) {
1398 return false;
1399 }
1400 status = dataloader->start(mId);
1401 if (!status.isOk()) {
1402 return false;
1403 }
1404 return true;
1405}
1406
1407void IncrementalService::DataLoaderStub::destroy() {
1408 mDestroyRequested = true;
1409 mService.mDataLoaderManager->destroyDataLoader(mId);
1410}
1411
1412binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
1413 if (mStatus == newStatus) {
1414 return binder::Status::ok();
1415 }
1416
1417 if (mListener) {
1418 // Give an external listener a chance to act before we destroy something.
1419 mListener->onStatusChanged(mountId, newStatus);
1420 }
1421
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001422 {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001423 std::unique_lock l(mService.mLock);
1424 const auto& ifs = mService.getIfsLocked(mountId);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001425 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001426 LOG(WARNING) << "Received data loader status " << int(newStatus)
1427 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001428 return binder::Status::ok();
1429 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001430 mStatus = newStatus;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001431
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001432 if (!mDestroyRequested && newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1433 mService.deleteStorageLocked(*ifs, std::move(l));
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001434 return binder::Status::ok();
1435 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001436 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001437
Songchun Fan3c82a302019-11-29 14:23:45 -08001438 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001439 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001440 if (mStartRequested) {
1441 start();
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001442 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001443 break;
1444 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001445 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001446 break;
1447 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001448 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001449 break;
1450 }
1451 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1452 break;
1453 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001454 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1455 break;
1456 }
1457 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1458 break;
1459 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001460 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1461 // Nothing for now. Rely on externalListener to handle this.
1462 break;
1463 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001464 default: {
1465 LOG(WARNING) << "Unknown data loader status: " << newStatus
1466 << " for mount: " << mountId;
1467 break;
1468 }
1469 }
1470
1471 return binder::Status::ok();
1472}
1473
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001474void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1475 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001476}
1477
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001478binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1479 bool enableReadLogs, int32_t* _aidl_return) {
1480 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1481 return binder::Status::ok();
1482}
1483
Songchun Fan3c82a302019-11-29 14:23:45 -08001484} // namespace android::incremental