blob: c1f237f91b44e1d41628c93addd9fb901021633d [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 Zubrytskyida208012020-04-07 15:35:21 -0700261IncrementalService::~IncrementalService() {
262 {
263 std::lock_guard lock(mJobMutex);
264 mRunning = false;
265 }
266 mJobCondition.notify_all();
267 mJobProcessor.join();
268}
Songchun Fan3c82a302019-11-29 14:23:45 -0800269
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800270inline const char* toString(TimePoint t) {
271 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800272 time_t time = SystemClock::to_time_t(
273 SystemClock::now() +
274 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800275 return std::ctime(&time);
276}
277
278inline const char* toString(IncrementalService::BindKind kind) {
279 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800280 case IncrementalService::BindKind::Temporary:
281 return "Temporary";
282 case IncrementalService::BindKind::Permanent:
283 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800284 }
285}
286
287void IncrementalService::onDump(int fd) {
288 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
289 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
290
291 std::unique_lock l(mLock);
292
293 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
294 for (auto&& [id, ifs] : mMounts) {
295 const IncFsMount& mnt = *ifs.get();
296 dprintf(fd, "\t[%d]:\n", id);
297 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700298 dprintf(fd, "\t\troot: %s\n", mnt.root.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800299 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700300 if (mnt.dataLoaderStub) {
301 const auto& dataLoaderStub = *mnt.dataLoaderStub;
302 dprintf(fd, "\t\tdataLoaderStatus: %d\n", dataLoaderStub.status());
303 dprintf(fd, "\t\tdataLoaderStartRequested: %s\n",
304 dataLoaderStub.startRequested() ? "true" : "false");
305 const auto& params = dataLoaderStub.params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700306 dprintf(fd, "\t\tdataLoaderParams:\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800307 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
308 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
309 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
310 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800311 }
312 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
313 for (auto&& [storageId, storage] : mnt.storages) {
314 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
315 }
316
317 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
318 for (auto&& [target, bind] : mnt.bindPoints) {
319 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
320 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
321 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
322 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
323 }
324 }
325
326 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
327 for (auto&& [target, mountPairIt] : mBindsByPath) {
328 const auto& bind = mountPairIt->second;
329 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
330 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
331 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
332 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
333 }
334}
335
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700336void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800337 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700338 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800339 }
340
341 std::vector<IfsMountPtr> mounts;
342 {
343 std::lock_guard l(mLock);
344 mounts.reserve(mMounts.size());
345 for (auto&& [id, ifs] : mMounts) {
346 if (ifs->mountId == id) {
347 mounts.push_back(ifs);
348 }
349 }
350 }
351
Alex Buynytskyy69941662020-04-11 21:40:37 -0700352 if (mounts.empty()) {
353 return;
354 }
355
Songchun Fan3c82a302019-11-29 14:23:45 -0800356 std::thread([this, mounts = std::move(mounts)]() {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700357 mJni->initializeForCurrentThread();
Songchun Fan3c82a302019-11-29 14:23:45 -0800358 for (auto&& ifs : mounts) {
Alex Buynytskyy69941662020-04-11 21:40:37 -0700359 if (ifs->dataLoaderStub->create()) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800360 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
361 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800362 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800363 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800364 }
365 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800366 }).detach();
Songchun Fan3c82a302019-11-29 14:23:45 -0800367}
368
369auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
370 for (;;) {
371 if (mNextId == kMaxStorageId) {
372 mNextId = 0;
373 }
374 auto id = ++mNextId;
375 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
376 if (inserted) {
377 return it;
378 }
379 }
380}
381
Songchun Fan1124fd32020-02-10 12:49:41 -0800382StorageId IncrementalService::createStorage(
383 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
384 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800385 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
386 if (!path::isAbsolute(mountPoint)) {
387 LOG(ERROR) << "path is not absolute: " << mountPoint;
388 return kInvalidStorageId;
389 }
390
391 auto mountNorm = path::normalize(mountPoint);
392 {
393 const auto id = findStorageId(mountNorm);
394 if (id != kInvalidStorageId) {
395 if (options & CreateOptions::OpenExisting) {
396 LOG(INFO) << "Opened existing storage " << id;
397 return id;
398 }
399 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
400 return kInvalidStorageId;
401 }
402 }
403
404 if (!(options & CreateOptions::CreateNew)) {
405 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
406 return kInvalidStorageId;
407 }
408
409 if (!path::isEmptyDir(mountNorm)) {
410 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
411 return kInvalidStorageId;
412 }
413 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
414 if (mountRoot.empty()) {
415 LOG(ERROR) << "Bad mount point";
416 return kInvalidStorageId;
417 }
418 // Make sure the code removes all crap it may create while still failing.
419 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
420 auto firstCleanupOnFailure =
421 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
422
423 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800424 const auto backing = path::join(mountRoot, constants().backing);
425 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800426 return kInvalidStorageId;
427 }
428
Songchun Fan3c82a302019-11-29 14:23:45 -0800429 IncFsMount::Control control;
430 {
431 std::lock_guard l(mMountOperationLock);
432 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800433
434 if (auto err = rmDirContent(backing.c_str())) {
435 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
436 return kInvalidStorageId;
437 }
438 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
439 return kInvalidStorageId;
440 }
441 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800442 if (!status.isOk()) {
443 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
444 return kInvalidStorageId;
445 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800446 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
447 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800448 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
449 return kInvalidStorageId;
450 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800451 int cmd = controlParcel.cmd.release().release();
452 int pendingReads = controlParcel.pendingReads.release().release();
453 int logs = controlParcel.log.release().release();
454 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800455 }
456
457 std::unique_lock l(mLock);
458 const auto mountIt = getStorageSlotLocked();
459 const auto mountId = mountIt->first;
460 l.unlock();
461
462 auto ifs =
463 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
464 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
465 // is the removal of the |ifs|.
466 firstCleanupOnFailure.release();
467
468 auto secondCleanup = [this, &l](auto itPtr) {
469 if (!l.owns_lock()) {
470 l.lock();
471 }
472 mMounts.erase(*itPtr);
473 };
474 auto secondCleanupOnFailure =
475 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
476
477 const auto storageIt = ifs->makeStorage(ifs->mountId);
478 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800479 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800480 return kInvalidStorageId;
481 }
482
483 {
484 metadata::Mount m;
485 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700486 m.mutable_loader()->set_type((int)dataLoaderParams.type);
487 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
488 m.mutable_loader()->set_class_name(dataLoaderParams.className);
489 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800490 const auto metadata = m.SerializeAsString();
491 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800492 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800493 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800494 if (auto err =
495 mIncFs->makeFile(ifs->control,
496 path::join(ifs->root, constants().mount,
497 constants().infoMdName),
498 0777, idFromMetadata(metadata),
499 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800500 LOG(ERROR) << "Saving mount metadata failed: " << -err;
501 return kInvalidStorageId;
502 }
503 }
504
505 const auto bk =
506 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800507 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
508 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800509 err < 0) {
510 LOG(ERROR) << "adding bind mount failed: " << -err;
511 return kInvalidStorageId;
512 }
513
514 // Done here as well, all data structures are in good state.
515 secondCleanupOnFailure.release();
516
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700517 auto dataLoaderStub =
518 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
519 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800520
521 mountIt->second = std::move(ifs);
522 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700523
524 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->create()) {
525 // failed to create data loader
526 LOG(ERROR) << "initializeDataLoader() failed";
527 deleteStorage(dataLoaderStub->id());
528 return kInvalidStorageId;
529 }
530
Songchun Fan3c82a302019-11-29 14:23:45 -0800531 LOG(INFO) << "created storage " << mountId;
532 return mountId;
533}
534
535StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
536 StorageId linkedStorage,
537 IncrementalService::CreateOptions options) {
538 if (!isValidMountTarget(mountPoint)) {
539 LOG(ERROR) << "Mount point is invalid or missing";
540 return kInvalidStorageId;
541 }
542
543 std::unique_lock l(mLock);
544 const auto& ifs = getIfsLocked(linkedStorage);
545 if (!ifs) {
546 LOG(ERROR) << "Ifs unavailable";
547 return kInvalidStorageId;
548 }
549
550 const auto mountIt = getStorageSlotLocked();
551 const auto storageId = mountIt->first;
552 const auto storageIt = ifs->makeStorage(storageId);
553 if (storageIt == ifs->storages.end()) {
554 LOG(ERROR) << "Can't create a new storage";
555 mMounts.erase(mountIt);
556 return kInvalidStorageId;
557 }
558
559 l.unlock();
560
561 const auto bk =
562 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800563 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
564 std::string(storageIt->second.name), path::normalize(mountPoint),
565 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800566 err < 0) {
567 LOG(ERROR) << "bindMount failed with error: " << err;
568 return kInvalidStorageId;
569 }
570
571 mountIt->second = ifs;
572 return storageId;
573}
574
575IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
576 std::string_view path) const {
577 auto bindPointIt = mBindsByPath.upper_bound(path);
578 if (bindPointIt == mBindsByPath.begin()) {
579 return mBindsByPath.end();
580 }
581 --bindPointIt;
582 if (!path::startsWith(path, bindPointIt->first)) {
583 return mBindsByPath.end();
584 }
585 return bindPointIt;
586}
587
588StorageId IncrementalService::findStorageId(std::string_view path) const {
589 std::lock_guard l(mLock);
590 auto it = findStorageLocked(path);
591 if (it == mBindsByPath.end()) {
592 return kInvalidStorageId;
593 }
594 return it->second->second.storage;
595}
596
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700597int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
598 const auto ifs = getIfs(storageId);
599 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700600 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700601 return -EINVAL;
602 }
603
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700604 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700605 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700606 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
607 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700608 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700609 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700610 return fromBinderStatus(status);
611 }
612 }
613
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700614 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
615 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
616 return fromBinderStatus(status);
617 }
618
619 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700620 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700621 }
622
623 return 0;
624}
625
626binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700627 using unique_fd = ::android::base::unique_fd;
628 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700629 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
630 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
631 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700632 if (logsFd >= 0) {
633 control.log.reset(unique_fd(dup(logsFd)));
634 }
635
636 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700637 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700638}
639
Songchun Fan3c82a302019-11-29 14:23:45 -0800640void IncrementalService::deleteStorage(StorageId storageId) {
641 const auto ifs = getIfs(storageId);
642 if (!ifs) {
643 return;
644 }
645 deleteStorage(*ifs);
646}
647
648void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
649 std::unique_lock l(ifs.lock);
650 deleteStorageLocked(ifs, std::move(l));
651}
652
653void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
654 std::unique_lock<std::mutex>&& ifsLock) {
655 const auto storages = std::move(ifs.storages);
656 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
657 const auto bindPoints = ifs.bindPoints;
658 ifsLock.unlock();
659
660 std::lock_guard l(mLock);
661 for (auto&& [id, _] : storages) {
662 if (id != ifs.mountId) {
663 mMounts.erase(id);
664 }
665 }
666 for (auto&& [path, _] : bindPoints) {
667 mBindsByPath.erase(path);
668 }
669 mMounts.erase(ifs.mountId);
670}
671
672StorageId IncrementalService::openStorage(std::string_view pathInMount) {
673 if (!path::isAbsolute(pathInMount)) {
674 return kInvalidStorageId;
675 }
676
677 return findStorageId(path::normalize(pathInMount));
678}
679
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800680FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800681 const auto ifs = getIfs(storage);
682 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800683 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800684 }
685 std::unique_lock l(ifs->lock);
686 auto storageIt = ifs->storages.find(storage);
687 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800688 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800689 }
690 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800691 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800692 }
693 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
694 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800695 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800696}
697
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800698std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800699 StorageId storage, std::string_view subpath) const {
700 auto name = path::basename(subpath);
701 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800702 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800703 }
704 auto dir = path::dirname(subpath);
705 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800706 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800707 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800708 auto id = nodeFor(storage, dir);
709 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800710}
711
712IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
713 std::lock_guard l(mLock);
714 return getIfsLocked(storage);
715}
716
717const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
718 auto it = mMounts.find(storage);
719 if (it == mMounts.end()) {
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700720 static const android::base::NoDestructor<IfsMountPtr> kEmpty{};
721 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800722 }
723 return it->second;
724}
725
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800726int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
727 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800728 if (!isValidMountTarget(target)) {
729 return -EINVAL;
730 }
731
732 const auto ifs = getIfs(storage);
733 if (!ifs) {
734 return -EINVAL;
735 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800736
Songchun Fan3c82a302019-11-29 14:23:45 -0800737 std::unique_lock l(ifs->lock);
738 const auto storageInfo = ifs->storages.find(storage);
739 if (storageInfo == ifs->storages.end()) {
740 return -EINVAL;
741 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700742 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
743 if (normSource.empty()) {
744 return -EINVAL;
745 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800746 l.unlock();
747 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800748 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
749 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800750}
751
752int IncrementalService::unbind(StorageId storage, std::string_view target) {
753 if (!path::isAbsolute(target)) {
754 return -EINVAL;
755 }
756
757 LOG(INFO) << "Removing bind point " << target;
758
759 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
760 // otherwise there's a chance to unmount something completely unrelated
761 const auto norm = path::normalize(target);
762 std::unique_lock l(mLock);
763 const auto storageIt = mBindsByPath.find(norm);
764 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
765 return -EINVAL;
766 }
767 const auto bindIt = storageIt->second;
768 const auto storageId = bindIt->second.storage;
769 const auto ifs = getIfsLocked(storageId);
770 if (!ifs) {
771 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
772 << " is missing";
773 return -EFAULT;
774 }
775 mBindsByPath.erase(storageIt);
776 l.unlock();
777
778 mVold->unmountIncFs(bindIt->first);
779 std::unique_lock l2(ifs->lock);
780 if (ifs->bindPoints.size() <= 1) {
781 ifs->bindPoints.clear();
782 deleteStorageLocked(*ifs, std::move(l2));
783 } else {
784 const std::string savedFile = std::move(bindIt->second.savedFilename);
785 ifs->bindPoints.erase(bindIt);
786 l2.unlock();
787 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800788 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800789 }
790 }
791 return 0;
792}
793
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700794std::string IncrementalService::normalizePathToStorageLocked(
795 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
796 std::string normPath;
797 if (path::isAbsolute(path)) {
798 normPath = path::normalize(path);
799 if (!path::startsWith(normPath, storageIt->second.name)) {
800 return {};
801 }
802 } else {
803 normPath = path::normalize(path::join(storageIt->second.name, path));
804 }
805 return normPath;
806}
807
808std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800809 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700810 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800811 const auto storageInfo = ifs->storages.find(storage);
812 if (storageInfo == ifs->storages.end()) {
813 return {};
814 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700815 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800816}
817
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800818int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
819 incfs::NewFileParams params) {
820 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800821 std::string normPath = normalizePathToStorage(ifs, storage, path);
822 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700823 LOG(ERROR) << "Internal error: storageId " << storage
824 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800825 return -EINVAL;
826 }
827 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800828 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700829 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800830 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800831 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800832 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800833 }
834 return -EINVAL;
835}
836
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800837int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800838 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800839 std::string normPath = normalizePathToStorage(ifs, storageId, path);
840 if (normPath.empty()) {
841 return -EINVAL;
842 }
843 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800844 }
845 return -EINVAL;
846}
847
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800848int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800849 const auto ifs = getIfs(storageId);
850 if (!ifs) {
851 return -EINVAL;
852 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800853 std::string normPath = normalizePathToStorage(ifs, storageId, path);
854 if (normPath.empty()) {
855 return -EINVAL;
856 }
857 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800858 if (err == -EEXIST) {
859 return 0;
860 } else if (err != -ENOENT) {
861 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800862 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800863 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800864 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800865 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800866 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800867}
868
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800869int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
870 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700871 auto ifsSrc = getIfs(sourceStorageId);
872 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
873 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800874 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
875 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
876 if (normOldPath.empty() || normNewPath.empty()) {
877 return -EINVAL;
878 }
879 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800880 }
881 return -EINVAL;
882}
883
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800884int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800885 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800886 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
887 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800888 }
889 return -EINVAL;
890}
891
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800892int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
893 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800894 std::string&& target, BindKind kind,
895 std::unique_lock<std::mutex>& mainLock) {
896 if (!isValidMountTarget(target)) {
897 return -EINVAL;
898 }
899
900 std::string mdFileName;
901 if (kind != BindKind::Temporary) {
902 metadata::BindPoint bp;
903 bp.set_storage_id(storage);
904 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800905 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800906 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800907 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800908 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800909 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800910 auto node =
911 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
912 0444, idFromMetadata(metadata),
913 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
914 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800915 return int(node);
916 }
917 }
918
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800919 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800920 std::move(target), kind, mainLock);
921}
922
923int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800924 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 std::string&& target, BindKind kind,
926 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800927 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800928 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800929 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800930 if (!status.isOk()) {
931 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
932 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
933 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
934 : status.serviceSpecificErrorCode() == 0
935 ? -EFAULT
936 : status.serviceSpecificErrorCode()
937 : -EIO;
938 }
939 }
940
941 if (!mainLock.owns_lock()) {
942 mainLock.lock();
943 }
944 std::lock_guard l(ifs.lock);
945 const auto [it, _] =
946 ifs.bindPoints.insert_or_assign(target,
947 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800948 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800949 mBindsByPath[std::move(target)] = it;
950 return 0;
951}
952
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800953RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800954 const auto ifs = getIfs(storage);
955 if (!ifs) {
956 return {};
957 }
958 return mIncFs->getMetadata(ifs->control, node);
959}
960
961std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
962 const auto ifs = getIfs(storage);
963 if (!ifs) {
964 return {};
965 }
966
967 std::unique_lock l(ifs->lock);
968 auto subdirIt = ifs->storages.find(storage);
969 if (subdirIt == ifs->storages.end()) {
970 return {};
971 }
972 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
973 l.unlock();
974
975 const auto prefixSize = dir.size() + 1;
976 std::vector<std::string> todoDirs{std::move(dir)};
977 std::vector<std::string> result;
978 do {
979 auto currDir = std::move(todoDirs.back());
980 todoDirs.pop_back();
981
982 auto d =
983 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
984 while (auto e = ::readdir(d.get())) {
985 if (e->d_type == DT_REG) {
986 result.emplace_back(
987 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
988 continue;
989 }
990 if (e->d_type == DT_DIR) {
991 if (e->d_name == "."sv || e->d_name == ".."sv) {
992 continue;
993 }
994 todoDirs.emplace_back(path::join(currDir, e->d_name));
995 continue;
996 }
997 }
998 } while (!todoDirs.empty());
999 return result;
1000}
1001
1002bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001003 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001004 {
1005 std::unique_lock l(mLock);
1006 const auto& ifs = getIfsLocked(storage);
1007 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001008 return false;
1009 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001010 dataLoaderStub = ifs->dataLoaderStub;
1011 if (!dataLoaderStub) {
1012 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001013 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001014 }
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001015 return dataLoaderStub->requestStart();
Songchun Fan3c82a302019-11-29 14:23:45 -08001016}
1017
1018void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001019 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1020 const auto path = entry.path().u8string();
1021 const auto name = entry.path().filename().u8string();
1022 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001023 continue;
1024 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001025 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001026 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001027 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001028 }
1029 }
1030}
1031
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001032bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001033 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001034 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001035
Songchun Fan3c82a302019-11-29 14:23:45 -08001036 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001037 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001038 if (!status.isOk()) {
1039 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1040 return false;
1041 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001042
1043 int cmd = controlParcel.cmd.release().release();
1044 int pendingReads = controlParcel.pendingReads.release().release();
1045 int logs = controlParcel.log.release().release();
1046 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001047
1048 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1049
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001050 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1051 path::join(mountTarget, constants().infoMdName));
1052 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001053 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1054 return false;
1055 }
1056
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001057 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001058 mNextId = std::max(mNextId, ifs->mountId + 1);
1059
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001060 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001061 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001062 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001063 const auto& loader = mount.loader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001064 dataLoaderParams.type = (android::content::pm::DataLoaderType)loader.type();
1065 dataLoaderParams.packageName = loader.package_name();
1066 dataLoaderParams.className = loader.class_name();
1067 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001068 }
1069
Alex Buynytskyy69941662020-04-11 21:40:37 -07001070 prepareDataLoader(*ifs, std::move(dataLoaderParams), nullptr);
1071 CHECK(ifs->dataLoaderStub);
1072
Songchun Fan3c82a302019-11-29 14:23:45 -08001073 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001074 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001075 while (auto e = ::readdir(d.get())) {
1076 if (e->d_type == DT_REG) {
1077 auto name = std::string_view(e->d_name);
1078 if (name.starts_with(constants().mountpointMdPrefix)) {
1079 bindPoints.emplace_back(name,
1080 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1081 ifs->control,
1082 path::join(mountTarget,
1083 name)));
1084 if (bindPoints.back().second.dest_path().empty() ||
1085 bindPoints.back().second.source_subdir().empty()) {
1086 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001087 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001088 }
1089 }
1090 } else if (e->d_type == DT_DIR) {
1091 if (e->d_name == "."sv || e->d_name == ".."sv) {
1092 continue;
1093 }
1094 auto name = std::string_view(e->d_name);
1095 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001096 int storageId;
1097 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1098 name.data() + name.size(), storageId);
1099 if (res.ec != std::errc{} || *res.ptr != '_') {
1100 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1101 << root;
1102 continue;
1103 }
1104 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001105 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001106 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001107 << " for mount " << root;
1108 continue;
1109 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001110 ifs->storages.insert_or_assign(storageId,
1111 IncFsMount::Storage{
1112 path::join(root, constants().mount, name)});
1113 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001114 }
1115 }
1116 }
1117
1118 if (ifs->storages.empty()) {
1119 LOG(WARNING) << "No valid storages in mount " << root;
1120 return false;
1121 }
1122
1123 int bindCount = 0;
1124 for (auto&& bp : bindPoints) {
1125 std::unique_lock l(mLock, std::defer_lock);
1126 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1127 std::move(*bp.second.mutable_source_subdir()),
1128 std::move(*bp.second.mutable_dest_path()),
1129 BindKind::Permanent, l);
1130 }
1131
1132 if (bindCount == 0) {
1133 LOG(WARNING) << "No valid bind points for mount " << root;
1134 deleteStorage(*ifs);
1135 return false;
1136 }
1137
Songchun Fan3c82a302019-11-29 14:23:45 -08001138 mMounts[ifs->mountId] = std::move(ifs);
1139 return true;
1140}
1141
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001142IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
1143 IncrementalService::IncFsMount& ifs, DataLoaderParamsParcel&& params,
1144 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001145 std::unique_lock l(ifs.lock);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001146 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001147 LOG(INFO) << "Skipped data loader preparation because it already exists";
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001148 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001149 }
1150
Songchun Fan3c82a302019-11-29 14:23:45 -08001151 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001152 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001153 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001154 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001155 base::unique_fd(::dup(ifs.control.pendingReads())));
1156 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001157 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001158
1159 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1160 std::move(fsControlParcel), externalListener);
1161 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001162}
1163
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001164template <class Duration>
1165static long elapsedMcs(Duration start, Duration end) {
1166 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1167}
1168
1169// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001170bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1171 std::string_view libDirRelativePath,
1172 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001173 auto start = Clock::now();
1174
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001175 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001176 if (!ifs) {
1177 LOG(ERROR) << "Invalid storage " << storage;
1178 return false;
1179 }
1180
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001181 // First prepare target directories if they don't exist yet
1182 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1183 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1184 << " errno: " << res;
1185 return false;
1186 }
1187
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001188 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001189 ZipArchiveHandle zipFileHandle;
1190 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001191 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1192 return false;
1193 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001194
1195 // Need a shared pointer: will be passing it into all unpacking jobs.
1196 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001197 void* cookie = nullptr;
1198 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001199 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001200 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1201 return false;
1202 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001203 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001204 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1205
1206 auto openZipTs = Clock::now();
1207
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001208 std::vector<Job> jobQueue;
1209 ZipEntry entry;
1210 std::string_view fileName;
1211 while (!Next(cookie, &entry, &fileName)) {
1212 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001213 continue;
1214 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001215
1216 auto startFileTs = Clock::now();
1217
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001218 const auto libName = path::basename(fileName);
1219 const auto targetLibPath = path::join(libDirRelativePath, libName);
1220 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1221 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001222 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1223 if (sEnablePerfLogging) {
1224 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1225 << "; skipping extraction, spent "
1226 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1227 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001228 continue;
1229 }
1230
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001231 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001232 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001233 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001234 .signature = {},
1235 // Metadata of the new lib file is its relative path
1236 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1237 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001238 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001239 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1240 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001241 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001242 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001243 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001244 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001245
1246 auto makeFileTs = Clock::now();
1247
Songchun Fanafaf6e92020-03-18 14:12:20 -07001248 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001249 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001250 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001251 LOG(INFO) << "incfs: Extracted " << libName
1252 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001253 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001254 continue;
1255 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001256
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001257 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1258 libFileId, libPath = std::move(targetLibPath),
1259 makeFileTs]() mutable {
1260 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001261 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001262
1263 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001264 auto prepareJobTs = Clock::now();
1265 LOG(INFO) << "incfs: Processed " << libName << ": "
1266 << elapsedMcs(startFileTs, prepareJobTs)
1267 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1268 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001269 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001270 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001271
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001272 auto processedTs = Clock::now();
1273
1274 if (!jobQueue.empty()) {
1275 {
1276 std::lock_guard lock(mJobMutex);
1277 if (mRunning) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001278 auto& existingJobs = mJobQueue[ifs->mountId];
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001279 if (existingJobs.empty()) {
1280 existingJobs = std::move(jobQueue);
1281 } else {
1282 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1283 std::move_iterator(jobQueue.end()));
1284 }
1285 }
1286 }
1287 mJobCondition.notify_all();
1288 }
1289
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001290 if (sEnablePerfLogging) {
1291 auto end = Clock::now();
1292 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1293 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1294 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001295 << " make files: " << elapsedMcs(openZipTs, processedTs)
1296 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001297 }
1298
1299 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001300}
1301
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001302void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1303 ZipEntry& entry, const incfs::FileId& libFileId,
1304 std::string_view targetLibPath,
1305 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001306 if (!ifs) {
1307 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1308 return;
1309 }
1310
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001311 auto libName = path::basename(targetLibPath);
1312 auto startedTs = Clock::now();
1313
1314 // Write extracted data to new file
1315 // NOTE: don't zero-initialize memory, it may take a while for nothing
1316 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1317 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1318 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1319 return;
1320 }
1321
1322 auto extractFileTs = Clock::now();
1323
1324 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1325 if (!writeFd.ok()) {
1326 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1327 return;
1328 }
1329
1330 auto openFileTs = Clock::now();
1331 const int numBlocks =
1332 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1333 std::vector<IncFsDataBlock> instructions(numBlocks);
1334 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1335 for (int i = 0; i < numBlocks; i++) {
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001336 const auto blockSize = std::min<long>(constants().blockSize, remainingData.size());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001337 instructions[i] = IncFsDataBlock{
1338 .fileFd = writeFd.get(),
1339 .pageIndex = static_cast<IncFsBlockIndex>(i),
1340 .compression = INCFS_COMPRESSION_KIND_NONE,
1341 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi6c65a562020-04-14 15:25:49 -07001342 .dataSize = static_cast<uint32_t>(blockSize),
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001343 .data = reinterpret_cast<const char*>(remainingData.data()),
1344 };
1345 remainingData = remainingData.subspan(blockSize);
1346 }
1347 auto prepareInstsTs = Clock::now();
1348
1349 size_t res = mIncFs->writeBlocks(instructions);
1350 if (res != instructions.size()) {
1351 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1352 return;
1353 }
1354
1355 if (sEnablePerfLogging) {
1356 auto endFileTs = Clock::now();
1357 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1358 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1359 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1360 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1361 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1362 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1363 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1364 }
1365}
1366
1367bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001368 struct WaitPrinter {
1369 const Clock::time_point startTs = Clock::now();
1370 ~WaitPrinter() noexcept {
1371 if (sEnablePerfLogging) {
1372 const auto endTs = Clock::now();
1373 LOG(INFO) << "incfs: waitForNativeBinariesExtraction() complete in "
1374 << elapsedMcs(startTs, endTs) << "mcs";
1375 }
1376 }
1377 } waitPrinter;
1378
1379 MountId mount;
1380 {
1381 auto ifs = getIfs(storage);
1382 if (!ifs) {
1383 return true;
1384 }
1385 mount = ifs->mountId;
1386 }
1387
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001388 std::unique_lock lock(mJobMutex);
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001389 mJobCondition.wait(lock, [this, mount] {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001390 return !mRunning ||
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001391 (mPendingJobsMount != mount && mJobQueue.find(mount) == mJobQueue.end());
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001392 });
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001393 return mRunning;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001394}
1395
1396void IncrementalService::runJobProcessing() {
1397 for (;;) {
1398 std::unique_lock lock(mJobMutex);
1399 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1400 if (!mRunning) {
1401 return;
1402 }
1403
1404 auto it = mJobQueue.begin();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001405 mPendingJobsMount = it->first;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001406 auto queue = std::move(it->second);
1407 mJobQueue.erase(it);
1408 lock.unlock();
1409
1410 for (auto&& job : queue) {
1411 job();
1412 }
1413
1414 lock.lock();
Yurii Zubrytskyi721ac4d2020-04-13 11:34:32 -07001415 mPendingJobsMount = kInvalidStorageId;
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001416 lock.unlock();
1417 mJobCondition.notify_all();
1418 }
1419}
1420
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001421void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001422 sp<IAppOpsCallback> listener;
1423 {
1424 std::unique_lock lock{mCallbacksLock};
1425 auto& cb = mCallbackRegistered[packageName];
1426 if (cb) {
1427 return;
1428 }
1429 cb = new AppOpsListener(*this, packageName);
1430 listener = cb;
1431 }
1432
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001433 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1434 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001435}
1436
1437bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1438 sp<IAppOpsCallback> listener;
1439 {
1440 std::unique_lock lock{mCallbacksLock};
1441 auto found = mCallbackRegistered.find(packageName);
1442 if (found == mCallbackRegistered.end()) {
1443 return false;
1444 }
1445 listener = found->second;
1446 mCallbackRegistered.erase(found);
1447 }
1448
1449 mAppOpsManager->stopWatchingMode(listener);
1450 return true;
1451}
1452
1453void IncrementalService::onAppOpChanged(const std::string& packageName) {
1454 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001455 return;
1456 }
1457
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001458 std::vector<IfsMountPtr> affected;
1459 {
1460 std::lock_guard l(mLock);
1461 affected.reserve(mMounts.size());
1462 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001463 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001464 affected.push_back(ifs);
1465 }
1466 }
1467 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001468 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001469 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001470 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001471}
1472
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001473IncrementalService::DataLoaderStub::~DataLoaderStub() {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001474 waitForDestroy();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001475}
1476
1477bool IncrementalService::DataLoaderStub::create() {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001478 {
1479 std::unique_lock lock(mStatusMutex);
1480 mStartRequested = false;
1481 mDestroyRequested = false;
1482 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001483 bool created = false;
1484 auto status = mService.mDataLoaderManager->initializeDataLoader(mId, mParams, mControl, this,
1485 &created);
1486 if (!status.isOk() || !created) {
1487 LOG(ERROR) << "Failed to create a data loader for mount " << mId;
1488 return false;
1489 }
1490 return true;
1491}
1492
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001493bool IncrementalService::DataLoaderStub::requestStart() {
1494 {
1495 std::unique_lock lock(mStatusMutex);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001496 mStartRequested = true;
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001497 if (mStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
1498 return true;
1499 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001500 }
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001501 return start();
1502}
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001503
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001504bool IncrementalService::DataLoaderStub::start() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001505 sp<IDataLoader> dataloader;
1506 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1507 if (!status.isOk()) {
1508 return false;
1509 }
1510 if (!dataloader) {
1511 return false;
1512 }
1513 status = dataloader->start(mId);
1514 if (!status.isOk()) {
1515 return false;
1516 }
1517 return true;
1518}
1519
1520void IncrementalService::DataLoaderStub::destroy() {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001521 {
1522 std::unique_lock lock(mStatusMutex);
1523 mDestroyRequested = true;
1524 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001525 mService.mDataLoaderManager->destroyDataLoader(mId);
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001526
1527 waitForDestroy();
1528}
1529
1530bool IncrementalService::DataLoaderStub::waitForDestroy() {
1531 auto now = std::chrono::steady_clock::now();
1532 std::unique_lock lock(mStatusMutex);
1533 return mStatusCondition.wait_until(lock, now + 60s, [this] {
1534 return mStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED;
1535 });
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001536}
1537
1538binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
1539 if (mStatus == newStatus) {
1540 return binder::Status::ok();
1541 }
1542
1543 if (mListener) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001544 mListener->onStatusChanged(mountId, newStatus);
1545 }
1546
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001547 bool startRequested;
1548 bool destroyRequested;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001549 {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001550 std::unique_lock lock(mStatusMutex);
1551 if (mStatus == newStatus) {
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001552 return binder::Status::ok();
1553 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001554
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001555 startRequested = mStartRequested;
1556 destroyRequested = mDestroyRequested;
1557
1558 mStatus = newStatus;
Songchun Fan3c82a302019-11-29 14:23:45 -08001559 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001560
Songchun Fan3c82a302019-11-29 14:23:45 -08001561 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001562 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001563 if (startRequested) {
1564 LOG(WARNING) << "Start was requested, triggering, for mount: " << mountId;
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001565 start();
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001566 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001567 break;
1568 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001569 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001570 if (!destroyRequested) {
1571 LOG(WARNING) << "DataLoader destroyed, reconnecting, for mount: " << mountId;
1572 create();
1573 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001574 break;
1575 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001576 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001577 break;
1578 }
1579 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1580 break;
1581 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001582 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1583 break;
1584 }
1585 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1586 break;
1587 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001588 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1589 // Nothing for now. Rely on externalListener to handle this.
1590 break;
1591 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001592 default: {
1593 LOG(WARNING) << "Unknown data loader status: " << newStatus
1594 << " for mount: " << mountId;
1595 break;
1596 }
1597 }
1598
1599 return binder::Status::ok();
1600}
1601
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001602void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1603 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001604}
1605
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001606binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1607 bool enableReadLogs, int32_t* _aidl_return) {
1608 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1609 return binder::Status::ok();
1610}
1611
Alex Buynytskyy0b202662020-04-13 09:53:04 -07001612FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
1613 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
1614}
1615
Songchun Fan3c82a302019-11-29 14:23:45 -08001616} // namespace android::incremental