blob: 2c6bf0a80fe0177f1aa38153a643982cbe0c0d23 [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 Buynytskyy0ea4ff42020-04-09 17:25:42 -0700356 /* TODO(b/151241369): restore data loaders on reboot.
Songchun Fan3c82a302019-11-29 14:23:45 -0800357 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800358 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800359 if (prepareDataLoader(*ifs)) {
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();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700367 */
Songchun Fan3c82a302019-11-29 14:23:45 -0800368}
369
370auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
371 for (;;) {
372 if (mNextId == kMaxStorageId) {
373 mNextId = 0;
374 }
375 auto id = ++mNextId;
376 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
377 if (inserted) {
378 return it;
379 }
380 }
381}
382
Songchun Fan1124fd32020-02-10 12:49:41 -0800383StorageId IncrementalService::createStorage(
384 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
385 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800386 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
387 if (!path::isAbsolute(mountPoint)) {
388 LOG(ERROR) << "path is not absolute: " << mountPoint;
389 return kInvalidStorageId;
390 }
391
392 auto mountNorm = path::normalize(mountPoint);
393 {
394 const auto id = findStorageId(mountNorm);
395 if (id != kInvalidStorageId) {
396 if (options & CreateOptions::OpenExisting) {
397 LOG(INFO) << "Opened existing storage " << id;
398 return id;
399 }
400 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
401 return kInvalidStorageId;
402 }
403 }
404
405 if (!(options & CreateOptions::CreateNew)) {
406 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
407 return kInvalidStorageId;
408 }
409
410 if (!path::isEmptyDir(mountNorm)) {
411 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
412 return kInvalidStorageId;
413 }
414 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
415 if (mountRoot.empty()) {
416 LOG(ERROR) << "Bad mount point";
417 return kInvalidStorageId;
418 }
419 // Make sure the code removes all crap it may create while still failing.
420 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
421 auto firstCleanupOnFailure =
422 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
423
424 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800425 const auto backing = path::join(mountRoot, constants().backing);
426 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800427 return kInvalidStorageId;
428 }
429
Songchun Fan3c82a302019-11-29 14:23:45 -0800430 IncFsMount::Control control;
431 {
432 std::lock_guard l(mMountOperationLock);
433 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800434
435 if (auto err = rmDirContent(backing.c_str())) {
436 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
437 return kInvalidStorageId;
438 }
439 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
440 return kInvalidStorageId;
441 }
442 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800443 if (!status.isOk()) {
444 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
445 return kInvalidStorageId;
446 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800447 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
448 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800449 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
450 return kInvalidStorageId;
451 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800452 int cmd = controlParcel.cmd.release().release();
453 int pendingReads = controlParcel.pendingReads.release().release();
454 int logs = controlParcel.log.release().release();
455 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800456 }
457
458 std::unique_lock l(mLock);
459 const auto mountIt = getStorageSlotLocked();
460 const auto mountId = mountIt->first;
461 l.unlock();
462
463 auto ifs =
464 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
465 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
466 // is the removal of the |ifs|.
467 firstCleanupOnFailure.release();
468
469 auto secondCleanup = [this, &l](auto itPtr) {
470 if (!l.owns_lock()) {
471 l.lock();
472 }
473 mMounts.erase(*itPtr);
474 };
475 auto secondCleanupOnFailure =
476 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
477
478 const auto storageIt = ifs->makeStorage(ifs->mountId);
479 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800480 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800481 return kInvalidStorageId;
482 }
483
484 {
485 metadata::Mount m;
486 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700487 m.mutable_loader()->set_type((int)dataLoaderParams.type);
488 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
489 m.mutable_loader()->set_class_name(dataLoaderParams.className);
490 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800491 const auto metadata = m.SerializeAsString();
492 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800493 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800494 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800495 if (auto err =
496 mIncFs->makeFile(ifs->control,
497 path::join(ifs->root, constants().mount,
498 constants().infoMdName),
499 0777, idFromMetadata(metadata),
500 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800501 LOG(ERROR) << "Saving mount metadata failed: " << -err;
502 return kInvalidStorageId;
503 }
504 }
505
506 const auto bk =
507 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800508 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
509 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800510 err < 0) {
511 LOG(ERROR) << "adding bind mount failed: " << -err;
512 return kInvalidStorageId;
513 }
514
515 // Done here as well, all data structures are in good state.
516 secondCleanupOnFailure.release();
517
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700518 auto dataLoaderStub =
519 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
520 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800521
522 mountIt->second = std::move(ifs);
523 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700524
525 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->create()) {
526 // failed to create data loader
527 LOG(ERROR) << "initializeDataLoader() failed";
528 deleteStorage(dataLoaderStub->id());
529 return kInvalidStorageId;
530 }
531
Songchun Fan3c82a302019-11-29 14:23:45 -0800532 LOG(INFO) << "created storage " << mountId;
533 return mountId;
534}
535
536StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
537 StorageId linkedStorage,
538 IncrementalService::CreateOptions options) {
539 if (!isValidMountTarget(mountPoint)) {
540 LOG(ERROR) << "Mount point is invalid or missing";
541 return kInvalidStorageId;
542 }
543
544 std::unique_lock l(mLock);
545 const auto& ifs = getIfsLocked(linkedStorage);
546 if (!ifs) {
547 LOG(ERROR) << "Ifs unavailable";
548 return kInvalidStorageId;
549 }
550
551 const auto mountIt = getStorageSlotLocked();
552 const auto storageId = mountIt->first;
553 const auto storageIt = ifs->makeStorage(storageId);
554 if (storageIt == ifs->storages.end()) {
555 LOG(ERROR) << "Can't create a new storage";
556 mMounts.erase(mountIt);
557 return kInvalidStorageId;
558 }
559
560 l.unlock();
561
562 const auto bk =
563 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800564 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
565 std::string(storageIt->second.name), path::normalize(mountPoint),
566 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800567 err < 0) {
568 LOG(ERROR) << "bindMount failed with error: " << err;
569 return kInvalidStorageId;
570 }
571
572 mountIt->second = ifs;
573 return storageId;
574}
575
576IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
577 std::string_view path) const {
578 auto bindPointIt = mBindsByPath.upper_bound(path);
579 if (bindPointIt == mBindsByPath.begin()) {
580 return mBindsByPath.end();
581 }
582 --bindPointIt;
583 if (!path::startsWith(path, bindPointIt->first)) {
584 return mBindsByPath.end();
585 }
586 return bindPointIt;
587}
588
589StorageId IncrementalService::findStorageId(std::string_view path) const {
590 std::lock_guard l(mLock);
591 auto it = findStorageLocked(path);
592 if (it == mBindsByPath.end()) {
593 return kInvalidStorageId;
594 }
595 return it->second->second.storage;
596}
597
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700598int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
599 const auto ifs = getIfs(storageId);
600 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700601 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700602 return -EINVAL;
603 }
604
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700605 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700606 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700607 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
608 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700609 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700610 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700611 return fromBinderStatus(status);
612 }
613 }
614
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700615 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
616 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
617 return fromBinderStatus(status);
618 }
619
620 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700621 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700622 }
623
624 return 0;
625}
626
627binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700628 using unique_fd = ::android::base::unique_fd;
629 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700630 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
631 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
632 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700633 if (logsFd >= 0) {
634 control.log.reset(unique_fd(dup(logsFd)));
635 }
636
637 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700638 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700639}
640
Songchun Fan3c82a302019-11-29 14:23:45 -0800641void IncrementalService::deleteStorage(StorageId storageId) {
642 const auto ifs = getIfs(storageId);
643 if (!ifs) {
644 return;
645 }
646 deleteStorage(*ifs);
647}
648
649void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
650 std::unique_lock l(ifs.lock);
651 deleteStorageLocked(ifs, std::move(l));
652}
653
654void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
655 std::unique_lock<std::mutex>&& ifsLock) {
656 const auto storages = std::move(ifs.storages);
657 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
658 const auto bindPoints = ifs.bindPoints;
659 ifsLock.unlock();
660
661 std::lock_guard l(mLock);
662 for (auto&& [id, _] : storages) {
663 if (id != ifs.mountId) {
664 mMounts.erase(id);
665 }
666 }
667 for (auto&& [path, _] : bindPoints) {
668 mBindsByPath.erase(path);
669 }
670 mMounts.erase(ifs.mountId);
671}
672
673StorageId IncrementalService::openStorage(std::string_view pathInMount) {
674 if (!path::isAbsolute(pathInMount)) {
675 return kInvalidStorageId;
676 }
677
678 return findStorageId(path::normalize(pathInMount));
679}
680
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800681FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800682 const auto ifs = getIfs(storage);
683 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800684 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800685 }
686 std::unique_lock l(ifs->lock);
687 auto storageIt = ifs->storages.find(storage);
688 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800689 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800690 }
691 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800692 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800693 }
694 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
695 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800696 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800697}
698
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800699std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800700 StorageId storage, std::string_view subpath) const {
701 auto name = path::basename(subpath);
702 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800703 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800704 }
705 auto dir = path::dirname(subpath);
706 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800707 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800708 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800709 auto id = nodeFor(storage, dir);
710 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800711}
712
713IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
714 std::lock_guard l(mLock);
715 return getIfsLocked(storage);
716}
717
718const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
719 auto it = mMounts.find(storage);
720 if (it == mMounts.end()) {
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700721 static const android::base::NoDestructor<IfsMountPtr> kEmpty{};
722 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800723 }
724 return it->second;
725}
726
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800727int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
728 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800729 if (!isValidMountTarget(target)) {
730 return -EINVAL;
731 }
732
733 const auto ifs = getIfs(storage);
734 if (!ifs) {
735 return -EINVAL;
736 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800737
Songchun Fan3c82a302019-11-29 14:23:45 -0800738 std::unique_lock l(ifs->lock);
739 const auto storageInfo = ifs->storages.find(storage);
740 if (storageInfo == ifs->storages.end()) {
741 return -EINVAL;
742 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700743 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
744 if (normSource.empty()) {
745 return -EINVAL;
746 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800747 l.unlock();
748 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800749 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
750 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800751}
752
753int IncrementalService::unbind(StorageId storage, std::string_view target) {
754 if (!path::isAbsolute(target)) {
755 return -EINVAL;
756 }
757
758 LOG(INFO) << "Removing bind point " << target;
759
760 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
761 // otherwise there's a chance to unmount something completely unrelated
762 const auto norm = path::normalize(target);
763 std::unique_lock l(mLock);
764 const auto storageIt = mBindsByPath.find(norm);
765 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
766 return -EINVAL;
767 }
768 const auto bindIt = storageIt->second;
769 const auto storageId = bindIt->second.storage;
770 const auto ifs = getIfsLocked(storageId);
771 if (!ifs) {
772 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
773 << " is missing";
774 return -EFAULT;
775 }
776 mBindsByPath.erase(storageIt);
777 l.unlock();
778
779 mVold->unmountIncFs(bindIt->first);
780 std::unique_lock l2(ifs->lock);
781 if (ifs->bindPoints.size() <= 1) {
782 ifs->bindPoints.clear();
783 deleteStorageLocked(*ifs, std::move(l2));
784 } else {
785 const std::string savedFile = std::move(bindIt->second.savedFilename);
786 ifs->bindPoints.erase(bindIt);
787 l2.unlock();
788 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800789 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800790 }
791 }
792 return 0;
793}
794
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700795std::string IncrementalService::normalizePathToStorageLocked(
796 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
797 std::string normPath;
798 if (path::isAbsolute(path)) {
799 normPath = path::normalize(path);
800 if (!path::startsWith(normPath, storageIt->second.name)) {
801 return {};
802 }
803 } else {
804 normPath = path::normalize(path::join(storageIt->second.name, path));
805 }
806 return normPath;
807}
808
809std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800810 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700811 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800812 const auto storageInfo = ifs->storages.find(storage);
813 if (storageInfo == ifs->storages.end()) {
814 return {};
815 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700816 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800817}
818
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800819int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
820 incfs::NewFileParams params) {
821 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800822 std::string normPath = normalizePathToStorage(ifs, storage, path);
823 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700824 LOG(ERROR) << "Internal error: storageId " << storage
825 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800826 return -EINVAL;
827 }
828 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800829 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700830 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800831 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800832 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800833 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800834 }
835 return -EINVAL;
836}
837
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800838int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800839 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800840 std::string normPath = normalizePathToStorage(ifs, storageId, path);
841 if (normPath.empty()) {
842 return -EINVAL;
843 }
844 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800845 }
846 return -EINVAL;
847}
848
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800849int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800850 const auto ifs = getIfs(storageId);
851 if (!ifs) {
852 return -EINVAL;
853 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800854 std::string normPath = normalizePathToStorage(ifs, storageId, path);
855 if (normPath.empty()) {
856 return -EINVAL;
857 }
858 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800859 if (err == -EEXIST) {
860 return 0;
861 } else if (err != -ENOENT) {
862 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800863 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800864 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800865 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800866 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800867 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800868}
869
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800870int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
871 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700872 auto ifsSrc = getIfs(sourceStorageId);
873 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
874 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800875 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
876 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
877 if (normOldPath.empty() || normNewPath.empty()) {
878 return -EINVAL;
879 }
880 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800881 }
882 return -EINVAL;
883}
884
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800885int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800886 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800887 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
888 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800889 }
890 return -EINVAL;
891}
892
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800893int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
894 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800895 std::string&& target, BindKind kind,
896 std::unique_lock<std::mutex>& mainLock) {
897 if (!isValidMountTarget(target)) {
898 return -EINVAL;
899 }
900
901 std::string mdFileName;
902 if (kind != BindKind::Temporary) {
903 metadata::BindPoint bp;
904 bp.set_storage_id(storage);
905 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800906 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800907 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800908 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800909 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800910 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800911 auto node =
912 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
913 0444, idFromMetadata(metadata),
914 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
915 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800916 return int(node);
917 }
918 }
919
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800920 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800921 std::move(target), kind, mainLock);
922}
923
924int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800925 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800926 std::string&& target, BindKind kind,
927 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800928 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800929 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800930 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800931 if (!status.isOk()) {
932 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
933 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
934 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
935 : status.serviceSpecificErrorCode() == 0
936 ? -EFAULT
937 : status.serviceSpecificErrorCode()
938 : -EIO;
939 }
940 }
941
942 if (!mainLock.owns_lock()) {
943 mainLock.lock();
944 }
945 std::lock_guard l(ifs.lock);
946 const auto [it, _] =
947 ifs.bindPoints.insert_or_assign(target,
948 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800949 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800950 mBindsByPath[std::move(target)] = it;
951 return 0;
952}
953
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800954RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800955 const auto ifs = getIfs(storage);
956 if (!ifs) {
957 return {};
958 }
959 return mIncFs->getMetadata(ifs->control, node);
960}
961
962std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
963 const auto ifs = getIfs(storage);
964 if (!ifs) {
965 return {};
966 }
967
968 std::unique_lock l(ifs->lock);
969 auto subdirIt = ifs->storages.find(storage);
970 if (subdirIt == ifs->storages.end()) {
971 return {};
972 }
973 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
974 l.unlock();
975
976 const auto prefixSize = dir.size() + 1;
977 std::vector<std::string> todoDirs{std::move(dir)};
978 std::vector<std::string> result;
979 do {
980 auto currDir = std::move(todoDirs.back());
981 todoDirs.pop_back();
982
983 auto d =
984 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
985 while (auto e = ::readdir(d.get())) {
986 if (e->d_type == DT_REG) {
987 result.emplace_back(
988 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
989 continue;
990 }
991 if (e->d_type == DT_DIR) {
992 if (e->d_name == "."sv || e->d_name == ".."sv) {
993 continue;
994 }
995 todoDirs.emplace_back(path::join(currDir, e->d_name));
996 continue;
997 }
998 }
999 } while (!todoDirs.empty());
1000 return result;
1001}
1002
1003bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001004 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001005 {
1006 std::unique_lock l(mLock);
1007 const auto& ifs = getIfsLocked(storage);
1008 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001009 return false;
1010 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001011 dataLoaderStub = ifs->dataLoaderStub;
1012 if (!dataLoaderStub) {
1013 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001014 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001015 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001016 return dataLoaderStub->start();
Songchun Fan3c82a302019-11-29 14:23:45 -08001017}
1018
1019void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001020 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1021 const auto path = entry.path().u8string();
1022 const auto name = entry.path().filename().u8string();
1023 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001024 continue;
1025 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001026 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001027 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001028 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001029 }
1030 }
1031}
1032
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001033bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001034 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001035 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001036
Songchun Fan3c82a302019-11-29 14:23:45 -08001037 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001038 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001039 if (!status.isOk()) {
1040 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1041 return false;
1042 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001043
1044 int cmd = controlParcel.cmd.release().release();
1045 int pendingReads = controlParcel.pendingReads.release().release();
1046 int logs = controlParcel.log.release().release();
1047 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001048
1049 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1050
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001051 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1052 path::join(mountTarget, constants().infoMdName));
1053 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001054 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1055 return false;
1056 }
1057
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001058 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001059 mNextId = std::max(mNextId, ifs->mountId + 1);
1060
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001061 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001062 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001063 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001064 const auto& loader = mount.loader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001065 dataLoaderParams.type = (android::content::pm::DataLoaderType)loader.type();
1066 dataLoaderParams.packageName = loader.package_name();
1067 dataLoaderParams.className = loader.class_name();
1068 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001069 }
1070
Songchun Fan3c82a302019-11-29 14:23:45 -08001071 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001072 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001073 while (auto e = ::readdir(d.get())) {
1074 if (e->d_type == DT_REG) {
1075 auto name = std::string_view(e->d_name);
1076 if (name.starts_with(constants().mountpointMdPrefix)) {
1077 bindPoints.emplace_back(name,
1078 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1079 ifs->control,
1080 path::join(mountTarget,
1081 name)));
1082 if (bindPoints.back().second.dest_path().empty() ||
1083 bindPoints.back().second.source_subdir().empty()) {
1084 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001085 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001086 }
1087 }
1088 } else if (e->d_type == DT_DIR) {
1089 if (e->d_name == "."sv || e->d_name == ".."sv) {
1090 continue;
1091 }
1092 auto name = std::string_view(e->d_name);
1093 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001094 int storageId;
1095 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1096 name.data() + name.size(), storageId);
1097 if (res.ec != std::errc{} || *res.ptr != '_') {
1098 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1099 << root;
1100 continue;
1101 }
1102 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001103 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001104 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001105 << " for mount " << root;
1106 continue;
1107 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001108 ifs->storages.insert_or_assign(storageId,
1109 IncFsMount::Storage{
1110 path::join(root, constants().mount, name)});
1111 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001112 }
1113 }
1114 }
1115
1116 if (ifs->storages.empty()) {
1117 LOG(WARNING) << "No valid storages in mount " << root;
1118 return false;
1119 }
1120
1121 int bindCount = 0;
1122 for (auto&& bp : bindPoints) {
1123 std::unique_lock l(mLock, std::defer_lock);
1124 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1125 std::move(*bp.second.mutable_source_subdir()),
1126 std::move(*bp.second.mutable_dest_path()),
1127 BindKind::Permanent, l);
1128 }
1129
1130 if (bindCount == 0) {
1131 LOG(WARNING) << "No valid bind points for mount " << root;
1132 deleteStorage(*ifs);
1133 return false;
1134 }
1135
Songchun Fan3c82a302019-11-29 14:23:45 -08001136 mMounts[ifs->mountId] = std::move(ifs);
1137 return true;
1138}
1139
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001140IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
1141 IncrementalService::IncFsMount& ifs, DataLoaderParamsParcel&& params,
1142 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001143 std::unique_lock l(ifs.lock);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001144 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001145 LOG(INFO) << "Skipped data loader preparation because it already exists";
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001146 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001147 }
1148
Songchun Fan3c82a302019-11-29 14:23:45 -08001149 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001150 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001151 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001152 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001153 base::unique_fd(::dup(ifs.control.pendingReads())));
1154 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001155 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001156
1157 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1158 std::move(fsControlParcel), externalListener);
1159 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001160}
1161
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001162template <class Duration>
1163static long elapsedMcs(Duration start, Duration end) {
1164 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1165}
1166
1167// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001168bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1169 std::string_view libDirRelativePath,
1170 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001171 auto start = Clock::now();
1172
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001173 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001174 if (!ifs) {
1175 LOG(ERROR) << "Invalid storage " << storage;
1176 return false;
1177 }
1178
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001179 // First prepare target directories if they don't exist yet
1180 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1181 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1182 << " errno: " << res;
1183 return false;
1184 }
1185
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001186 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001187 ZipArchiveHandle zipFileHandle;
1188 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001189 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1190 return false;
1191 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001192
1193 // Need a shared pointer: will be passing it into all unpacking jobs.
1194 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001195 void* cookie = nullptr;
1196 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001197 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001198 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1199 return false;
1200 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001201 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001202 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1203
1204 auto openZipTs = Clock::now();
1205
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001206 std::vector<Job> jobQueue;
1207 ZipEntry entry;
1208 std::string_view fileName;
1209 while (!Next(cookie, &entry, &fileName)) {
1210 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001211 continue;
1212 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001213
1214 auto startFileTs = Clock::now();
1215
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001216 const auto libName = path::basename(fileName);
1217 const auto targetLibPath = path::join(libDirRelativePath, libName);
1218 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1219 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001220 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1221 if (sEnablePerfLogging) {
1222 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1223 << "; skipping extraction, spent "
1224 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1225 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001226 continue;
1227 }
1228
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001229 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001230 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001231 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001232 .signature = {},
1233 // Metadata of the new lib file is its relative path
1234 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1235 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001236 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001237 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1238 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001239 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001240 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001241 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001242 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001243
1244 auto makeFileTs = Clock::now();
1245
Songchun Fanafaf6e92020-03-18 14:12:20 -07001246 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001247 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001248 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001249 LOG(INFO) << "incfs: Extracted " << libName
1250 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001251 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001252 continue;
1253 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001254
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001255 jobQueue.emplace_back([this, zipFile, entry, ifs = std::weak_ptr<IncFsMount>(ifs),
1256 libFileId, libPath = std::move(targetLibPath),
1257 makeFileTs]() mutable {
1258 extractZipFile(ifs.lock(), zipFile.get(), entry, libFileId, libPath, makeFileTs);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001259 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001260
1261 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001262 auto prepareJobTs = Clock::now();
1263 LOG(INFO) << "incfs: Processed " << libName << ": "
1264 << elapsedMcs(startFileTs, prepareJobTs)
1265 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1266 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001267 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001268 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001269
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001270 auto processedTs = Clock::now();
1271
1272 if (!jobQueue.empty()) {
1273 {
1274 std::lock_guard lock(mJobMutex);
1275 if (mRunning) {
1276 auto& existingJobs = mJobQueue[storage];
1277 if (existingJobs.empty()) {
1278 existingJobs = std::move(jobQueue);
1279 } else {
1280 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1281 std::move_iterator(jobQueue.end()));
1282 }
1283 }
1284 }
1285 mJobCondition.notify_all();
1286 }
1287
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001288 if (sEnablePerfLogging) {
1289 auto end = Clock::now();
1290 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1291 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1292 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001293 << " make files: " << elapsedMcs(openZipTs, processedTs)
1294 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001295 }
1296
1297 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001298}
1299
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001300void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1301 ZipEntry& entry, const incfs::FileId& libFileId,
1302 std::string_view targetLibPath,
1303 Clock::time_point scheduledTs) {
Yurii Zubrytskyi86321402020-04-09 19:22:30 -07001304 if (!ifs) {
1305 LOG(INFO) << "Skipping zip file " << targetLibPath << " extraction for an expired mount";
1306 return;
1307 }
1308
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001309 auto libName = path::basename(targetLibPath);
1310 auto startedTs = Clock::now();
1311
1312 // Write extracted data to new file
1313 // NOTE: don't zero-initialize memory, it may take a while for nothing
1314 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1315 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1316 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1317 return;
1318 }
1319
1320 auto extractFileTs = Clock::now();
1321
1322 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1323 if (!writeFd.ok()) {
1324 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1325 return;
1326 }
1327
1328 auto openFileTs = Clock::now();
1329 const int numBlocks =
1330 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1331 std::vector<IncFsDataBlock> instructions(numBlocks);
1332 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1333 for (int i = 0; i < numBlocks; i++) {
1334 const auto blockSize = std::min<uint16_t>(constants().blockSize, remainingData.size());
1335 instructions[i] = IncFsDataBlock{
1336 .fileFd = writeFd.get(),
1337 .pageIndex = static_cast<IncFsBlockIndex>(i),
1338 .compression = INCFS_COMPRESSION_KIND_NONE,
1339 .kind = INCFS_BLOCK_KIND_DATA,
1340 .dataSize = blockSize,
1341 .data = reinterpret_cast<const char*>(remainingData.data()),
1342 };
1343 remainingData = remainingData.subspan(blockSize);
1344 }
1345 auto prepareInstsTs = Clock::now();
1346
1347 size_t res = mIncFs->writeBlocks(instructions);
1348 if (res != instructions.size()) {
1349 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1350 return;
1351 }
1352
1353 if (sEnablePerfLogging) {
1354 auto endFileTs = Clock::now();
1355 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1356 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1357 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1358 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1359 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1360 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1361 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1362 }
1363}
1364
1365bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
1366 std::unique_lock lock(mJobMutex);
1367 mJobCondition.wait(lock, [this, storage] {
1368 return !mRunning ||
1369 (mPendingJobsStorage != storage && mJobQueue.find(storage) == mJobQueue.end());
1370 });
1371 return mPendingJobsStorage != storage && mJobQueue.find(storage) == mJobQueue.end();
1372}
1373
1374void IncrementalService::runJobProcessing() {
1375 for (;;) {
1376 std::unique_lock lock(mJobMutex);
1377 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1378 if (!mRunning) {
1379 return;
1380 }
1381
1382 auto it = mJobQueue.begin();
1383 mPendingJobsStorage = it->first;
1384 auto queue = std::move(it->second);
1385 mJobQueue.erase(it);
1386 lock.unlock();
1387
1388 for (auto&& job : queue) {
1389 job();
1390 }
1391
1392 lock.lock();
1393 mPendingJobsStorage = kInvalidStorageId;
1394 lock.unlock();
1395 mJobCondition.notify_all();
1396 }
1397}
1398
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001399void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001400 sp<IAppOpsCallback> listener;
1401 {
1402 std::unique_lock lock{mCallbacksLock};
1403 auto& cb = mCallbackRegistered[packageName];
1404 if (cb) {
1405 return;
1406 }
1407 cb = new AppOpsListener(*this, packageName);
1408 listener = cb;
1409 }
1410
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001411 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1412 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001413}
1414
1415bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1416 sp<IAppOpsCallback> listener;
1417 {
1418 std::unique_lock lock{mCallbacksLock};
1419 auto found = mCallbackRegistered.find(packageName);
1420 if (found == mCallbackRegistered.end()) {
1421 return false;
1422 }
1423 listener = found->second;
1424 mCallbackRegistered.erase(found);
1425 }
1426
1427 mAppOpsManager->stopWatchingMode(listener);
1428 return true;
1429}
1430
1431void IncrementalService::onAppOpChanged(const std::string& packageName) {
1432 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001433 return;
1434 }
1435
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001436 std::vector<IfsMountPtr> affected;
1437 {
1438 std::lock_guard l(mLock);
1439 affected.reserve(mMounts.size());
1440 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001441 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001442 affected.push_back(ifs);
1443 }
1444 }
1445 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001446 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001447 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001448 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001449}
1450
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001451IncrementalService::DataLoaderStub::~DataLoaderStub() {
1452 CHECK(mStatus == -1 || mStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED)
1453 << "Dataloader has to be destroyed prior to destructor: " << mId
1454 << ", status: " << mStatus;
1455}
1456
1457bool IncrementalService::DataLoaderStub::create() {
1458 bool created = false;
1459 auto status = mService.mDataLoaderManager->initializeDataLoader(mId, mParams, mControl, this,
1460 &created);
1461 if (!status.isOk() || !created) {
1462 LOG(ERROR) << "Failed to create a data loader for mount " << mId;
1463 return false;
1464 }
1465 return true;
1466}
1467
1468bool IncrementalService::DataLoaderStub::start() {
1469 if (mStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
1470 mStartRequested = true;
1471 return true;
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001472 }
1473
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001474 sp<IDataLoader> dataloader;
1475 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1476 if (!status.isOk()) {
1477 return false;
1478 }
1479 if (!dataloader) {
1480 return false;
1481 }
1482 status = dataloader->start(mId);
1483 if (!status.isOk()) {
1484 return false;
1485 }
1486 return true;
1487}
1488
1489void IncrementalService::DataLoaderStub::destroy() {
1490 mDestroyRequested = true;
1491 mService.mDataLoaderManager->destroyDataLoader(mId);
1492}
1493
1494binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
1495 if (mStatus == newStatus) {
1496 return binder::Status::ok();
1497 }
1498
1499 if (mListener) {
1500 // Give an external listener a chance to act before we destroy something.
1501 mListener->onStatusChanged(mountId, newStatus);
1502 }
1503
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001504 {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001505 std::unique_lock l(mService.mLock);
1506 const auto& ifs = mService.getIfsLocked(mountId);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001507 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001508 LOG(WARNING) << "Received data loader status " << int(newStatus)
1509 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001510 return binder::Status::ok();
1511 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001512 mStatus = newStatus;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001513
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001514 if (!mDestroyRequested && newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1515 mService.deleteStorageLocked(*ifs, std::move(l));
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001516 return binder::Status::ok();
1517 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001518 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001519
Songchun Fan3c82a302019-11-29 14:23:45 -08001520 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001521 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001522 if (mStartRequested) {
1523 start();
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001524 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001525 break;
1526 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001527 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001528 break;
1529 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001530 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001531 break;
1532 }
1533 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1534 break;
1535 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001536 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1537 break;
1538 }
1539 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1540 break;
1541 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001542 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1543 // Nothing for now. Rely on externalListener to handle this.
1544 break;
1545 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001546 default: {
1547 LOG(WARNING) << "Unknown data loader status: " << newStatus
1548 << " for mount: " << mountId;
1549 break;
1550 }
1551 }
1552
1553 return binder::Status::ok();
1554}
1555
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001556void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1557 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001558}
1559
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001560binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1561 bool enableReadLogs, int32_t* _aidl_return) {
1562 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1563 return binder::Status::ok();
1564}
1565
Songchun Fan3c82a302019-11-29 14:23:45 -08001566} // namespace android::incremental