blob: 400388e9326225f651c6a2efe95d3a6ae62c4885 [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()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800240 mIncrementalDir(rootDir) {
241 if (!mVold) {
242 LOG(FATAL) << "Vold service is unavailable";
243 }
Songchun Fan68645c42020-02-27 15:57:35 -0800244 if (!mDataLoaderManager) {
245 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800246 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700247 if (!mAppOpsManager) {
248 LOG(FATAL) << "AppOpsManager is unavailable";
249 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -0700250
251 mJobQueue.reserve(16);
252 mJobProcessor = std::thread([this]() { runJobProcessing(); });
253
Songchun Fan1124fd32020-02-10 12:49:41 -0800254 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800255}
256
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800257FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800258 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800259}
260
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 Buynytskyy0ea4ff42020-04-09 17:25:42 -0700352 /* TODO(b/151241369): restore data loaders on reboot.
Songchun Fan3c82a302019-11-29 14:23:45 -0800353 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800354 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800355 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800356 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
357 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800358 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800359 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800360 }
361 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800362 }).detach();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700363 */
Songchun Fan3c82a302019-11-29 14:23:45 -0800364}
365
366auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
367 for (;;) {
368 if (mNextId == kMaxStorageId) {
369 mNextId = 0;
370 }
371 auto id = ++mNextId;
372 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
373 if (inserted) {
374 return it;
375 }
376 }
377}
378
Songchun Fan1124fd32020-02-10 12:49:41 -0800379StorageId IncrementalService::createStorage(
380 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
381 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800382 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
383 if (!path::isAbsolute(mountPoint)) {
384 LOG(ERROR) << "path is not absolute: " << mountPoint;
385 return kInvalidStorageId;
386 }
387
388 auto mountNorm = path::normalize(mountPoint);
389 {
390 const auto id = findStorageId(mountNorm);
391 if (id != kInvalidStorageId) {
392 if (options & CreateOptions::OpenExisting) {
393 LOG(INFO) << "Opened existing storage " << id;
394 return id;
395 }
396 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
397 return kInvalidStorageId;
398 }
399 }
400
401 if (!(options & CreateOptions::CreateNew)) {
402 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
403 return kInvalidStorageId;
404 }
405
406 if (!path::isEmptyDir(mountNorm)) {
407 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
408 return kInvalidStorageId;
409 }
410 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
411 if (mountRoot.empty()) {
412 LOG(ERROR) << "Bad mount point";
413 return kInvalidStorageId;
414 }
415 // Make sure the code removes all crap it may create while still failing.
416 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
417 auto firstCleanupOnFailure =
418 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
419
420 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800421 const auto backing = path::join(mountRoot, constants().backing);
422 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800423 return kInvalidStorageId;
424 }
425
Songchun Fan3c82a302019-11-29 14:23:45 -0800426 IncFsMount::Control control;
427 {
428 std::lock_guard l(mMountOperationLock);
429 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800430
431 if (auto err = rmDirContent(backing.c_str())) {
432 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
433 return kInvalidStorageId;
434 }
435 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
436 return kInvalidStorageId;
437 }
438 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800439 if (!status.isOk()) {
440 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
441 return kInvalidStorageId;
442 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800443 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
444 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800445 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
446 return kInvalidStorageId;
447 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800448 int cmd = controlParcel.cmd.release().release();
449 int pendingReads = controlParcel.pendingReads.release().release();
450 int logs = controlParcel.log.release().release();
451 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800452 }
453
454 std::unique_lock l(mLock);
455 const auto mountIt = getStorageSlotLocked();
456 const auto mountId = mountIt->first;
457 l.unlock();
458
459 auto ifs =
460 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
461 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
462 // is the removal of the |ifs|.
463 firstCleanupOnFailure.release();
464
465 auto secondCleanup = [this, &l](auto itPtr) {
466 if (!l.owns_lock()) {
467 l.lock();
468 }
469 mMounts.erase(*itPtr);
470 };
471 auto secondCleanupOnFailure =
472 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
473
474 const auto storageIt = ifs->makeStorage(ifs->mountId);
475 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800476 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800477 return kInvalidStorageId;
478 }
479
480 {
481 metadata::Mount m;
482 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700483 m.mutable_loader()->set_type((int)dataLoaderParams.type);
484 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
485 m.mutable_loader()->set_class_name(dataLoaderParams.className);
486 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800487 const auto metadata = m.SerializeAsString();
488 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800489 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800490 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800491 if (auto err =
492 mIncFs->makeFile(ifs->control,
493 path::join(ifs->root, constants().mount,
494 constants().infoMdName),
495 0777, idFromMetadata(metadata),
496 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800497 LOG(ERROR) << "Saving mount metadata failed: " << -err;
498 return kInvalidStorageId;
499 }
500 }
501
502 const auto bk =
503 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800504 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
505 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800506 err < 0) {
507 LOG(ERROR) << "adding bind mount failed: " << -err;
508 return kInvalidStorageId;
509 }
510
511 // Done here as well, all data structures are in good state.
512 secondCleanupOnFailure.release();
513
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700514 auto dataLoaderStub =
515 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
516 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800517
518 mountIt->second = std::move(ifs);
519 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700520
521 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->create()) {
522 // failed to create data loader
523 LOG(ERROR) << "initializeDataLoader() failed";
524 deleteStorage(dataLoaderStub->id());
525 return kInvalidStorageId;
526 }
527
Songchun Fan3c82a302019-11-29 14:23:45 -0800528 LOG(INFO) << "created storage " << mountId;
529 return mountId;
530}
531
532StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
533 StorageId linkedStorage,
534 IncrementalService::CreateOptions options) {
535 if (!isValidMountTarget(mountPoint)) {
536 LOG(ERROR) << "Mount point is invalid or missing";
537 return kInvalidStorageId;
538 }
539
540 std::unique_lock l(mLock);
541 const auto& ifs = getIfsLocked(linkedStorage);
542 if (!ifs) {
543 LOG(ERROR) << "Ifs unavailable";
544 return kInvalidStorageId;
545 }
546
547 const auto mountIt = getStorageSlotLocked();
548 const auto storageId = mountIt->first;
549 const auto storageIt = ifs->makeStorage(storageId);
550 if (storageIt == ifs->storages.end()) {
551 LOG(ERROR) << "Can't create a new storage";
552 mMounts.erase(mountIt);
553 return kInvalidStorageId;
554 }
555
556 l.unlock();
557
558 const auto bk =
559 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800560 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
561 std::string(storageIt->second.name), path::normalize(mountPoint),
562 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800563 err < 0) {
564 LOG(ERROR) << "bindMount failed with error: " << err;
565 return kInvalidStorageId;
566 }
567
568 mountIt->second = ifs;
569 return storageId;
570}
571
572IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
573 std::string_view path) const {
574 auto bindPointIt = mBindsByPath.upper_bound(path);
575 if (bindPointIt == mBindsByPath.begin()) {
576 return mBindsByPath.end();
577 }
578 --bindPointIt;
579 if (!path::startsWith(path, bindPointIt->first)) {
580 return mBindsByPath.end();
581 }
582 return bindPointIt;
583}
584
585StorageId IncrementalService::findStorageId(std::string_view path) const {
586 std::lock_guard l(mLock);
587 auto it = findStorageLocked(path);
588 if (it == mBindsByPath.end()) {
589 return kInvalidStorageId;
590 }
591 return it->second->second.storage;
592}
593
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700594int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
595 const auto ifs = getIfs(storageId);
596 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700597 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700598 return -EINVAL;
599 }
600
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700601 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700602 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700603 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
604 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700605 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700606 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700607 return fromBinderStatus(status);
608 }
609 }
610
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700611 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
612 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
613 return fromBinderStatus(status);
614 }
615
616 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700617 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700618 }
619
620 return 0;
621}
622
623binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700624 using unique_fd = ::android::base::unique_fd;
625 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700626 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
627 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
628 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700629 if (logsFd >= 0) {
630 control.log.reset(unique_fd(dup(logsFd)));
631 }
632
633 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700634 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700635}
636
Songchun Fan3c82a302019-11-29 14:23:45 -0800637void IncrementalService::deleteStorage(StorageId storageId) {
638 const auto ifs = getIfs(storageId);
639 if (!ifs) {
640 return;
641 }
642 deleteStorage(*ifs);
643}
644
645void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
646 std::unique_lock l(ifs.lock);
647 deleteStorageLocked(ifs, std::move(l));
648}
649
650void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
651 std::unique_lock<std::mutex>&& ifsLock) {
652 const auto storages = std::move(ifs.storages);
653 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
654 const auto bindPoints = ifs.bindPoints;
655 ifsLock.unlock();
656
657 std::lock_guard l(mLock);
658 for (auto&& [id, _] : storages) {
659 if (id != ifs.mountId) {
660 mMounts.erase(id);
661 }
662 }
663 for (auto&& [path, _] : bindPoints) {
664 mBindsByPath.erase(path);
665 }
666 mMounts.erase(ifs.mountId);
667}
668
669StorageId IncrementalService::openStorage(std::string_view pathInMount) {
670 if (!path::isAbsolute(pathInMount)) {
671 return kInvalidStorageId;
672 }
673
674 return findStorageId(path::normalize(pathInMount));
675}
676
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800677FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800678 const auto ifs = getIfs(storage);
679 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800680 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800681 }
682 std::unique_lock l(ifs->lock);
683 auto storageIt = ifs->storages.find(storage);
684 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800685 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800686 }
687 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800688 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800689 }
690 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
691 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800692 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800693}
694
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800695std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800696 StorageId storage, std::string_view subpath) const {
697 auto name = path::basename(subpath);
698 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800699 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800700 }
701 auto dir = path::dirname(subpath);
702 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800703 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800704 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800705 auto id = nodeFor(storage, dir);
706 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800707}
708
709IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
710 std::lock_guard l(mLock);
711 return getIfsLocked(storage);
712}
713
714const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
715 auto it = mMounts.find(storage);
716 if (it == mMounts.end()) {
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700717 static const android::base::NoDestructor<IfsMountPtr> kEmpty{};
718 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800719 }
720 return it->second;
721}
722
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800723int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
724 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800725 if (!isValidMountTarget(target)) {
726 return -EINVAL;
727 }
728
729 const auto ifs = getIfs(storage);
730 if (!ifs) {
731 return -EINVAL;
732 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800733
Songchun Fan3c82a302019-11-29 14:23:45 -0800734 std::unique_lock l(ifs->lock);
735 const auto storageInfo = ifs->storages.find(storage);
736 if (storageInfo == ifs->storages.end()) {
737 return -EINVAL;
738 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700739 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
740 if (normSource.empty()) {
741 return -EINVAL;
742 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800743 l.unlock();
744 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800745 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
746 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800747}
748
749int IncrementalService::unbind(StorageId storage, std::string_view target) {
750 if (!path::isAbsolute(target)) {
751 return -EINVAL;
752 }
753
754 LOG(INFO) << "Removing bind point " << target;
755
756 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
757 // otherwise there's a chance to unmount something completely unrelated
758 const auto norm = path::normalize(target);
759 std::unique_lock l(mLock);
760 const auto storageIt = mBindsByPath.find(norm);
761 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
762 return -EINVAL;
763 }
764 const auto bindIt = storageIt->second;
765 const auto storageId = bindIt->second.storage;
766 const auto ifs = getIfsLocked(storageId);
767 if (!ifs) {
768 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
769 << " is missing";
770 return -EFAULT;
771 }
772 mBindsByPath.erase(storageIt);
773 l.unlock();
774
775 mVold->unmountIncFs(bindIt->first);
776 std::unique_lock l2(ifs->lock);
777 if (ifs->bindPoints.size() <= 1) {
778 ifs->bindPoints.clear();
779 deleteStorageLocked(*ifs, std::move(l2));
780 } else {
781 const std::string savedFile = std::move(bindIt->second.savedFilename);
782 ifs->bindPoints.erase(bindIt);
783 l2.unlock();
784 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800785 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800786 }
787 }
788 return 0;
789}
790
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700791std::string IncrementalService::normalizePathToStorageLocked(
792 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
793 std::string normPath;
794 if (path::isAbsolute(path)) {
795 normPath = path::normalize(path);
796 if (!path::startsWith(normPath, storageIt->second.name)) {
797 return {};
798 }
799 } else {
800 normPath = path::normalize(path::join(storageIt->second.name, path));
801 }
802 return normPath;
803}
804
805std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800806 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700807 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800808 const auto storageInfo = ifs->storages.find(storage);
809 if (storageInfo == ifs->storages.end()) {
810 return {};
811 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700812 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800813}
814
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800815int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
816 incfs::NewFileParams params) {
817 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800818 std::string normPath = normalizePathToStorage(ifs, storage, path);
819 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700820 LOG(ERROR) << "Internal error: storageId " << storage
821 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800822 return -EINVAL;
823 }
824 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800825 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700826 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800827 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800828 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800829 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800830 }
831 return -EINVAL;
832}
833
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800834int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800835 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800836 std::string normPath = normalizePathToStorage(ifs, storageId, path);
837 if (normPath.empty()) {
838 return -EINVAL;
839 }
840 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800841 }
842 return -EINVAL;
843}
844
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800845int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800846 const auto ifs = getIfs(storageId);
847 if (!ifs) {
848 return -EINVAL;
849 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800850 std::string normPath = normalizePathToStorage(ifs, storageId, path);
851 if (normPath.empty()) {
852 return -EINVAL;
853 }
854 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800855 if (err == -EEXIST) {
856 return 0;
857 } else if (err != -ENOENT) {
858 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800859 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800860 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800861 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800862 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800863 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800864}
865
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800866int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
867 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700868 auto ifsSrc = getIfs(sourceStorageId);
869 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
870 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800871 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
872 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
873 if (normOldPath.empty() || normNewPath.empty()) {
874 return -EINVAL;
875 }
876 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800877 }
878 return -EINVAL;
879}
880
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800881int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800882 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800883 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
884 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800885 }
886 return -EINVAL;
887}
888
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800889int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
890 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800891 std::string&& target, BindKind kind,
892 std::unique_lock<std::mutex>& mainLock) {
893 if (!isValidMountTarget(target)) {
894 return -EINVAL;
895 }
896
897 std::string mdFileName;
898 if (kind != BindKind::Temporary) {
899 metadata::BindPoint bp;
900 bp.set_storage_id(storage);
901 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800902 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800903 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800904 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800905 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800906 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800907 auto node =
908 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
909 0444, idFromMetadata(metadata),
910 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
911 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800912 return int(node);
913 }
914 }
915
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800916 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800917 std::move(target), kind, mainLock);
918}
919
920int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800921 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800922 std::string&& target, BindKind kind,
923 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800924 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800925 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800926 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800927 if (!status.isOk()) {
928 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
929 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
930 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
931 : status.serviceSpecificErrorCode() == 0
932 ? -EFAULT
933 : status.serviceSpecificErrorCode()
934 : -EIO;
935 }
936 }
937
938 if (!mainLock.owns_lock()) {
939 mainLock.lock();
940 }
941 std::lock_guard l(ifs.lock);
942 const auto [it, _] =
943 ifs.bindPoints.insert_or_assign(target,
944 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800945 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800946 mBindsByPath[std::move(target)] = it;
947 return 0;
948}
949
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800950RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800951 const auto ifs = getIfs(storage);
952 if (!ifs) {
953 return {};
954 }
955 return mIncFs->getMetadata(ifs->control, node);
956}
957
958std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
959 const auto ifs = getIfs(storage);
960 if (!ifs) {
961 return {};
962 }
963
964 std::unique_lock l(ifs->lock);
965 auto subdirIt = ifs->storages.find(storage);
966 if (subdirIt == ifs->storages.end()) {
967 return {};
968 }
969 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
970 l.unlock();
971
972 const auto prefixSize = dir.size() + 1;
973 std::vector<std::string> todoDirs{std::move(dir)};
974 std::vector<std::string> result;
975 do {
976 auto currDir = std::move(todoDirs.back());
977 todoDirs.pop_back();
978
979 auto d =
980 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
981 while (auto e = ::readdir(d.get())) {
982 if (e->d_type == DT_REG) {
983 result.emplace_back(
984 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
985 continue;
986 }
987 if (e->d_type == DT_DIR) {
988 if (e->d_name == "."sv || e->d_name == ".."sv) {
989 continue;
990 }
991 todoDirs.emplace_back(path::join(currDir, e->d_name));
992 continue;
993 }
994 }
995 } while (!todoDirs.empty());
996 return result;
997}
998
999bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001000 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001001 {
1002 std::unique_lock l(mLock);
1003 const auto& ifs = getIfsLocked(storage);
1004 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001005 return false;
1006 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001007 dataLoaderStub = ifs->dataLoaderStub;
1008 if (!dataLoaderStub) {
1009 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001010 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001011 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001012 return dataLoaderStub->start();
Songchun Fan3c82a302019-11-29 14:23:45 -08001013}
1014
1015void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001016 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1017 const auto path = entry.path().u8string();
1018 const auto name = entry.path().filename().u8string();
1019 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001020 continue;
1021 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001022 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001023 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001024 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001025 }
1026 }
1027}
1028
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001029bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001030 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001031 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001032
Songchun Fan3c82a302019-11-29 14:23:45 -08001033 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001034 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001035 if (!status.isOk()) {
1036 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1037 return false;
1038 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001039
1040 int cmd = controlParcel.cmd.release().release();
1041 int pendingReads = controlParcel.pendingReads.release().release();
1042 int logs = controlParcel.log.release().release();
1043 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001044
1045 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1046
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001047 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1048 path::join(mountTarget, constants().infoMdName));
1049 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001050 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1051 return false;
1052 }
1053
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001054 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001055 mNextId = std::max(mNextId, ifs->mountId + 1);
1056
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001057 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001058 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001059 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001060 const auto& loader = mount.loader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001061 dataLoaderParams.type = (android::content::pm::DataLoaderType)loader.type();
1062 dataLoaderParams.packageName = loader.package_name();
1063 dataLoaderParams.className = loader.class_name();
1064 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001065 }
1066
Songchun Fan3c82a302019-11-29 14:23:45 -08001067 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001068 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001069 while (auto e = ::readdir(d.get())) {
1070 if (e->d_type == DT_REG) {
1071 auto name = std::string_view(e->d_name);
1072 if (name.starts_with(constants().mountpointMdPrefix)) {
1073 bindPoints.emplace_back(name,
1074 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1075 ifs->control,
1076 path::join(mountTarget,
1077 name)));
1078 if (bindPoints.back().second.dest_path().empty() ||
1079 bindPoints.back().second.source_subdir().empty()) {
1080 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001081 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001082 }
1083 }
1084 } else if (e->d_type == DT_DIR) {
1085 if (e->d_name == "."sv || e->d_name == ".."sv) {
1086 continue;
1087 }
1088 auto name = std::string_view(e->d_name);
1089 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001090 int storageId;
1091 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1092 name.data() + name.size(), storageId);
1093 if (res.ec != std::errc{} || *res.ptr != '_') {
1094 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1095 << root;
1096 continue;
1097 }
1098 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001099 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001100 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001101 << " for mount " << root;
1102 continue;
1103 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001104 ifs->storages.insert_or_assign(storageId,
1105 IncFsMount::Storage{
1106 path::join(root, constants().mount, name)});
1107 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001108 }
1109 }
1110 }
1111
1112 if (ifs->storages.empty()) {
1113 LOG(WARNING) << "No valid storages in mount " << root;
1114 return false;
1115 }
1116
1117 int bindCount = 0;
1118 for (auto&& bp : bindPoints) {
1119 std::unique_lock l(mLock, std::defer_lock);
1120 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1121 std::move(*bp.second.mutable_source_subdir()),
1122 std::move(*bp.second.mutable_dest_path()),
1123 BindKind::Permanent, l);
1124 }
1125
1126 if (bindCount == 0) {
1127 LOG(WARNING) << "No valid bind points for mount " << root;
1128 deleteStorage(*ifs);
1129 return false;
1130 }
1131
Songchun Fan3c82a302019-11-29 14:23:45 -08001132 mMounts[ifs->mountId] = std::move(ifs);
1133 return true;
1134}
1135
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001136IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
1137 IncrementalService::IncFsMount& ifs, DataLoaderParamsParcel&& params,
1138 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001139 std::unique_lock l(ifs.lock);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001140 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001141 LOG(INFO) << "Skipped data loader preparation because it already exists";
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001142 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001143 }
1144
Songchun Fan3c82a302019-11-29 14:23:45 -08001145 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001146 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001147 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001148 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001149 base::unique_fd(::dup(ifs.control.pendingReads())));
1150 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001151 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001152
1153 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1154 std::move(fsControlParcel), externalListener);
1155 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001156}
1157
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001158template <class Duration>
1159static long elapsedMcs(Duration start, Duration end) {
1160 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1161}
1162
1163// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001164bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1165 std::string_view libDirRelativePath,
1166 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001167 auto start = Clock::now();
1168
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001169 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001170 if (!ifs) {
1171 LOG(ERROR) << "Invalid storage " << storage;
1172 return false;
1173 }
1174
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001175 // First prepare target directories if they don't exist yet
1176 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1177 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1178 << " errno: " << res;
1179 return false;
1180 }
1181
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001182 auto mkDirsTs = Clock::now();
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001183 ZipArchiveHandle zipFileHandle;
1184 if (OpenArchive(path::c_str(apkFullPath), &zipFileHandle)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001185 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1186 return false;
1187 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001188
1189 // Need a shared pointer: will be passing it into all unpacking jobs.
1190 std::shared_ptr<ZipArchive> zipFile(zipFileHandle, [](ZipArchiveHandle h) { CloseArchive(h); });
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001191 void* cookie = nullptr;
1192 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001193 if (StartIteration(zipFile.get(), &cookie, libFilePrefix, constants().libSuffix)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001194 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1195 return false;
1196 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001197 auto endIteration = [](void* cookie) { EndIteration(cookie); };
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001198 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1199
1200 auto openZipTs = Clock::now();
1201
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001202 std::vector<Job> jobQueue;
1203 ZipEntry entry;
1204 std::string_view fileName;
1205 while (!Next(cookie, &entry, &fileName)) {
1206 if (fileName.empty()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001207 continue;
1208 }
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001209
1210 auto startFileTs = Clock::now();
1211
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001212 const auto libName = path::basename(fileName);
1213 const auto targetLibPath = path::join(libDirRelativePath, libName);
1214 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1215 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001216 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1217 if (sEnablePerfLogging) {
1218 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1219 << "; skipping extraction, spent "
1220 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1221 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001222 continue;
1223 }
1224
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001225 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001226 incfs::NewFileParams libFileParams = {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001227 .size = entry.uncompressed_length,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001228 .signature = {},
1229 // Metadata of the new lib file is its relative path
1230 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1231 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001232 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001233 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1234 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001235 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001236 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001237 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001238 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001239
1240 auto makeFileTs = Clock::now();
1241
Songchun Fanafaf6e92020-03-18 14:12:20 -07001242 // If it is a zero-byte file, skip data writing
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001243 if (entry.uncompressed_length == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001244 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001245 LOG(INFO) << "incfs: Extracted " << libName
1246 << "(0 bytes): " << elapsedMcs(startFileTs, makeFileTs) << "mcs";
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001247 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001248 continue;
1249 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001250
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001251 jobQueue.emplace_back([this, zipFile, entry, ifs, libFileId,
1252 libPath = std::move(targetLibPath), makeFileTs]() mutable {
1253 extractZipFile(ifs, zipFile.get(), entry, libFileId, libPath, makeFileTs);
1254 });
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001255
1256 if (sEnablePerfLogging) {
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001257 auto prepareJobTs = Clock::now();
1258 LOG(INFO) << "incfs: Processed " << libName << ": "
1259 << elapsedMcs(startFileTs, prepareJobTs)
1260 << "mcs, make file: " << elapsedMcs(startFileTs, makeFileTs)
1261 << " prepare job: " << elapsedMcs(makeFileTs, prepareJobTs);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001262 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001263 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001264
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001265 auto processedTs = Clock::now();
1266
1267 if (!jobQueue.empty()) {
1268 {
1269 std::lock_guard lock(mJobMutex);
1270 if (mRunning) {
1271 auto& existingJobs = mJobQueue[storage];
1272 if (existingJobs.empty()) {
1273 existingJobs = std::move(jobQueue);
1274 } else {
1275 existingJobs.insert(existingJobs.end(), std::move_iterator(jobQueue.begin()),
1276 std::move_iterator(jobQueue.end()));
1277 }
1278 }
1279 }
1280 mJobCondition.notify_all();
1281 }
1282
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001283 if (sEnablePerfLogging) {
1284 auto end = Clock::now();
1285 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1286 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1287 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001288 << " make files: " << elapsedMcs(openZipTs, processedTs)
1289 << " schedule jobs: " << elapsedMcs(processedTs, end);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001290 }
1291
1292 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001293}
1294
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001295void IncrementalService::extractZipFile(const IfsMountPtr& ifs, ZipArchiveHandle zipFile,
1296 ZipEntry& entry, const incfs::FileId& libFileId,
1297 std::string_view targetLibPath,
1298 Clock::time_point scheduledTs) {
1299 auto libName = path::basename(targetLibPath);
1300 auto startedTs = Clock::now();
1301
1302 // Write extracted data to new file
1303 // NOTE: don't zero-initialize memory, it may take a while for nothing
1304 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[entry.uncompressed_length]);
1305 if (ExtractToMemory(zipFile, &entry, libData.get(), entry.uncompressed_length)) {
1306 LOG(ERROR) << "Failed to extract native lib zip entry: " << libName;
1307 return;
1308 }
1309
1310 auto extractFileTs = Clock::now();
1311
1312 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1313 if (!writeFd.ok()) {
1314 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
1315 return;
1316 }
1317
1318 auto openFileTs = Clock::now();
1319 const int numBlocks =
1320 (entry.uncompressed_length + constants().blockSize - 1) / constants().blockSize;
1321 std::vector<IncFsDataBlock> instructions(numBlocks);
1322 auto remainingData = std::span(libData.get(), entry.uncompressed_length);
1323 for (int i = 0; i < numBlocks; i++) {
1324 const auto blockSize = std::min<uint16_t>(constants().blockSize, remainingData.size());
1325 instructions[i] = IncFsDataBlock{
1326 .fileFd = writeFd.get(),
1327 .pageIndex = static_cast<IncFsBlockIndex>(i),
1328 .compression = INCFS_COMPRESSION_KIND_NONE,
1329 .kind = INCFS_BLOCK_KIND_DATA,
1330 .dataSize = blockSize,
1331 .data = reinterpret_cast<const char*>(remainingData.data()),
1332 };
1333 remainingData = remainingData.subspan(blockSize);
1334 }
1335 auto prepareInstsTs = Clock::now();
1336
1337 size_t res = mIncFs->writeBlocks(instructions);
1338 if (res != instructions.size()) {
1339 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
1340 return;
1341 }
1342
1343 if (sEnablePerfLogging) {
1344 auto endFileTs = Clock::now();
1345 LOG(INFO) << "incfs: Extracted " << libName << "(" << entry.compressed_length << " -> "
1346 << entry.uncompressed_length << " bytes): " << elapsedMcs(startedTs, endFileTs)
1347 << "mcs, scheduling delay: " << elapsedMcs(scheduledTs, startedTs)
1348 << " extract: " << elapsedMcs(startedTs, extractFileTs)
1349 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1350 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1351 << " write: " << elapsedMcs(prepareInstsTs, endFileTs);
1352 }
1353}
1354
1355bool IncrementalService::waitForNativeBinariesExtraction(StorageId storage) {
1356 std::unique_lock lock(mJobMutex);
1357 mJobCondition.wait(lock, [this, storage] {
1358 return !mRunning ||
1359 (mPendingJobsStorage != storage && mJobQueue.find(storage) == mJobQueue.end());
1360 });
1361 return mPendingJobsStorage != storage && mJobQueue.find(storage) == mJobQueue.end();
1362}
1363
1364void IncrementalService::runJobProcessing() {
1365 for (;;) {
1366 std::unique_lock lock(mJobMutex);
1367 mJobCondition.wait(lock, [this]() { return !mRunning || !mJobQueue.empty(); });
1368 if (!mRunning) {
1369 return;
1370 }
1371
1372 auto it = mJobQueue.begin();
1373 mPendingJobsStorage = it->first;
1374 auto queue = std::move(it->second);
1375 mJobQueue.erase(it);
1376 lock.unlock();
1377
1378 for (auto&& job : queue) {
1379 job();
1380 }
1381
1382 lock.lock();
1383 mPendingJobsStorage = kInvalidStorageId;
1384 lock.unlock();
1385 mJobCondition.notify_all();
1386 }
1387}
1388
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001389void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001390 sp<IAppOpsCallback> listener;
1391 {
1392 std::unique_lock lock{mCallbacksLock};
1393 auto& cb = mCallbackRegistered[packageName];
1394 if (cb) {
1395 return;
1396 }
1397 cb = new AppOpsListener(*this, packageName);
1398 listener = cb;
1399 }
1400
Yurii Zubrytskyida208012020-04-07 15:35:21 -07001401 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS,
1402 String16(packageName.c_str()), listener);
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001403}
1404
1405bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1406 sp<IAppOpsCallback> listener;
1407 {
1408 std::unique_lock lock{mCallbacksLock};
1409 auto found = mCallbackRegistered.find(packageName);
1410 if (found == mCallbackRegistered.end()) {
1411 return false;
1412 }
1413 listener = found->second;
1414 mCallbackRegistered.erase(found);
1415 }
1416
1417 mAppOpsManager->stopWatchingMode(listener);
1418 return true;
1419}
1420
1421void IncrementalService::onAppOpChanged(const std::string& packageName) {
1422 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001423 return;
1424 }
1425
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001426 std::vector<IfsMountPtr> affected;
1427 {
1428 std::lock_guard l(mLock);
1429 affected.reserve(mMounts.size());
1430 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001431 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001432 affected.push_back(ifs);
1433 }
1434 }
1435 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001436 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001437 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001438 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001439}
1440
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001441IncrementalService::DataLoaderStub::~DataLoaderStub() {
1442 CHECK(mStatus == -1 || mStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED)
1443 << "Dataloader has to be destroyed prior to destructor: " << mId
1444 << ", status: " << mStatus;
1445}
1446
1447bool IncrementalService::DataLoaderStub::create() {
1448 bool created = false;
1449 auto status = mService.mDataLoaderManager->initializeDataLoader(mId, mParams, mControl, this,
1450 &created);
1451 if (!status.isOk() || !created) {
1452 LOG(ERROR) << "Failed to create a data loader for mount " << mId;
1453 return false;
1454 }
1455 return true;
1456}
1457
1458bool IncrementalService::DataLoaderStub::start() {
1459 if (mStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
1460 mStartRequested = true;
1461 return true;
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001462 }
1463
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001464 sp<IDataLoader> dataloader;
1465 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1466 if (!status.isOk()) {
1467 return false;
1468 }
1469 if (!dataloader) {
1470 return false;
1471 }
1472 status = dataloader->start(mId);
1473 if (!status.isOk()) {
1474 return false;
1475 }
1476 return true;
1477}
1478
1479void IncrementalService::DataLoaderStub::destroy() {
1480 mDestroyRequested = true;
1481 mService.mDataLoaderManager->destroyDataLoader(mId);
1482}
1483
1484binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
1485 if (mStatus == newStatus) {
1486 return binder::Status::ok();
1487 }
1488
1489 if (mListener) {
1490 // Give an external listener a chance to act before we destroy something.
1491 mListener->onStatusChanged(mountId, newStatus);
1492 }
1493
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001494 {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001495 std::unique_lock l(mService.mLock);
1496 const auto& ifs = mService.getIfsLocked(mountId);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001497 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001498 LOG(WARNING) << "Received data loader status " << int(newStatus)
1499 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001500 return binder::Status::ok();
1501 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001502 mStatus = newStatus;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001503
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001504 if (!mDestroyRequested && newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1505 mService.deleteStorageLocked(*ifs, std::move(l));
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001506 return binder::Status::ok();
1507 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001508 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001509
Songchun Fan3c82a302019-11-29 14:23:45 -08001510 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001511 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001512 if (mStartRequested) {
1513 start();
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001514 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001515 break;
1516 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001517 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001518 break;
1519 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001520 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001521 break;
1522 }
1523 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1524 break;
1525 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001526 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1527 break;
1528 }
1529 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1530 break;
1531 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001532 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1533 // Nothing for now. Rely on externalListener to handle this.
1534 break;
1535 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001536 default: {
1537 LOG(WARNING) << "Unknown data loader status: " << newStatus
1538 << " for mount: " << mountId;
1539 break;
1540 }
1541 }
1542
1543 return binder::Status::ok();
1544}
1545
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001546void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1547 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001548}
1549
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001550binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1551 bool enableReadLogs, int32_t* _aidl_return) {
1552 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1553 return binder::Status::ok();
1554}
1555
Songchun Fan3c82a302019-11-29 14:23:45 -08001556} // namespace android::incremental