blob: f7cc8f5f014154c17c576577fe692b6e951fc7b9 [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "IncrementalService"
18
19#include "IncrementalService.h"
20
21#include <android-base/file.h>
22#include <android-base/logging.h>
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -070023#include <android-base/no_destructor.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080024#include <android-base/properties.h>
25#include <android-base/stringprintf.h>
26#include <android-base/strings.h>
27#include <android/content/pm/IDataLoaderStatusListener.h>
28#include <android/os/IVold.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080029#include <binder/BinderService.h>
Jooyung Han66c567a2020-03-07 21:47:09 +090030#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080031#include <binder/ParcelFileDescriptor.h>
32#include <binder/Status.h>
33#include <sys/stat.h>
34#include <uuid/uuid.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080035
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070036#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080037#include <ctime>
Songchun Fan1124fd32020-02-10 12:49:41 -080038#include <filesystem>
Songchun Fan3c82a302019-11-29 14:23:45 -080039#include <iterator>
40#include <span>
Songchun Fan3c82a302019-11-29 14:23:45 -080041#include <type_traits>
42
43#include "Metadata.pb.h"
44
45using namespace std::literals;
46using namespace android::content::pm;
Songchun Fan1124fd32020-02-10 12:49:41 -080047namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080048
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070049constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070050constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070051
Songchun Fan3c82a302019-11-29 14:23:45 -080052namespace android::incremental {
53
54namespace {
55
56using IncrementalFileSystemControlParcel =
57 ::android::os::incremental::IncrementalFileSystemControlParcel;
58
59struct Constants {
60 static constexpr auto backing = "backing_store"sv;
61 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080062 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080063 static constexpr auto storagePrefix = "st"sv;
64 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
65 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080066 static constexpr auto libDir = "lib"sv;
67 static constexpr auto libSuffix = ".so"sv;
68 static constexpr auto blockSize = 4096;
Songchun Fan3c82a302019-11-29 14:23:45 -080069};
70
71static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070072 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080073 return c;
74}
75
76template <base::LogSeverity level = base::ERROR>
77bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
78 auto cstr = path::c_str(name);
79 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080080 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080081 PLOG(level) << "Can't create directory '" << name << '\'';
82 return false;
83 }
84 struct stat st;
85 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
86 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
87 return false;
88 }
89 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080090 if (::chmod(cstr, mode)) {
91 PLOG(level) << "Changing permission failed for '" << name << '\'';
92 return false;
93 }
94
Songchun Fan3c82a302019-11-29 14:23:45 -080095 return true;
96}
97
98static std::string toMountKey(std::string_view path) {
99 if (path.empty()) {
100 return "@none";
101 }
102 if (path == "/"sv) {
103 return "@root";
104 }
105 if (path::isAbsolute(path)) {
106 path.remove_prefix(1);
107 }
108 std::string res(path);
109 std::replace(res.begin(), res.end(), '/', '_');
110 std::replace(res.begin(), res.end(), '@', '_');
Songchun Fan1124fd32020-02-10 12:49:41 -0800111 return std::string(constants().mountKeyPrefix) + res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800112}
113
114static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
115 std::string_view path) {
116 auto mountKey = toMountKey(path);
117 const auto prefixSize = mountKey.size();
118 for (int counter = 0; counter < 1000;
119 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
120 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800121 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800122 return {mountKey, mountRoot};
123 }
124 }
125 return {};
126}
127
128template <class ProtoMessage, class Control>
129static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
130 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800131 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800132 ProtoMessage message;
133 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
134}
135
136static bool isValidMountTarget(std::string_view path) {
137 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
138}
139
140std::string makeBindMdName() {
141 static constexpr auto uuidStringSize = 36;
142
143 uuid_t guid;
144 uuid_generate(guid);
145
146 std::string name;
147 const auto prefixSize = constants().mountpointMdPrefix.size();
148 name.reserve(prefixSize + uuidStringSize);
149
150 name = constants().mountpointMdPrefix;
151 name.resize(prefixSize + uuidStringSize);
152 uuid_unparse(guid, name.data() + prefixSize);
153
154 return name;
155}
156} // namespace
157
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700158const bool IncrementalService::sEnablePerfLogging =
159 android::base::GetBoolProperty("incremental.perflogging", false);
160
Songchun Fan3c82a302019-11-29 14:23:45 -0800161IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700162 if (dataLoaderStub) {
163 dataLoaderStub->destroy();
164 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800165 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
166 for (auto&& [target, _] : bindPoints) {
167 LOG(INFO) << "\tbind: " << target;
168 incrementalService.mVold->unmountIncFs(target);
169 }
170 LOG(INFO) << "\troot: " << root;
171 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
172 cleanupFilesystem(root);
173}
174
175auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800176 std::string name;
177 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
178 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
179 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800180 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
181 constants().storagePrefix.data(), id, no);
182 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800183 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800184 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800185 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
186 } else if (err != EEXIST) {
187 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
188 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800189 }
190 }
191 nextStorageDirNo = 0;
192 return storages.end();
193}
194
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800195static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
196 return {::opendir(path), ::closedir};
197}
198
199static int rmDirContent(const char* path) {
200 auto dir = openDir(path);
201 if (!dir) {
202 return -EINVAL;
203 }
204 while (auto entry = ::readdir(dir.get())) {
205 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
206 continue;
207 }
208 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
209 if (entry->d_type == DT_DIR) {
210 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
211 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
212 return err;
213 }
214 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
215 PLOG(WARNING) << "Failed to rmdir " << fullPath;
216 return err;
217 }
218 } else {
219 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
220 PLOG(WARNING) << "Failed to delete " << fullPath;
221 return err;
222 }
223 }
224 }
225 return 0;
226}
227
Songchun Fan3c82a302019-11-29 14:23:45 -0800228void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800229 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800230 ::rmdir(path::join(root, constants().backing).c_str());
231 ::rmdir(path::join(root, constants().mount).c_str());
232 ::rmdir(path::c_str(root));
233}
234
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800235IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800236 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800237 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800238 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700239 mAppOpsManager(sm.getAppOpsManager()),
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700240 mJni(sm.getJni()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800241 mIncrementalDir(rootDir) {
242 if (!mVold) {
243 LOG(FATAL) << "Vold service is unavailable";
244 }
Songchun Fan68645c42020-02-27 15:57:35 -0800245 if (!mDataLoaderManager) {
246 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800247 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700248 if (!mAppOpsManager) {
249 LOG(FATAL) << "AppOpsManager is unavailable";
250 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700251
252 mJobQueue.reserve(16);
Yurii Zubrytskyi86321402020-04-09 19:22:30 -0700253 mJobProcessor = std::thread([this]() {
254 mJni->initializeForCurrentThread();
255 runJobProcessing();
256 });
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700257
Songchun Fan1124fd32020-02-10 12:49:41 -0800258 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800259}
260
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800261FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800262 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800263}
264
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700265IncrementalService::~IncrementalService() {
266 {
267 std::lock_guard lock(mJobMutex);
268 mRunning = false;
269 }
270 mJobCondition.notify_all();
271 mJobProcessor.join();
272}
Songchun Fan3c82a302019-11-29 14:23:45 -0800273
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800274inline const char* toString(TimePoint t) {
275 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800276 time_t time = SystemClock::to_time_t(
277 SystemClock::now() +
278 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800279 return std::ctime(&time);
280}
281
282inline const char* toString(IncrementalService::BindKind kind) {
283 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800284 case IncrementalService::BindKind::Temporary:
285 return "Temporary";
286 case IncrementalService::BindKind::Permanent:
287 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800288 }
289}
290
291void IncrementalService::onDump(int fd) {
292 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
293 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
294
295 std::unique_lock l(mLock);
296
297 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
298 for (auto&& [id, ifs] : mMounts) {
299 const IncFsMount& mnt = *ifs.get();
300 dprintf(fd, "\t[%d]:\n", id);
301 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700302 dprintf(fd, "\t\troot: %s\n", mnt.root.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800303 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700304 if (mnt.dataLoaderStub) {
305 const auto& dataLoaderStub = *mnt.dataLoaderStub;
306 dprintf(fd, "\t\tdataLoaderStatus: %d\n", dataLoaderStub.status());
307 dprintf(fd, "\t\tdataLoaderStartRequested: %s\n",
308 dataLoaderStub.startRequested() ? "true" : "false");
309 const auto& params = dataLoaderStub.params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700310 dprintf(fd, "\t\tdataLoaderParams:\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800311 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
312 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
313 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
314 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800315 }
316 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
317 for (auto&& [storageId, storage] : mnt.storages) {
318 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
319 }
320
321 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
322 for (auto&& [target, bind] : mnt.bindPoints) {
323 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
324 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
325 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
326 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
327 }
328 }
329
330 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
331 for (auto&& [target, mountPairIt] : mBindsByPath) {
332 const auto& bind = mountPairIt->second;
333 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
334 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
335 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
336 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
337 }
338}
339
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700340void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800341 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700342 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800343 }
344
345 std::vector<IfsMountPtr> mounts;
346 {
347 std::lock_guard l(mLock);
348 mounts.reserve(mMounts.size());
349 for (auto&& [id, ifs] : mMounts) {
350 if (ifs->mountId == id) {
351 mounts.push_back(ifs);
352 }
353 }
354 }
355
Alex Buynytskyy69941662020-04-11 21:40:37 -0700356 if (mounts.empty()) {
357 return;
358 }
359
Songchun Fan3c82a302019-11-29 14:23:45 -0800360 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700361 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800362 for (auto&& ifs : mounts) {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700363 if (ifs->dataLoaderStub->create()) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800364 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
365 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800366 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800367 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800368 }
369 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800370 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800371}
372
373auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
374 for (;;) {
375 if (mNextId == kMaxStorageId) {
376 mNextId = 0;
377 }
378 auto id = ++mNextId;
379 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
380 if (inserted) {
381 return it;
382 }
383 }
384}
385
Songchun Fan1124fd32020-02-10 12:49:41 -0800386StorageId IncrementalService::createStorage(
387 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
388 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800389 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
390 if (!path::isAbsolute(mountPoint)) {
391 LOG(ERROR) << "path is not absolute: " << mountPoint;
392 return kInvalidStorageId;
393 }
394
395 auto mountNorm = path::normalize(mountPoint);
396 {
397 const auto id = findStorageId(mountNorm);
398 if (id != kInvalidStorageId) {
399 if (options & CreateOptions::OpenExisting) {
400 LOG(INFO) << "Opened existing storage " << id;
401 return id;
402 }
403 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
404 return kInvalidStorageId;
405 }
406 }
407
408 if (!(options & CreateOptions::CreateNew)) {
409 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
410 return kInvalidStorageId;
411 }
412
413 if (!path::isEmptyDir(mountNorm)) {
414 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
415 return kInvalidStorageId;
416 }
417 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
418 if (mountRoot.empty()) {
419 LOG(ERROR) << "Bad mount point";
420 return kInvalidStorageId;
421 }
422 // Make sure the code removes all crap it may create while still failing.
423 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
424 auto firstCleanupOnFailure =
425 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
426
427 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800428 const auto backing = path::join(mountRoot, constants().backing);
429 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800430 return kInvalidStorageId;
431 }
432
Songchun Fan3c82a302019-11-29 14:23:45 -0800433 IncFsMount::Control control;
434 {
435 std::lock_guard l(mMountOperationLock);
436 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800437
438 if (auto err = rmDirContent(backing.c_str())) {
439 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
440 return kInvalidStorageId;
441 }
442 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
443 return kInvalidStorageId;
444 }
445 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800446 if (!status.isOk()) {
447 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
448 return kInvalidStorageId;
449 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800450 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
451 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800452 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
453 return kInvalidStorageId;
454 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800455 int cmd = controlParcel.cmd.release().release();
456 int pendingReads = controlParcel.pendingReads.release().release();
457 int logs = controlParcel.log.release().release();
458 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800459 }
460
461 std::unique_lock l(mLock);
462 const auto mountIt = getStorageSlotLocked();
463 const auto mountId = mountIt->first;
464 l.unlock();
465
466 auto ifs =
467 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
468 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
469 // is the removal of the |ifs|.
470 firstCleanupOnFailure.release();
471
472 auto secondCleanup = [this, &l](auto itPtr) {
473 if (!l.owns_lock()) {
474 l.lock();
475 }
476 mMounts.erase(*itPtr);
477 };
478 auto secondCleanupOnFailure =
479 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
480
481 const auto storageIt = ifs->makeStorage(ifs->mountId);
482 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800483 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800484 return kInvalidStorageId;
485 }
486
487 {
488 metadata::Mount m;
489 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700490 m.mutable_loader()->set_type((int)dataLoaderParams.type);
491 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
492 m.mutable_loader()->set_class_name(dataLoaderParams.className);
493 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800494 const auto metadata = m.SerializeAsString();
495 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800496 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800497 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800498 if (auto err =
499 mIncFs->makeFile(ifs->control,
500 path::join(ifs->root, constants().mount,
501 constants().infoMdName),
502 0777, idFromMetadata(metadata),
503 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800504 LOG(ERROR) << "Saving mount metadata failed: " << -err;
505 return kInvalidStorageId;
506 }
507 }
508
509 const auto bk =
510 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800511 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
512 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800513 err < 0) {
514 LOG(ERROR) << "adding bind mount failed: " << -err;
515 return kInvalidStorageId;
516 }
517
518 // Done here as well, all data structures are in good state.
519 secondCleanupOnFailure.release();
520
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700521 auto dataLoaderStub =
522 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
523 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800524
525 mountIt->second = std::move(ifs);
526 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700527
528 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->create()) {
529 // failed to create data loader
530 LOG(ERROR) << "initializeDataLoader() failed";
531 deleteStorage(dataLoaderStub->id());
532 return kInvalidStorageId;
533 }
534
Songchun Fan3c82a302019-11-29 14:23:45 -0800535 LOG(INFO) << "created storage " << mountId;
536 return mountId;
537}
538
539StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
540 StorageId linkedStorage,
541 IncrementalService::CreateOptions options) {
542 if (!isValidMountTarget(mountPoint)) {
543 LOG(ERROR) << "Mount point is invalid or missing";
544 return kInvalidStorageId;
545 }
546
547 std::unique_lock l(mLock);
548 const auto& ifs = getIfsLocked(linkedStorage);
549 if (!ifs) {
550 LOG(ERROR) << "Ifs unavailable";
551 return kInvalidStorageId;
552 }
553
554 const auto mountIt = getStorageSlotLocked();
555 const auto storageId = mountIt->first;
556 const auto storageIt = ifs->makeStorage(storageId);
557 if (storageIt == ifs->storages.end()) {
558 LOG(ERROR) << "Can't create a new storage";
559 mMounts.erase(mountIt);
560 return kInvalidStorageId;
561 }
562
563 l.unlock();
564
565 const auto bk =
566 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800567 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
568 std::string(storageIt->second.name), path::normalize(mountPoint),
569 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800570 err < 0) {
571 LOG(ERROR) << "bindMount failed with error: " << err;
572 return kInvalidStorageId;
573 }
574
575 mountIt->second = ifs;
576 return storageId;
577}
578
579IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
580 std::string_view path) const {
581 auto bindPointIt = mBindsByPath.upper_bound(path);
582 if (bindPointIt == mBindsByPath.begin()) {
583 return mBindsByPath.end();
584 }
585 --bindPointIt;
586 if (!path::startsWith(path, bindPointIt->first)) {
587 return mBindsByPath.end();
588 }
589 return bindPointIt;
590}
591
592StorageId IncrementalService::findStorageId(std::string_view path) const {
593 std::lock_guard l(mLock);
594 auto it = findStorageLocked(path);
595 if (it == mBindsByPath.end()) {
596 return kInvalidStorageId;
597 }
598 return it->second->second.storage;
599}
600
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700601int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
602 const auto ifs = getIfs(storageId);
603 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700604 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700605 return -EINVAL;
606 }
607
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700608 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700609 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700610 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
611 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700612 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700613 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700614 return fromBinderStatus(status);
615 }
616 }
617
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700618 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
619 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
620 return fromBinderStatus(status);
621 }
622
623 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700624 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700625 }
626
627 return 0;
628}
629
630binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700631 using unique_fd = ::android::base::unique_fd;
632 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700633 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
634 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
635 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700636 if (logsFd >= 0) {
637 control.log.reset(unique_fd(dup(logsFd)));
638 }
639
640 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700641 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700642}
643
Songchun Fan3c82a302019-11-29 14:23:45 -0800644void IncrementalService::deleteStorage(StorageId storageId) {
645 const auto ifs = getIfs(storageId);
646 if (!ifs) {
647 return;
648 }
649 deleteStorage(*ifs);
650}
651
652void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
653 std::unique_lock l(ifs.lock);
654 deleteStorageLocked(ifs, std::move(l));
655}
656
657void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
658 std::unique_lock<std::mutex>&& ifsLock) {
659 const auto storages = std::move(ifs.storages);
660 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
661 const auto bindPoints = ifs.bindPoints;
662 ifsLock.unlock();
663
664 std::lock_guard l(mLock);
665 for (auto&& [id, _] : storages) {
666 if (id != ifs.mountId) {
667 mMounts.erase(id);
668 }
669 }
670 for (auto&& [path, _] : bindPoints) {
671 mBindsByPath.erase(path);
672 }
673 mMounts.erase(ifs.mountId);
674}
675
676StorageId IncrementalService::openStorage(std::string_view pathInMount) {
677 if (!path::isAbsolute(pathInMount)) {
678 return kInvalidStorageId;
679 }
680
681 return findStorageId(path::normalize(pathInMount));
682}
683
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800684FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800685 const auto ifs = getIfs(storage);
686 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800687 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800688 }
689 std::unique_lock l(ifs->lock);
690 auto storageIt = ifs->storages.find(storage);
691 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800692 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800693 }
694 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800695 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800696 }
697 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
698 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800699 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800700}
701
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800702std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800703 StorageId storage, std::string_view subpath) const {
704 auto name = path::basename(subpath);
705 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800706 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800707 }
708 auto dir = path::dirname(subpath);
709 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800710 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800711 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800712 auto id = nodeFor(storage, dir);
713 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800714}
715
716IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
717 std::lock_guard l(mLock);
718 return getIfsLocked(storage);
719}
720
721const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
722 auto it = mMounts.find(storage);
723 if (it == mMounts.end()) {
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700724 static const android::base::NoDestructor<IfsMountPtr> kEmpty{};
725 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800726 }
727 return it->second;
728}
729
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800730int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
731 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800732 if (!isValidMountTarget(target)) {
733 return -EINVAL;
734 }
735
736 const auto ifs = getIfs(storage);
737 if (!ifs) {
738 return -EINVAL;
739 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800740
Songchun Fan3c82a302019-11-29 14:23:45 -0800741 std::unique_lock l(ifs->lock);
742 const auto storageInfo = ifs->storages.find(storage);
743 if (storageInfo == ifs->storages.end()) {
744 return -EINVAL;
745 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700746 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
747 if (normSource.empty()) {
748 return -EINVAL;
749 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800750 l.unlock();
751 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800752 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
753 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800754}
755
756int IncrementalService::unbind(StorageId storage, std::string_view target) {
757 if (!path::isAbsolute(target)) {
758 return -EINVAL;
759 }
760
761 LOG(INFO) << "Removing bind point " << target;
762
763 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
764 // otherwise there's a chance to unmount something completely unrelated
765 const auto norm = path::normalize(target);
766 std::unique_lock l(mLock);
767 const auto storageIt = mBindsByPath.find(norm);
768 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
769 return -EINVAL;
770 }
771 const auto bindIt = storageIt->second;
772 const auto storageId = bindIt->second.storage;
773 const auto ifs = getIfsLocked(storageId);
774 if (!ifs) {
775 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
776 << " is missing";
777 return -EFAULT;
778 }
779 mBindsByPath.erase(storageIt);
780 l.unlock();
781
782 mVold->unmountIncFs(bindIt->first);
783 std::unique_lock l2(ifs->lock);
784 if (ifs->bindPoints.size() <= 1) {
785 ifs->bindPoints.clear();
786 deleteStorageLocked(*ifs, std::move(l2));
787 } else {
788 const std::string savedFile = std::move(bindIt->second.savedFilename);
789 ifs->bindPoints.erase(bindIt);
790 l2.unlock();
791 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800792 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800793 }
794 }
795 return 0;
796}
797
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700798std::string IncrementalService::normalizePathToStorageLocked(
799 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
800 std::string normPath;
801 if (path::isAbsolute(path)) {
802 normPath = path::normalize(path);
803 if (!path::startsWith(normPath, storageIt->second.name)) {
804 return {};
805 }
806 } else {
807 normPath = path::normalize(path::join(storageIt->second.name, path));
808 }
809 return normPath;
810}
811
812std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800813 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700814 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800815 const auto storageInfo = ifs->storages.find(storage);
816 if (storageInfo == ifs->storages.end()) {
817 return {};
818 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700819 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800820}
821
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800822int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
823 incfs::NewFileParams params) {
824 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800825 std::string normPath = normalizePathToStorage(ifs, storage, path);
826 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700827 LOG(ERROR) << "Internal error: storageId " << storage
828 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800829 return -EINVAL;
830 }
831 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800832 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700833 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800834 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800835 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800836 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800837 }
838 return -EINVAL;
839}
840
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800841int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800842 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800843 std::string normPath = normalizePathToStorage(ifs, storageId, path);
844 if (normPath.empty()) {
845 return -EINVAL;
846 }
847 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800848 }
849 return -EINVAL;
850}
851
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800852int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800853 const auto ifs = getIfs(storageId);
854 if (!ifs) {
855 return -EINVAL;
856 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800857 std::string normPath = normalizePathToStorage(ifs, storageId, path);
858 if (normPath.empty()) {
859 return -EINVAL;
860 }
861 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800862 if (err == -EEXIST) {
863 return 0;
864 } else if (err != -ENOENT) {
865 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800866 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800867 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800868 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800869 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800870 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800871}
872
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800873int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
874 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700875 auto ifsSrc = getIfs(sourceStorageId);
876 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
877 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800878 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
879 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
880 if (normOldPath.empty() || normNewPath.empty()) {
881 return -EINVAL;
882 }
883 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800884 }
885 return -EINVAL;
886}
887
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800888int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800889 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800890 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
891 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800892 }
893 return -EINVAL;
894}
895
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800896int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
897 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800898 std::string&& target, BindKind kind,
899 std::unique_lock<std::mutex>& mainLock) {
900 if (!isValidMountTarget(target)) {
901 return -EINVAL;
902 }
903
904 std::string mdFileName;
905 if (kind != BindKind::Temporary) {
906 metadata::BindPoint bp;
907 bp.set_storage_id(storage);
908 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800909 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800911 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800912 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800913 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800914 auto node =
915 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
916 0444, idFromMetadata(metadata),
917 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
918 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800919 return int(node);
920 }
921 }
922
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800923 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800924 std::move(target), kind, mainLock);
925}
926
927int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800928 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800929 std::string&& target, BindKind kind,
930 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800931 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800932 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800933 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800934 if (!status.isOk()) {
935 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
936 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
937 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
938 : status.serviceSpecificErrorCode() == 0
939 ? -EFAULT
940 : status.serviceSpecificErrorCode()
941 : -EIO;
942 }
943 }
944
945 if (!mainLock.owns_lock()) {
946 mainLock.lock();
947 }
948 std::lock_guard l(ifs.lock);
949 const auto [it, _] =
950 ifs.bindPoints.insert_or_assign(target,
951 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800952 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800953 mBindsByPath[std::move(target)] = it;
954 return 0;
955}
956
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800957RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800958 const auto ifs = getIfs(storage);
959 if (!ifs) {
960 return {};
961 }
962 return mIncFs->getMetadata(ifs->control, node);
963}
964
965std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
966 const auto ifs = getIfs(storage);
967 if (!ifs) {
968 return {};
969 }
970
971 std::unique_lock l(ifs->lock);
972 auto subdirIt = ifs->storages.find(storage);
973 if (subdirIt == ifs->storages.end()) {
974 return {};
975 }
976 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
977 l.unlock();
978
979 const auto prefixSize = dir.size() + 1;
980 std::vector<std::string> todoDirs{std::move(dir)};
981 std::vector<std::string> result;
982 do {
983 auto currDir = std::move(todoDirs.back());
984 todoDirs.pop_back();
985
986 auto d =
987 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
988 while (auto e = ::readdir(d.get())) {
989 if (e->d_type == DT_REG) {
990 result.emplace_back(
991 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
992 continue;
993 }
994 if (e->d_type == DT_DIR) {
995 if (e->d_name == "."sv || e->d_name == ".."sv) {
996 continue;
997 }
998 todoDirs.emplace_back(path::join(currDir, e->d_name));
999 continue;
1000 }
1001 }
1002 } while (!todoDirs.empty());
1003 return result;
1004}
1005
1006bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001007 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001008 {
1009 std::unique_lock l(mLock);
1010 const auto& ifs = getIfsLocked(storage);
1011 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001012 return false;
1013 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001014 dataLoaderStub = ifs->dataLoaderStub;
1015 if (!dataLoaderStub) {
1016 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001017 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001018 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001019 return dataLoaderStub->start();
Songchun Fan3c82a302019-11-29 14:23:45 -08001020}
1021
1022void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001023 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1024 const auto path = entry.path().u8string();
1025 const auto name = entry.path().filename().u8string();
1026 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001027 continue;
1028 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001029 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001030 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001031 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001032 }
1033 }
1034}
1035
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001036bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001037 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001038 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001039
Songchun Fan3c82a302019-11-29 14:23:45 -08001040 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001041 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001042 if (!status.isOk()) {
1043 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1044 return false;
1045 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001046
1047 int cmd = controlParcel.cmd.release().release();
1048 int pendingReads = controlParcel.pendingReads.release().release();
1049 int logs = controlParcel.log.release().release();
1050 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001051
1052 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1053
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001054 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1055 path::join(mountTarget, constants().infoMdName));
1056 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001057 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1058 return false;
1059 }
1060
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001061 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 mNextId = std::max(mNextId, ifs->mountId + 1);
1063
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001064 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001065 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001066 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001067 const auto& loader = mount.loader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001068 dataLoaderParams.type = (android::content::pm::DataLoaderType)loader.type();
1069 dataLoaderParams.packageName = loader.package_name();
1070 dataLoaderParams.className = loader.class_name();
1071 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001072 }
1073
Alex Buynytskyy69941662020-04-11 21:40:37 -07001074 prepareDataLoader(*ifs, std::move(dataLoaderParams), nullptr);
1075 CHECK(ifs->dataLoaderStub);
1076
Songchun Fan3c82a302019-11-29 14:23:45 -08001077 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001078 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001079 while (auto e = ::readdir(d.get())) {
1080 if (e->d_type == DT_REG) {
1081 auto name = std::string_view(e->d_name);
1082 if (name.starts_with(constants().mountpointMdPrefix)) {
1083 bindPoints.emplace_back(name,
1084 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1085 ifs->control,
1086 path::join(mountTarget,
1087 name)));
1088 if (bindPoints.back().second.dest_path().empty() ||
1089 bindPoints.back().second.source_subdir().empty()) {
1090 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001091 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001092 }
1093 }
1094 } else if (e->d_type == DT_DIR) {
1095 if (e->d_name == "."sv || e->d_name == ".."sv) {
1096 continue;
1097 }
1098 auto name = std::string_view(e->d_name);
1099 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001100 int storageId;
1101 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1102 name.data() + name.size(), storageId);
1103 if (res.ec != std::errc{} || *res.ptr != '_') {
1104 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1105 << root;
1106 continue;
1107 }
1108 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001109 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001110 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001111 << " for mount " << root;
1112 continue;
1113 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001114 ifs->storages.insert_or_assign(storageId,
1115 IncFsMount::Storage{
1116 path::join(root, constants().mount, name)});
1117 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001118 }
1119 }
1120 }
1121
1122 if (ifs->storages.empty()) {
1123 LOG(WARNING) << "No valid storages in mount " << root;
1124 return false;
1125 }
1126
1127 int bindCount = 0;
1128 for (auto&& bp : bindPoints) {
1129 std::unique_lock l(mLock, std::defer_lock);
1130 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1131 std::move(*bp.second.mutable_source_subdir()),
1132 std::move(*bp.second.mutable_dest_path()),
1133 BindKind::Permanent, l);
1134 }
1135
1136 if (bindCount == 0) {
1137 LOG(WARNING) << "No valid bind points for mount " << root;
1138 deleteStorage(*ifs);
1139 return false;
1140 }
1141
Songchun Fan3c82a302019-11-29 14:23:45 -08001142 mMounts[ifs->mountId] = std::move(ifs);
1143 return true;
1144}
1145
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001146IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
1147 IncrementalService::IncFsMount& ifs, DataLoaderParamsParcel&& params,
1148 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001149 std::unique_lock l(ifs.lock);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001150 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001151 LOG(INFO) << "Skipped data loader preparation because it already exists";
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001152 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001153 }
1154
Songchun Fan3c82a302019-11-29 14:23:45 -08001155 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001156 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001157 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001158 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001159 base::unique_fd(::dup(ifs.control.pendingReads())));
1160 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001161 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001162
1163 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1164 std::move(fsControlParcel), externalListener);
1165 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001166}
1167
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001168template <class Duration>
1169static long elapsedMcs(Duration start, Duration end) {
1170 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1171}
1172
1173// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001174bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1175 std::string_view libDirRelativePath,
1176 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001177 auto start = Clock::now();
1178
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001179 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001180 if (!ifs) {
1181 LOG(ERROR) << "Invalid storage " << storage;
1182 return false;
1183 }
1184
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001185 // First prepare target directories if they don't exist yet
1186 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1187 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1188 << " errno: " << res;
1189 return false;
1190 }
1191
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001192 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001193 ZipArchiveHandle zipFileHandle;
1194 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001195 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1196 return false;
1197 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001198
1199 // Need a shared pointer: will be passing it into all unpacking jobs.
1200 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001201 void* cookie = nullptr;
1202 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001203 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001204 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1205 return false;
1206 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001207 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001208 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1209
1210 auto openZipTs = Clock::now();
1211
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001212 std::vector<Job> jobQueue;
1213 ZipEntry entry;
1214 std::string_view fileName;
1215 while (!Next(cookie, &entry, &fileName)) {
1216 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001217 continue;
1218 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001219
1220 auto startFileTs = Clock::now();
1221
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001222 const auto libName = path::basename(fileName);
1223 const auto targetLibPath = path::join(libDirRelativePath, libName);
1224 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1225 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001226 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1227 if (sEnablePerfLogging) {
1228 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1229 << "; skipping extraction, spent "
1230 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1231 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001232 continue;
1233 }
1234
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001235 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001236 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001237 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001238 .signature = {},
1239 // Metadata of the new lib file is its relative path
1240 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1241 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001242 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001243 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1244 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001245 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001246 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001247 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001248 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001249
1250 auto makeFileTs = Clock::now();
1251
Songchun Fanafaf6e92020-03-18 14:12:20 -07001252 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001253 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001254 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001255 LOG(INFO) << "incfs: Extracted " << libName
1256 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001257 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001258 continue;
1259 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001260
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001261 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1262 libFileId, libPath = std::move(targetLibPath),
1263 makeFileTs]() mutable {
1264 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001265 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001266
1267 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001268 auto prepareJobTs = Clock::now();
1269 LOG(INFO) << "incfs: Processed " << libName << ": "
1270 << elapsedMcs(startFileTs, prepareJobTs)
1271 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1272 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001273 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001274 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001275
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001276 auto processedTs = Clock::now();
1277
1278 if (!jobQueue.empty()) {
1279 {
1280 std::lock_guard lock(mJobMutex);
1281 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001282 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001283 if (existingJobs.empty()) {
1284 existingJobs = std::move(jobQueue);
1285 } else {
1286 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1287 std::move_iterator(jobQueue.end()));
1288 }
1289 }
1290 }
1291 mJobCondition.notify_all();
1292 }
1293
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001294 if (sEnablePerfLogging) {
1295 auto end = Clock::now();
1296 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1297 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1298 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001299 << " make files: " << elapsedMcs(openZipTs, processedTs)
1300 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001301 }
1302
1303 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001304}
1305
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001306void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1307 ZipEntry& entry, const incfs::FileId& libFileId,
1308 std::string_view targetLibPath,
1309 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001310 if (!ifs) {
1311 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1312 return;
1313 }
1314
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001315 auto libName = path::basename(targetLibPath);
1316 auto startedTs = Clock::now();
1317
1318 // Write extracted data to new file
1319 // NOTE: don't zero-initialize memory, it may take a while for nothing
1320 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1321 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1322 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1323 return;
1324 }
1325
1326 auto extractFileTs = Clock::now();
1327
1328 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1329 if (!writeFd.ok()) {
1330 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1331 return;
1332 }
1333
1334 auto openFileTs = Clock::now();
1335 const int numBlocks =
1336 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1337 std::vector<IncFsDataBlock> instructions(numBlocks);
1338 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1339 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001340 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001341 instructions[i] = IncFsDataBlock{
1342 .fileFd = writeFd.get(),
1343 .pageIndex = static_cast<IncFsBlockIndex>(i),
1344 .compression = INCFS_COMPRESSION_KIND_NONE,
1345 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001346 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001347 .data = reinterpret_cast<const char*>(remainingData.data()),
1348 };
1349 remainingData = remainingData.subspan(blockSize);
1350 }
1351 auto prepareInstsTs = Clock::now();
1352
1353 size_t res = mIncFs->writeBlocks(instructions);
1354 if (res != instructions.size()) {
1355 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1356 return;
1357 }
1358
1359 if (sEnablePerfLogging) {
1360 auto endFileTs = Clock::now();
1361 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1362 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1363 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1364 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1365 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1366 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1367 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1368 }
1369}
1370
1371bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001372 struct WaitPrinter {
1373 const Clock::time_point startTs = Clock::now();
1374 ~WaitPrinter() noexcept {
1375 if (sEnablePerfLogging) {
1376 const auto endTs = Clock::now();
1377 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1378 << elapsedMcs(startTs, endTs) << "mcs";
1379 }
1380 }
1381 } waitPrinter;
1382
1383 MountId mount;
1384 {
1385 auto ifs = getIfs(storage);
1386 if (!ifs) {
1387 return true;
1388 }
1389 mount = ifs->mountId;
1390 }
1391
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001392 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001393 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001394 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001395 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001396 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001397 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001398}
1399
1400void IncrementalService::runJobProcessing() {
1401 for (;;) {
1402 std::unique_lock lock(mJobMutex);
1403 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1404 if (!mRunning) {
1405 return;
1406 }
1407
1408 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001409 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001410 auto queue = std::move(it->second);
1411 mJobQueue.erase(it);
1412 lock.unlock();
1413
1414 for (auto&& job : queue) {
1415 job();
1416 }
1417
1418 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001419 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001420 lock.unlock();
1421 mJobCondition.notify_all();
1422 }
1423}
1424
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001425void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001426 sp<IAppOpsCallback> listener;
1427 {
1428 std::unique_lock lock{mCallbacksLock};
1429 auto& cb = mCallbackRegistered[packageName];
1430 if (cb) {
1431 return;
1432 }
1433 cb = new AppOpsListener(*this, packageName);
1434 listener = cb;
1435 }
1436
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001437 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1438 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001439}
1440
1441bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1442 sp<IAppOpsCallback> listener;
1443 {
1444 std::unique_lock lock{mCallbacksLock};
1445 auto found = mCallbackRegistered.find(packageName);
1446 if (found == mCallbackRegistered.end()) {
1447 return false;
1448 }
1449 listener = found->second;
1450 mCallbackRegistered.erase(found);
1451 }
1452
1453 mAppOpsManager->stopWatchingMode(listener);
1454 return true;
1455}
1456
1457void IncrementalService::onAppOpChanged(const std::string& packageName) {
1458 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001459 return;
1460 }
1461
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001462 std::vector<IfsMountPtr> affected;
1463 {
1464 std::lock_guard l(mLock);
1465 affected.reserve(mMounts.size());
1466 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001467 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001468 affected.push_back(ifs);
1469 }
1470 }
1471 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001472 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001473 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001474 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001475}
1476
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001477IncrementalService::DataLoaderStub::~DataLoaderStub() {
1478 CHECK(mStatus == -1 || mStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED)
1479 << "Dataloader has to be destroyed prior to destructor: " << mId
1480 << ", status: " << mStatus;
1481}
1482
1483bool IncrementalService::DataLoaderStub::create() {
1484 bool created = false;
1485 auto status = mService.mDataLoaderManager->initializeDataLoader(mId, mParams, mControl, this,
1486 &created);
1487 if (!status.isOk() || !created) {
1488 LOG(ERROR) << "Failed to create a data loader for mount " << mId;
1489 return false;
1490 }
1491 return true;
1492}
1493
1494bool IncrementalService::DataLoaderStub::start() {
1495 if (mStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
1496 mStartRequested = true;
1497 return true;
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001498 }
1499
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001500 sp<IDataLoader> dataloader;
1501 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1502 if (!status.isOk()) {
1503 return false;
1504 }
1505 if (!dataloader) {
1506 return false;
1507 }
1508 status = dataloader->start(mId);
1509 if (!status.isOk()) {
1510 return false;
1511 }
1512 return true;
1513}
1514
1515void IncrementalService::DataLoaderStub::destroy() {
1516 mDestroyRequested = true;
1517 mService.mDataLoaderManager->destroyDataLoader(mId);
1518}
1519
1520binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
1521 if (mStatus == newStatus) {
1522 return binder::Status::ok();
1523 }
1524
1525 if (mListener) {
1526 // Give an external listener a chance to act before we destroy something.
1527 mListener->onStatusChanged(mountId, newStatus);
1528 }
1529
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001530 {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001531 std::unique_lock l(mService.mLock);
1532 const auto& ifs = mService.getIfsLocked(mountId);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001533 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001534 LOG(WARNING) << "Received data loader status " << int(newStatus)
1535 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001536 return binder::Status::ok();
1537 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001538 mStatus = newStatus;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001539
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001540 if (!mDestroyRequested && newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1541 mService.deleteStorageLocked(*ifs, std::move(l));
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001542 return binder::Status::ok();
1543 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001544 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001545
Songchun Fan3c82a302019-11-29 14:23:45 -08001546 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001547 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001548 if (mStartRequested) {
1549 start();
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001550 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001551 break;
1552 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001553 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001554 break;
1555 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001556 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001557 break;
1558 }
1559 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1560 break;
1561 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001562 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1563 break;
1564 }
1565 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1566 break;
1567 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001568 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1569 // Nothing for now. Rely on externalListener to handle this.
1570 break;
1571 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001572 default: {
1573 LOG(WARNING) << "Unknown data loader status: " << newStatus
1574 << " for mount: " << mountId;
1575 break;
1576 }
1577 }
1578
1579 return binder::Status::ok();
1580}
1581
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001582void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1583 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001584}
1585
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001586binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1587 bool enableReadLogs, int32_t* _aidl_return) {
1588 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1589 return binder::Status::ok();
1590}
1591
Songchun Fan3c82a302019-11-29 14:23:45 -08001592} // namespace android::incremental