blob: eb65a2ddc5f1927c50f9f7b1cb9094d53785e104 [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>
29#include <androidfw/ZipFileRO.h>
30#include <androidfw/ZipUtils.h>
31#include <binder/BinderService.h>
Jooyung Han66c567a2020-03-07 21:47:09 +090032#include <binder/Nullable.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080033#include <binder/ParcelFileDescriptor.h>
34#include <binder/Status.h>
35#include <sys/stat.h>
36#include <uuid/uuid.h>
37#include <zlib.h>
38
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -070039#include <charconv>
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080040#include <ctime>
Songchun Fan1124fd32020-02-10 12:49:41 -080041#include <filesystem>
Songchun Fan3c82a302019-11-29 14:23:45 -080042#include <iterator>
43#include <span>
44#include <stack>
45#include <thread>
46#include <type_traits>
47
48#include "Metadata.pb.h"
49
50using namespace std::literals;
51using namespace android::content::pm;
Songchun Fan1124fd32020-02-10 12:49:41 -080052namespace fs = std::filesystem;
Songchun Fan3c82a302019-11-29 14:23:45 -080053
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070054constexpr const char* kDataUsageStats = "android.permission.LOADER_USAGE_STATS";
Alex Buynytskyy119de1f2020-04-08 16:15:35 -070055constexpr const char* kOpUsage = "android:loader_usage_stats";
Alex Buynytskyy96e350b2020-04-02 20:03:47 -070056
Songchun Fan3c82a302019-11-29 14:23:45 -080057namespace android::incremental {
58
59namespace {
60
61using IncrementalFileSystemControlParcel =
62 ::android::os::incremental::IncrementalFileSystemControlParcel;
63
64struct Constants {
65 static constexpr auto backing = "backing_store"sv;
66 static constexpr auto mount = "mount"sv;
Songchun Fan1124fd32020-02-10 12:49:41 -080067 static constexpr auto mountKeyPrefix = "MT_"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080068 static constexpr auto storagePrefix = "st"sv;
69 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
70 static constexpr auto infoMdName = ".info"sv;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -080071 static constexpr auto libDir = "lib"sv;
72 static constexpr auto libSuffix = ".so"sv;
73 static constexpr auto blockSize = 4096;
Songchun Fan3c82a302019-11-29 14:23:45 -080074};
75
76static const Constants& constants() {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -070077 static constexpr Constants c;
Songchun Fan3c82a302019-11-29 14:23:45 -080078 return c;
79}
80
81template <base::LogSeverity level = base::ERROR>
82bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
83 auto cstr = path::c_str(name);
84 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080085 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080086 PLOG(level) << "Can't create directory '" << name << '\'';
87 return false;
88 }
89 struct stat st;
90 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
91 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
92 return false;
93 }
94 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080095 if (::chmod(cstr, mode)) {
96 PLOG(level) << "Changing permission failed for '" << name << '\'';
97 return false;
98 }
99
Songchun Fan3c82a302019-11-29 14:23:45 -0800100 return true;
101}
102
103static std::string toMountKey(std::string_view path) {
104 if (path.empty()) {
105 return "@none";
106 }
107 if (path == "/"sv) {
108 return "@root";
109 }
110 if (path::isAbsolute(path)) {
111 path.remove_prefix(1);
112 }
113 std::string res(path);
114 std::replace(res.begin(), res.end(), '/', '_');
115 std::replace(res.begin(), res.end(), '@', '_');
Songchun Fan1124fd32020-02-10 12:49:41 -0800116 return std::string(constants().mountKeyPrefix) + res;
Songchun Fan3c82a302019-11-29 14:23:45 -0800117}
118
119static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
120 std::string_view path) {
121 auto mountKey = toMountKey(path);
122 const auto prefixSize = mountKey.size();
123 for (int counter = 0; counter < 1000;
124 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
125 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800126 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800127 return {mountKey, mountRoot};
128 }
129 }
130 return {};
131}
132
133template <class ProtoMessage, class Control>
134static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
135 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800136 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800137 ProtoMessage message;
138 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
139}
140
141static bool isValidMountTarget(std::string_view path) {
142 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
143}
144
145std::string makeBindMdName() {
146 static constexpr auto uuidStringSize = 36;
147
148 uuid_t guid;
149 uuid_generate(guid);
150
151 std::string name;
152 const auto prefixSize = constants().mountpointMdPrefix.size();
153 name.reserve(prefixSize + uuidStringSize);
154
155 name = constants().mountpointMdPrefix;
156 name.resize(prefixSize + uuidStringSize);
157 uuid_unparse(guid, name.data() + prefixSize);
158
159 return name;
160}
161} // namespace
162
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700163const bool IncrementalService::sEnablePerfLogging =
164 android::base::GetBoolProperty("incremental.perflogging", false);
165
Songchun Fan3c82a302019-11-29 14:23:45 -0800166IncrementalService::IncFsMount::~IncFsMount() {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700167 if (dataLoaderStub) {
168 dataLoaderStub->destroy();
169 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800170 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
171 for (auto&& [target, _] : bindPoints) {
172 LOG(INFO) << "\tbind: " << target;
173 incrementalService.mVold->unmountIncFs(target);
174 }
175 LOG(INFO) << "\troot: " << root;
176 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
177 cleanupFilesystem(root);
178}
179
180auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800181 std::string name;
182 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
183 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
184 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800185 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
186 constants().storagePrefix.data(), id, no);
187 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800188 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800189 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800190 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
191 } else if (err != EEXIST) {
192 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
193 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800194 }
195 }
196 nextStorageDirNo = 0;
197 return storages.end();
198}
199
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800200static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
201 return {::opendir(path), ::closedir};
202}
203
204static int rmDirContent(const char* path) {
205 auto dir = openDir(path);
206 if (!dir) {
207 return -EINVAL;
208 }
209 while (auto entry = ::readdir(dir.get())) {
210 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
211 continue;
212 }
213 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
214 if (entry->d_type == DT_DIR) {
215 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
216 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
217 return err;
218 }
219 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
220 PLOG(WARNING) << "Failed to rmdir " << fullPath;
221 return err;
222 }
223 } else {
224 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
225 PLOG(WARNING) << "Failed to delete " << fullPath;
226 return err;
227 }
228 }
229 }
230 return 0;
231}
232
Songchun Fan3c82a302019-11-29 14:23:45 -0800233void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800234 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800235 ::rmdir(path::join(root, constants().backing).c_str());
236 ::rmdir(path::join(root, constants().mount).c_str());
237 ::rmdir(path::c_str(root));
238}
239
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800240IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800241 : mVold(sm.getVoldService()),
Songchun Fan68645c42020-02-27 15:57:35 -0800242 mDataLoaderManager(sm.getDataLoaderManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800243 mIncFs(sm.getIncFs()),
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700244 mAppOpsManager(sm.getAppOpsManager()),
Songchun Fan3c82a302019-11-29 14:23:45 -0800245 mIncrementalDir(rootDir) {
246 if (!mVold) {
247 LOG(FATAL) << "Vold service is unavailable";
248 }
Songchun Fan68645c42020-02-27 15:57:35 -0800249 if (!mDataLoaderManager) {
250 LOG(FATAL) << "DataLoaderManagerService is unavailable";
Songchun Fan3c82a302019-11-29 14:23:45 -0800251 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700252 if (!mAppOpsManager) {
253 LOG(FATAL) << "AppOpsManager is unavailable";
254 }
Songchun Fan1124fd32020-02-10 12:49:41 -0800255 mountExistingImages();
Songchun Fan3c82a302019-11-29 14:23:45 -0800256}
257
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800258FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800259 return IncFs_FileIdFromMetadata({(const char*)metadata.data(), metadata.size()});
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800260}
261
Songchun Fan3c82a302019-11-29 14:23:45 -0800262IncrementalService::~IncrementalService() = default;
263
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800264inline const char* toString(TimePoint t) {
265 using SystemClock = std::chrono::system_clock;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800266 time_t time = SystemClock::to_time_t(
267 SystemClock::now() +
268 std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800269 return std::ctime(&time);
270}
271
272inline const char* toString(IncrementalService::BindKind kind) {
273 switch (kind) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -0800274 case IncrementalService::BindKind::Temporary:
275 return "Temporary";
276 case IncrementalService::BindKind::Permanent:
277 return "Permanent";
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800278 }
279}
280
281void IncrementalService::onDump(int fd) {
282 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
283 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
284
285 std::unique_lock l(mLock);
286
287 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
288 for (auto&& [id, ifs] : mMounts) {
289 const IncFsMount& mnt = *ifs.get();
290 dprintf(fd, "\t[%d]:\n", id);
291 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -0700292 dprintf(fd, "\t\troot: %s\n", mnt.root.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800293 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700294 if (mnt.dataLoaderStub) {
295 const auto& dataLoaderStub = *mnt.dataLoaderStub;
296 dprintf(fd, "\t\tdataLoaderStatus: %d\n", dataLoaderStub.status());
297 dprintf(fd, "\t\tdataLoaderStartRequested: %s\n",
298 dataLoaderStub.startRequested() ? "true" : "false");
299 const auto& params = dataLoaderStub.params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700300 dprintf(fd, "\t\tdataLoaderParams:\n");
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800301 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
302 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
303 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
304 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800305 }
306 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
307 for (auto&& [storageId, storage] : mnt.storages) {
308 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
309 }
310
311 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
312 for (auto&& [target, bind] : mnt.bindPoints) {
313 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
314 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
315 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
316 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
317 }
318 }
319
320 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
321 for (auto&& [target, mountPairIt] : mBindsByPath) {
322 const auto& bind = mountPairIt->second;
323 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
324 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
325 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
326 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
327 }
328}
329
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700330void IncrementalService::onSystemReady() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800331 if (mSystemReady.exchange(true)) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700332 return;
Songchun Fan3c82a302019-11-29 14:23:45 -0800333 }
334
335 std::vector<IfsMountPtr> mounts;
336 {
337 std::lock_guard l(mLock);
338 mounts.reserve(mMounts.size());
339 for (auto&& [id, ifs] : mMounts) {
340 if (ifs->mountId == id) {
341 mounts.push_back(ifs);
342 }
343 }
344 }
345
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700346 /* TODO(b/151241369): restore data loaders on reboot.
Songchun Fan3c82a302019-11-29 14:23:45 -0800347 std::thread([this, mounts = std::move(mounts)]() {
Songchun Fan3c82a302019-11-29 14:23:45 -0800348 for (auto&& ifs : mounts) {
Alex Buynytskyy04f73912020-02-10 08:34:18 -0800349 if (prepareDataLoader(*ifs)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800350 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
351 } else {
Songchun Fan1124fd32020-02-10 12:49:41 -0800352 // TODO(b/133435829): handle data loader start failures
Songchun Fan3c82a302019-11-29 14:23:45 -0800353 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800354 }
355 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800356 }).detach();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700357 */
Songchun Fan3c82a302019-11-29 14:23:45 -0800358}
359
360auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
361 for (;;) {
362 if (mNextId == kMaxStorageId) {
363 mNextId = 0;
364 }
365 auto id = ++mNextId;
366 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
367 if (inserted) {
368 return it;
369 }
370 }
371}
372
Songchun Fan1124fd32020-02-10 12:49:41 -0800373StorageId IncrementalService::createStorage(
374 std::string_view mountPoint, DataLoaderParamsParcel&& dataLoaderParams,
375 const DataLoaderStatusListener& dataLoaderStatusListener, CreateOptions options) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800376 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
377 if (!path::isAbsolute(mountPoint)) {
378 LOG(ERROR) << "path is not absolute: " << mountPoint;
379 return kInvalidStorageId;
380 }
381
382 auto mountNorm = path::normalize(mountPoint);
383 {
384 const auto id = findStorageId(mountNorm);
385 if (id != kInvalidStorageId) {
386 if (options & CreateOptions::OpenExisting) {
387 LOG(INFO) << "Opened existing storage " << id;
388 return id;
389 }
390 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
391 return kInvalidStorageId;
392 }
393 }
394
395 if (!(options & CreateOptions::CreateNew)) {
396 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
397 return kInvalidStorageId;
398 }
399
400 if (!path::isEmptyDir(mountNorm)) {
401 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
402 return kInvalidStorageId;
403 }
404 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
405 if (mountRoot.empty()) {
406 LOG(ERROR) << "Bad mount point";
407 return kInvalidStorageId;
408 }
409 // Make sure the code removes all crap it may create while still failing.
410 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
411 auto firstCleanupOnFailure =
412 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
413
414 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800415 const auto backing = path::join(mountRoot, constants().backing);
416 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800417 return kInvalidStorageId;
418 }
419
Songchun Fan3c82a302019-11-29 14:23:45 -0800420 IncFsMount::Control control;
421 {
422 std::lock_guard l(mMountOperationLock);
423 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800424
425 if (auto err = rmDirContent(backing.c_str())) {
426 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
427 return kInvalidStorageId;
428 }
429 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
430 return kInvalidStorageId;
431 }
432 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800433 if (!status.isOk()) {
434 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
435 return kInvalidStorageId;
436 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800437 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
438 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800439 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
440 return kInvalidStorageId;
441 }
Songchun Fan20d6ef22020-03-03 09:47:15 -0800442 int cmd = controlParcel.cmd.release().release();
443 int pendingReads = controlParcel.pendingReads.release().release();
444 int logs = controlParcel.log.release().release();
445 control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -0800446 }
447
448 std::unique_lock l(mLock);
449 const auto mountIt = getStorageSlotLocked();
450 const auto mountId = mountIt->first;
451 l.unlock();
452
453 auto ifs =
454 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
455 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
456 // is the removal of the |ifs|.
457 firstCleanupOnFailure.release();
458
459 auto secondCleanup = [this, &l](auto itPtr) {
460 if (!l.owns_lock()) {
461 l.lock();
462 }
463 mMounts.erase(*itPtr);
464 };
465 auto secondCleanupOnFailure =
466 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
467
468 const auto storageIt = ifs->makeStorage(ifs->mountId);
469 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800470 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800471 return kInvalidStorageId;
472 }
473
474 {
475 metadata::Mount m;
476 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700477 m.mutable_loader()->set_type((int)dataLoaderParams.type);
478 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
479 m.mutable_loader()->set_class_name(dataLoaderParams.className);
480 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800481 const auto metadata = m.SerializeAsString();
482 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800483 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800484 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800485 if (auto err =
486 mIncFs->makeFile(ifs->control,
487 path::join(ifs->root, constants().mount,
488 constants().infoMdName),
489 0777, idFromMetadata(metadata),
490 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800491 LOG(ERROR) << "Saving mount metadata failed: " << -err;
492 return kInvalidStorageId;
493 }
494 }
495
496 const auto bk =
497 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800498 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
499 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800500 err < 0) {
501 LOG(ERROR) << "adding bind mount failed: " << -err;
502 return kInvalidStorageId;
503 }
504
505 // Done here as well, all data structures are in good state.
506 secondCleanupOnFailure.release();
507
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700508 auto dataLoaderStub =
509 prepareDataLoader(*ifs, std::move(dataLoaderParams), &dataLoaderStatusListener);
510 CHECK(dataLoaderStub);
Songchun Fan3c82a302019-11-29 14:23:45 -0800511
512 mountIt->second = std::move(ifs);
513 l.unlock();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700514
515 if (mSystemReady.load(std::memory_order_relaxed) && !dataLoaderStub->create()) {
516 // failed to create data loader
517 LOG(ERROR) << "initializeDataLoader() failed";
518 deleteStorage(dataLoaderStub->id());
519 return kInvalidStorageId;
520 }
521
Songchun Fan3c82a302019-11-29 14:23:45 -0800522 LOG(INFO) << "created storage " << mountId;
523 return mountId;
524}
525
526StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
527 StorageId linkedStorage,
528 IncrementalService::CreateOptions options) {
529 if (!isValidMountTarget(mountPoint)) {
530 LOG(ERROR) << "Mount point is invalid or missing";
531 return kInvalidStorageId;
532 }
533
534 std::unique_lock l(mLock);
535 const auto& ifs = getIfsLocked(linkedStorage);
536 if (!ifs) {
537 LOG(ERROR) << "Ifs unavailable";
538 return kInvalidStorageId;
539 }
540
541 const auto mountIt = getStorageSlotLocked();
542 const auto storageId = mountIt->first;
543 const auto storageIt = ifs->makeStorage(storageId);
544 if (storageIt == ifs->storages.end()) {
545 LOG(ERROR) << "Can't create a new storage";
546 mMounts.erase(mountIt);
547 return kInvalidStorageId;
548 }
549
550 l.unlock();
551
552 const auto bk =
553 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800554 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
555 std::string(storageIt->second.name), path::normalize(mountPoint),
556 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800557 err < 0) {
558 LOG(ERROR) << "bindMount failed with error: " << err;
559 return kInvalidStorageId;
560 }
561
562 mountIt->second = ifs;
563 return storageId;
564}
565
566IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
567 std::string_view path) const {
568 auto bindPointIt = mBindsByPath.upper_bound(path);
569 if (bindPointIt == mBindsByPath.begin()) {
570 return mBindsByPath.end();
571 }
572 --bindPointIt;
573 if (!path::startsWith(path, bindPointIt->first)) {
574 return mBindsByPath.end();
575 }
576 return bindPointIt;
577}
578
579StorageId IncrementalService::findStorageId(std::string_view path) const {
580 std::lock_guard l(mLock);
581 auto it = findStorageLocked(path);
582 if (it == mBindsByPath.end()) {
583 return kInvalidStorageId;
584 }
585 return it->second->second.storage;
586}
587
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700588int IncrementalService::setStorageParams(StorageId storageId, bool enableReadLogs) {
589 const auto ifs = getIfs(storageId);
590 if (!ifs) {
Alex Buynytskyy5f9e3a02020-04-07 21:13:41 -0700591 LOG(ERROR) << "setStorageParams failed, invalid storageId: " << storageId;
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700592 return -EINVAL;
593 }
594
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700595 const auto& params = ifs->dataLoaderStub->params();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700596 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700597 if (auto status = mAppOpsManager->checkPermission(kDataUsageStats, kOpUsage,
598 params.packageName.c_str());
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700599 !status.isOk()) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700600 LOG(ERROR) << "checkPermission failed: " << status.toString8();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700601 return fromBinderStatus(status);
602 }
603 }
604
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700605 if (auto status = applyStorageParams(*ifs, enableReadLogs); !status.isOk()) {
606 LOG(ERROR) << "applyStorageParams failed: " << status.toString8();
607 return fromBinderStatus(status);
608 }
609
610 if (enableReadLogs) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700611 registerAppOpsCallback(params.packageName);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700612 }
613
614 return 0;
615}
616
617binder::Status IncrementalService::applyStorageParams(IncFsMount& ifs, bool enableReadLogs) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700618 using unique_fd = ::android::base::unique_fd;
619 ::android::os::incremental::IncrementalFileSystemControlParcel control;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -0700620 control.cmd.reset(unique_fd(dup(ifs.control.cmd())));
621 control.pendingReads.reset(unique_fd(dup(ifs.control.pendingReads())));
622 auto logsFd = ifs.control.logs();
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700623 if (logsFd >= 0) {
624 control.log.reset(unique_fd(dup(logsFd)));
625 }
626
627 std::lock_guard l(mMountOperationLock);
Alex Buynytskyy1d892162020-04-03 23:00:19 -0700628 return mVold->setIncFsMountOptions(control, enableReadLogs);
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700629}
630
Songchun Fan3c82a302019-11-29 14:23:45 -0800631void IncrementalService::deleteStorage(StorageId storageId) {
632 const auto ifs = getIfs(storageId);
633 if (!ifs) {
634 return;
635 }
636 deleteStorage(*ifs);
637}
638
639void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
640 std::unique_lock l(ifs.lock);
641 deleteStorageLocked(ifs, std::move(l));
642}
643
644void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
645 std::unique_lock<std::mutex>&& ifsLock) {
646 const auto storages = std::move(ifs.storages);
647 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
648 const auto bindPoints = ifs.bindPoints;
649 ifsLock.unlock();
650
651 std::lock_guard l(mLock);
652 for (auto&& [id, _] : storages) {
653 if (id != ifs.mountId) {
654 mMounts.erase(id);
655 }
656 }
657 for (auto&& [path, _] : bindPoints) {
658 mBindsByPath.erase(path);
659 }
660 mMounts.erase(ifs.mountId);
661}
662
663StorageId IncrementalService::openStorage(std::string_view pathInMount) {
664 if (!path::isAbsolute(pathInMount)) {
665 return kInvalidStorageId;
666 }
667
668 return findStorageId(path::normalize(pathInMount));
669}
670
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800671FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800672 const auto ifs = getIfs(storage);
673 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800674 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800675 }
676 std::unique_lock l(ifs->lock);
677 auto storageIt = ifs->storages.find(storage);
678 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800679 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800680 }
681 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800682 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800683 }
684 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
685 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800686 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800687}
688
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800689std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800690 StorageId storage, std::string_view subpath) const {
691 auto name = path::basename(subpath);
692 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800693 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800694 }
695 auto dir = path::dirname(subpath);
696 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800697 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800698 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800699 auto id = nodeFor(storage, dir);
700 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800701}
702
703IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
704 std::lock_guard l(mLock);
705 return getIfsLocked(storage);
706}
707
708const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
709 auto it = mMounts.find(storage);
710 if (it == mMounts.end()) {
Yurii Zubrytskyi0cd80122020-04-09 23:08:31 -0700711 static const android::base::NoDestructor<IfsMountPtr> kEmpty{};
712 return *kEmpty;
Songchun Fan3c82a302019-11-29 14:23:45 -0800713 }
714 return it->second;
715}
716
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800717int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
718 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800719 if (!isValidMountTarget(target)) {
720 return -EINVAL;
721 }
722
723 const auto ifs = getIfs(storage);
724 if (!ifs) {
725 return -EINVAL;
726 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800727
Songchun Fan3c82a302019-11-29 14:23:45 -0800728 std::unique_lock l(ifs->lock);
729 const auto storageInfo = ifs->storages.find(storage);
730 if (storageInfo == ifs->storages.end()) {
731 return -EINVAL;
732 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700733 std::string normSource = normalizePathToStorageLocked(storageInfo, source);
734 if (normSource.empty()) {
735 return -EINVAL;
736 }
Songchun Fan3c82a302019-11-29 14:23:45 -0800737 l.unlock();
738 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800739 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
740 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800741}
742
743int IncrementalService::unbind(StorageId storage, std::string_view target) {
744 if (!path::isAbsolute(target)) {
745 return -EINVAL;
746 }
747
748 LOG(INFO) << "Removing bind point " << target;
749
750 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
751 // otherwise there's a chance to unmount something completely unrelated
752 const auto norm = path::normalize(target);
753 std::unique_lock l(mLock);
754 const auto storageIt = mBindsByPath.find(norm);
755 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
756 return -EINVAL;
757 }
758 const auto bindIt = storageIt->second;
759 const auto storageId = bindIt->second.storage;
760 const auto ifs = getIfsLocked(storageId);
761 if (!ifs) {
762 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
763 << " is missing";
764 return -EFAULT;
765 }
766 mBindsByPath.erase(storageIt);
767 l.unlock();
768
769 mVold->unmountIncFs(bindIt->first);
770 std::unique_lock l2(ifs->lock);
771 if (ifs->bindPoints.size() <= 1) {
772 ifs->bindPoints.clear();
773 deleteStorageLocked(*ifs, std::move(l2));
774 } else {
775 const std::string savedFile = std::move(bindIt->second.savedFilename);
776 ifs->bindPoints.erase(bindIt);
777 l2.unlock();
778 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800779 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800780 }
781 }
782 return 0;
783}
784
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700785std::string IncrementalService::normalizePathToStorageLocked(
786 IncFsMount::StorageMap::iterator storageIt, std::string_view path) {
787 std::string normPath;
788 if (path::isAbsolute(path)) {
789 normPath = path::normalize(path);
790 if (!path::startsWith(normPath, storageIt->second.name)) {
791 return {};
792 }
793 } else {
794 normPath = path::normalize(path::join(storageIt->second.name, path));
795 }
796 return normPath;
797}
798
799std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr& ifs,
Songchun Fan103ba1d2020-02-03 17:32:32 -0800800 StorageId storage, std::string_view path) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700801 std::unique_lock l(ifs->lock);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800802 const auto storageInfo = ifs->storages.find(storage);
803 if (storageInfo == ifs->storages.end()) {
804 return {};
805 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700806 return normalizePathToStorageLocked(storageInfo, path);
Songchun Fan103ba1d2020-02-03 17:32:32 -0800807}
808
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800809int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
810 incfs::NewFileParams params) {
811 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800812 std::string normPath = normalizePathToStorage(ifs, storage, path);
813 if (normPath.empty()) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700814 LOG(ERROR) << "Internal error: storageId " << storage
815 << " failed to normalize: " << path;
Songchun Fan54c6aed2020-01-31 16:52:41 -0800816 return -EINVAL;
817 }
818 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800819 if (err) {
Alex Buynytskyy5e860ba2020-03-31 15:30:21 -0700820 LOG(ERROR) << "Internal error: storageId " << storage << " failed to makeFile: " << err;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800821 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800822 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800823 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800824 }
825 return -EINVAL;
826}
827
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800828int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800829 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800830 std::string normPath = normalizePathToStorage(ifs, storageId, path);
831 if (normPath.empty()) {
832 return -EINVAL;
833 }
834 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800835 }
836 return -EINVAL;
837}
838
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800839int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800840 const auto ifs = getIfs(storageId);
841 if (!ifs) {
842 return -EINVAL;
843 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800844 std::string normPath = normalizePathToStorage(ifs, storageId, path);
845 if (normPath.empty()) {
846 return -EINVAL;
847 }
848 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800849 if (err == -EEXIST) {
850 return 0;
851 } else if (err != -ENOENT) {
852 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800853 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800854 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800855 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800856 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800857 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800858}
859
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800860int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
861 StorageId destStorageId, std::string_view newPath) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -0700862 auto ifsSrc = getIfs(sourceStorageId);
863 auto ifsDest = sourceStorageId == destStorageId ? ifsSrc : getIfs(destStorageId);
864 if (ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800865 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
866 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
867 if (normOldPath.empty() || normNewPath.empty()) {
868 return -EINVAL;
869 }
870 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800871 }
872 return -EINVAL;
873}
874
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800875int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800876 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800877 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
878 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800879 }
880 return -EINVAL;
881}
882
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800883int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
884 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800885 std::string&& target, BindKind kind,
886 std::unique_lock<std::mutex>& mainLock) {
887 if (!isValidMountTarget(target)) {
888 return -EINVAL;
889 }
890
891 std::string mdFileName;
892 if (kind != BindKind::Temporary) {
893 metadata::BindPoint bp;
894 bp.set_storage_id(storage);
895 bp.set_allocated_dest_path(&target);
Songchun Fan1124fd32020-02-10 12:49:41 -0800896 bp.set_allocated_source_subdir(&source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800897 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800898 bp.release_dest_path();
Songchun Fan1124fd32020-02-10 12:49:41 -0800899 bp.release_source_subdir();
Songchun Fan3c82a302019-11-29 14:23:45 -0800900 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800901 auto node =
902 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
903 0444, idFromMetadata(metadata),
904 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
905 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800906 return int(node);
907 }
908 }
909
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800910 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800911 std::move(target), kind, mainLock);
912}
913
914int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800915 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800916 std::string&& target, BindKind kind,
917 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800918 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800919 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800920 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800921 if (!status.isOk()) {
922 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
923 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
924 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
925 : status.serviceSpecificErrorCode() == 0
926 ? -EFAULT
927 : status.serviceSpecificErrorCode()
928 : -EIO;
929 }
930 }
931
932 if (!mainLock.owns_lock()) {
933 mainLock.lock();
934 }
935 std::lock_guard l(ifs.lock);
936 const auto [it, _] =
937 ifs.bindPoints.insert_or_assign(target,
938 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800939 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800940 mBindsByPath[std::move(target)] = it;
941 return 0;
942}
943
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800944RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800945 const auto ifs = getIfs(storage);
946 if (!ifs) {
947 return {};
948 }
949 return mIncFs->getMetadata(ifs->control, node);
950}
951
952std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
953 const auto ifs = getIfs(storage);
954 if (!ifs) {
955 return {};
956 }
957
958 std::unique_lock l(ifs->lock);
959 auto subdirIt = ifs->storages.find(storage);
960 if (subdirIt == ifs->storages.end()) {
961 return {};
962 }
963 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
964 l.unlock();
965
966 const auto prefixSize = dir.size() + 1;
967 std::vector<std::string> todoDirs{std::move(dir)};
968 std::vector<std::string> result;
969 do {
970 auto currDir = std::move(todoDirs.back());
971 todoDirs.pop_back();
972
973 auto d =
974 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
975 while (auto e = ::readdir(d.get())) {
976 if (e->d_type == DT_REG) {
977 result.emplace_back(
978 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
979 continue;
980 }
981 if (e->d_type == DT_DIR) {
982 if (e->d_name == "."sv || e->d_name == ".."sv) {
983 continue;
984 }
985 todoDirs.emplace_back(path::join(currDir, e->d_name));
986 continue;
987 }
988 }
989 } while (!todoDirs.empty());
990 return result;
991}
992
993bool IncrementalService::startLoading(StorageId storage) const {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -0700994 DataLoaderStubPtr dataLoaderStub;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -0700995 {
996 std::unique_lock l(mLock);
997 const auto& ifs = getIfsLocked(storage);
998 if (!ifs) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800999 return false;
1000 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001001 dataLoaderStub = ifs->dataLoaderStub;
1002 if (!dataLoaderStub) {
1003 return false;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001004 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001005 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001006 return dataLoaderStub->start();
Songchun Fan3c82a302019-11-29 14:23:45 -08001007}
1008
1009void IncrementalService::mountExistingImages() {
Songchun Fan1124fd32020-02-10 12:49:41 -08001010 for (const auto& entry : fs::directory_iterator(mIncrementalDir)) {
1011 const auto path = entry.path().u8string();
1012 const auto name = entry.path().filename().u8string();
1013 if (!base::StartsWith(name, constants().mountKeyPrefix)) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001014 continue;
1015 }
Songchun Fan1124fd32020-02-10 12:49:41 -08001016 const auto root = path::join(mIncrementalDir, name);
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001017 if (!mountExistingImage(root)) {
Songchun Fan1124fd32020-02-10 12:49:41 -08001018 IncFsMount::cleanupFilesystem(path);
Songchun Fan3c82a302019-11-29 14:23:45 -08001019 }
1020 }
1021}
1022
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001023bool IncrementalService::mountExistingImage(std::string_view root) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001024 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001025 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -08001026
Songchun Fan3c82a302019-11-29 14:23:45 -08001027 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001028 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -08001029 if (!status.isOk()) {
1030 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
1031 return false;
1032 }
Songchun Fan20d6ef22020-03-03 09:47:15 -08001033
1034 int cmd = controlParcel.cmd.release().release();
1035 int pendingReads = controlParcel.pendingReads.release().release();
1036 int logs = controlParcel.log.release().release();
1037 IncFsMount::Control control = mIncFs->createControl(cmd, pendingReads, logs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001038
1039 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
1040
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001041 auto mount = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
1042 path::join(mountTarget, constants().infoMdName));
1043 if (!mount.has_loader() || !mount.has_storage()) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001044 LOG(ERROR) << "Bad mount metadata in mount at " << root;
1045 return false;
1046 }
1047
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001048 ifs->mountId = mount.storage().id();
Songchun Fan3c82a302019-11-29 14:23:45 -08001049 mNextId = std::max(mNextId, ifs->mountId + 1);
1050
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001051 // DataLoader params
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001052 DataLoaderParamsParcel dataLoaderParams;
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001053 {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001054 const auto& loader = mount.loader();
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001055 dataLoaderParams.type = (android::content::pm::DataLoaderType)loader.type();
1056 dataLoaderParams.packageName = loader.package_name();
1057 dataLoaderParams.className = loader.class_name();
1058 dataLoaderParams.arguments = loader.arguments();
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001059 }
1060
Songchun Fan3c82a302019-11-29 14:23:45 -08001061 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001062 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001063 while (auto e = ::readdir(d.get())) {
1064 if (e->d_type == DT_REG) {
1065 auto name = std::string_view(e->d_name);
1066 if (name.starts_with(constants().mountpointMdPrefix)) {
1067 bindPoints.emplace_back(name,
1068 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1069 ifs->control,
1070 path::join(mountTarget,
1071 name)));
1072 if (bindPoints.back().second.dest_path().empty() ||
1073 bindPoints.back().second.source_subdir().empty()) {
1074 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001075 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001076 }
1077 }
1078 } else if (e->d_type == DT_DIR) {
1079 if (e->d_name == "."sv || e->d_name == ".."sv) {
1080 continue;
1081 }
1082 auto name = std::string_view(e->d_name);
1083 if (name.starts_with(constants().storagePrefix)) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001084 int storageId;
1085 const auto res = std::from_chars(name.data() + constants().storagePrefix.size() + 1,
1086 name.data() + name.size(), storageId);
1087 if (res.ec != std::errc{} || *res.ptr != '_') {
1088 LOG(WARNING) << "Ignoring storage with invalid name '" << name << "' for mount "
1089 << root;
1090 continue;
1091 }
1092 auto [_, inserted] = mMounts.try_emplace(storageId, ifs);
Songchun Fan3c82a302019-11-29 14:23:45 -08001093 if (!inserted) {
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001094 LOG(WARNING) << "Ignoring storage with duplicate id " << storageId
Songchun Fan3c82a302019-11-29 14:23:45 -08001095 << " for mount " << root;
1096 continue;
1097 }
Yurii Zubrytskyi107ae352020-04-03 13:12:51 -07001098 ifs->storages.insert_or_assign(storageId,
1099 IncFsMount::Storage{
1100 path::join(root, constants().mount, name)});
1101 mNextId = std::max(mNextId, storageId + 1);
Songchun Fan3c82a302019-11-29 14:23:45 -08001102 }
1103 }
1104 }
1105
1106 if (ifs->storages.empty()) {
1107 LOG(WARNING) << "No valid storages in mount " << root;
1108 return false;
1109 }
1110
1111 int bindCount = 0;
1112 for (auto&& bp : bindPoints) {
1113 std::unique_lock l(mLock, std::defer_lock);
1114 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1115 std::move(*bp.second.mutable_source_subdir()),
1116 std::move(*bp.second.mutable_dest_path()),
1117 BindKind::Permanent, l);
1118 }
1119
1120 if (bindCount == 0) {
1121 LOG(WARNING) << "No valid bind points for mount " << root;
1122 deleteStorage(*ifs);
1123 return false;
1124 }
1125
Songchun Fan3c82a302019-11-29 14:23:45 -08001126 mMounts[ifs->mountId] = std::move(ifs);
1127 return true;
1128}
1129
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001130IncrementalService::DataLoaderStubPtr IncrementalService::prepareDataLoader(
1131 IncrementalService::IncFsMount& ifs, DataLoaderParamsParcel&& params,
1132 const DataLoaderStatusListener* externalListener) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001133 std::unique_lock l(ifs.lock);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001134 if (ifs.dataLoaderStub) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001135 LOG(INFO) << "Skipped data loader preparation because it already exists";
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001136 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001137 }
1138
Songchun Fan3c82a302019-11-29 14:23:45 -08001139 FileSystemControlParcel fsControlParcel;
Jooyung Han66c567a2020-03-07 21:47:09 +09001140 fsControlParcel.incremental = aidl::make_nullable<IncrementalFileSystemControlParcel>();
Songchun Fan20d6ef22020-03-03 09:47:15 -08001141 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd())));
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001142 fsControlParcel.incremental->pendingReads.reset(
Songchun Fan20d6ef22020-03-03 09:47:15 -08001143 base::unique_fd(::dup(ifs.control.pendingReads())));
1144 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs())));
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001145 fsControlParcel.service = new IncrementalServiceConnector(*this, ifs.mountId);
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001146
1147 ifs.dataLoaderStub = new DataLoaderStub(*this, ifs.mountId, std::move(params),
1148 std::move(fsControlParcel), externalListener);
1149 return ifs.dataLoaderStub;
Songchun Fan3c82a302019-11-29 14:23:45 -08001150}
1151
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001152template <class Duration>
1153static long elapsedMcs(Duration start, Duration end) {
1154 return std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
1155}
1156
1157// Extract lib files from zip, create new files in incfs and write data to them
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001158bool IncrementalService::configureNativeBinaries(StorageId storage, std::string_view apkFullPath,
1159 std::string_view libDirRelativePath,
1160 std::string_view abi) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001161 namespace sc = std::chrono;
1162 using Clock = sc::steady_clock;
1163 auto start = Clock::now();
1164
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001165 const auto ifs = getIfs(storage);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001166 if (!ifs) {
1167 LOG(ERROR) << "Invalid storage " << storage;
1168 return false;
1169 }
1170
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001171 // First prepare target directories if they don't exist yet
1172 if (auto res = makeDirs(storage, libDirRelativePath, 0755)) {
1173 LOG(ERROR) << "Failed to prepare target lib directory " << libDirRelativePath
1174 << " errno: " << res;
1175 return false;
1176 }
1177
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001178 auto mkDirsTs = Clock::now();
1179
1180 std::unique_ptr<ZipFileRO> zipFile(ZipFileRO::open(path::c_str(apkFullPath)));
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001181 if (!zipFile) {
1182 LOG(ERROR) << "Failed to open zip file at " << apkFullPath;
1183 return false;
1184 }
1185 void* cookie = nullptr;
1186 const auto libFilePrefix = path::join(constants().libDir, abi);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001187 if (!zipFile->startIteration(&cookie, libFilePrefix.c_str() /* prefix */,
1188 constants().libSuffix.data() /* suffix */)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001189 LOG(ERROR) << "Failed to start zip iteration for " << apkFullPath;
1190 return false;
1191 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001192 auto endIteration = [&zipFile](void* cookie) { zipFile->endIteration(cookie); };
1193 auto iterationCleaner = std::unique_ptr<void, decltype(endIteration)>(cookie, endIteration);
1194
1195 auto openZipTs = Clock::now();
1196
1197 std::vector<IncFsDataBlock> instructions;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001198 ZipEntryRO entry = nullptr;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001199 while ((entry = zipFile->nextEntry(cookie)) != nullptr) {
1200 auto startFileTs = Clock::now();
1201
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001202 char fileName[PATH_MAX];
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001203 if (zipFile->getEntryFileName(entry, fileName, sizeof(fileName))) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001204 continue;
1205 }
1206 const auto libName = path::basename(fileName);
1207 const auto targetLibPath = path::join(libDirRelativePath, libName);
1208 const auto targetLibPathAbsolute = normalizePathToStorage(ifs, storage, targetLibPath);
1209 // If the extract file already exists, skip
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001210 if (access(targetLibPathAbsolute.c_str(), F_OK) == 0) {
1211 if (sEnablePerfLogging) {
1212 LOG(INFO) << "incfs: Native lib file already exists: " << targetLibPath
1213 << "; skipping extraction, spent "
1214 << elapsedMcs(startFileTs, Clock::now()) << "mcs";
1215 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001216 continue;
1217 }
1218
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001219 uint32_t uncompressedLen, compressedLen;
1220 if (!zipFile->getEntryInfo(entry, nullptr, &uncompressedLen, &compressedLen, nullptr,
1221 nullptr, nullptr)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001222 LOG(ERROR) << "Failed to read native lib entry: " << fileName;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001223 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001224 }
1225
1226 // Create new lib file without signature info
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001227 incfs::NewFileParams libFileParams = {
1228 .size = uncompressedLen,
1229 .signature = {},
1230 // Metadata of the new lib file is its relative path
1231 .metadata = {targetLibPath.c_str(), (IncFsSize)targetLibPath.size()},
1232 };
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001233 incfs::FileId libFileId = idFromMetadata(targetLibPath);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001234 if (auto res = mIncFs->makeFile(ifs->control, targetLibPathAbsolute, 0777, libFileId,
1235 libFileParams)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001236 LOG(ERROR) << "Failed to make file for: " << targetLibPath << " errno: " << res;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001237 // If one lib file fails to be created, abort others as well
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001238 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001239 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001240
1241 auto makeFileTs = Clock::now();
1242
Songchun Fanafaf6e92020-03-18 14:12:20 -07001243 // If it is a zero-byte file, skip data writing
1244 if (uncompressedLen == 0) {
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001245 if (sEnablePerfLogging) {
1246 LOG(INFO) << "incfs: Extracted " << libName << "(" << compressedLen << " -> "
1247 << uncompressedLen << " bytes): " << elapsedMcs(startFileTs, makeFileTs)
1248 << "mcs, make: " << elapsedMcs(startFileTs, makeFileTs);
1249 }
Songchun Fanafaf6e92020-03-18 14:12:20 -07001250 continue;
1251 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001252
1253 // Write extracted data to new file
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001254 // NOTE: don't zero-initialize memory, it may take a while
1255 auto libData = std::unique_ptr<uint8_t[]>(new uint8_t[uncompressedLen]);
1256 if (!zipFile->uncompressEntry(entry, libData.get(), uncompressedLen)) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001257 LOG(ERROR) << "Failed to extract native lib zip entry: " << fileName;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001258 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001259 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001260
1261 auto extractFileTs = Clock::now();
1262
Yurii Zubrytskyie82cdd72020-04-01 12:19:26 -07001263 const auto writeFd = mIncFs->openForSpecialOps(ifs->control, libFileId);
1264 if (!writeFd.ok()) {
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001265 LOG(ERROR) << "Failed to open write fd for: " << targetLibPath << " errno: " << writeFd;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001266 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001267 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001268
1269 auto openFileTs = Clock::now();
1270
1271 const int numBlocks = (uncompressedLen + constants().blockSize - 1) / constants().blockSize;
1272 instructions.clear();
1273 instructions.reserve(numBlocks);
1274 auto remainingData = std::span(libData.get(), uncompressedLen);
1275 for (int i = 0; i < numBlocks; i++) {
1276 const auto blockSize = std::min<uint16_t>(constants().blockSize, remainingData.size());
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001277 auto inst = IncFsDataBlock{
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001278 .fileFd = writeFd.get(),
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001279 .pageIndex = static_cast<IncFsBlockIndex>(i),
1280 .compression = INCFS_COMPRESSION_KIND_NONE,
1281 .kind = INCFS_BLOCK_KIND_DATA,
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001282 .dataSize = blockSize,
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001283 .data = reinterpret_cast<const char*>(remainingData.data()),
1284 };
1285 instructions.push_back(inst);
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001286 remainingData = remainingData.subspan(blockSize);
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001287 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001288 auto prepareInstsTs = Clock::now();
1289
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001290 size_t res = mIncFs->writeBlocks(instructions);
1291 if (res != instructions.size()) {
1292 LOG(ERROR) << "Failed to write data into: " << targetLibPath;
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001293 return false;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001294 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001295
1296 if (sEnablePerfLogging) {
1297 auto endFileTs = Clock::now();
1298 LOG(INFO) << "incfs: Extracted " << libName << "(" << compressedLen << " -> "
1299 << uncompressedLen << " bytes): " << elapsedMcs(startFileTs, endFileTs)
1300 << "mcs, make: " << elapsedMcs(startFileTs, makeFileTs)
1301 << " extract: " << elapsedMcs(makeFileTs, extractFileTs)
1302 << " open: " << elapsedMcs(extractFileTs, openFileTs)
1303 << " prepare: " << elapsedMcs(openFileTs, prepareInstsTs)
1304 << " write:" << elapsedMcs(prepareInstsTs, endFileTs);
1305 }
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001306 }
Yurii Zubrytskyi3787c9f2020-04-06 23:10:28 -07001307
1308 if (sEnablePerfLogging) {
1309 auto end = Clock::now();
1310 LOG(INFO) << "incfs: configureNativeBinaries complete in " << elapsedMcs(start, end)
1311 << "mcs, make dirs: " << elapsedMcs(start, mkDirsTs)
1312 << " open zip: " << elapsedMcs(mkDirsTs, openZipTs)
1313 << " extract all: " << elapsedMcs(openZipTs, end);
1314 }
1315
1316 return true;
Songchun Fan0f8b6fe2020-02-05 17:41:25 -08001317}
1318
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001319void IncrementalService::registerAppOpsCallback(const std::string& packageName) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001320 sp<IAppOpsCallback> listener;
1321 {
1322 std::unique_lock lock{mCallbacksLock};
1323 auto& cb = mCallbackRegistered[packageName];
1324 if (cb) {
1325 return;
1326 }
1327 cb = new AppOpsListener(*this, packageName);
1328 listener = cb;
1329 }
1330
1331 mAppOpsManager->startWatchingMode(AppOpsManager::OP_GET_USAGE_STATS, String16(packageName.c_str()), listener);
1332}
1333
1334bool IncrementalService::unregisterAppOpsCallback(const std::string& packageName) {
1335 sp<IAppOpsCallback> listener;
1336 {
1337 std::unique_lock lock{mCallbacksLock};
1338 auto found = mCallbackRegistered.find(packageName);
1339 if (found == mCallbackRegistered.end()) {
1340 return false;
1341 }
1342 listener = found->second;
1343 mCallbackRegistered.erase(found);
1344 }
1345
1346 mAppOpsManager->stopWatchingMode(listener);
1347 return true;
1348}
1349
1350void IncrementalService::onAppOpChanged(const std::string& packageName) {
1351 if (!unregisterAppOpsCallback(packageName)) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001352 return;
1353 }
1354
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001355 std::vector<IfsMountPtr> affected;
1356 {
1357 std::lock_guard l(mLock);
1358 affected.reserve(mMounts.size());
1359 for (auto&& [id, ifs] : mMounts) {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001360 if (ifs->mountId == id && ifs->dataLoaderStub->params().packageName == packageName) {
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001361 affected.push_back(ifs);
1362 }
1363 }
1364 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001365 for (auto&& ifs : affected) {
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001366 applyStorageParams(*ifs, false);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001367 }
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001368}
1369
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001370IncrementalService::DataLoaderStub::~DataLoaderStub() {
1371 CHECK(mStatus == -1 || mStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED)
1372 << "Dataloader has to be destroyed prior to destructor: " << mId
1373 << ", status: " << mStatus;
1374}
1375
1376bool IncrementalService::DataLoaderStub::create() {
1377 bool created = false;
1378 auto status = mService.mDataLoaderManager->initializeDataLoader(mId, mParams, mControl, this,
1379 &created);
1380 if (!status.isOk() || !created) {
1381 LOG(ERROR) << "Failed to create a data loader for mount " << mId;
1382 return false;
1383 }
1384 return true;
1385}
1386
1387bool IncrementalService::DataLoaderStub::start() {
1388 if (mStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
1389 mStartRequested = true;
1390 return true;
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001391 }
1392
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001393 sp<IDataLoader> dataloader;
1394 auto status = mService.mDataLoaderManager->getDataLoader(mId, &dataloader);
1395 if (!status.isOk()) {
1396 return false;
1397 }
1398 if (!dataloader) {
1399 return false;
1400 }
1401 status = dataloader->start(mId);
1402 if (!status.isOk()) {
1403 return false;
1404 }
1405 return true;
1406}
1407
1408void IncrementalService::DataLoaderStub::destroy() {
1409 mDestroyRequested = true;
1410 mService.mDataLoaderManager->destroyDataLoader(mId);
1411}
1412
1413binder::Status IncrementalService::DataLoaderStub::onStatusChanged(MountId mountId, int newStatus) {
1414 if (mStatus == newStatus) {
1415 return binder::Status::ok();
1416 }
1417
1418 if (mListener) {
1419 // Give an external listener a chance to act before we destroy something.
1420 mListener->onStatusChanged(mountId, newStatus);
1421 }
1422
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001423 {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001424 std::unique_lock l(mService.mLock);
1425 const auto& ifs = mService.getIfsLocked(mountId);
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001426 if (!ifs) {
Songchun Fan306b7df2020-03-17 12:37:07 -07001427 LOG(WARNING) << "Received data loader status " << int(newStatus)
1428 << " for unknown mount " << mountId;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001429 return binder::Status::ok();
1430 }
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001431 mStatus = newStatus;
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001432
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001433 if (!mDestroyRequested && newStatus == IDataLoaderStatusListener::DATA_LOADER_DESTROYED) {
1434 mService.deleteStorageLocked(*ifs, std::move(l));
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001435 return binder::Status::ok();
1436 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001437 }
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001438
Songchun Fan3c82a302019-11-29 14:23:45 -08001439 switch (newStatus) {
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001440 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Alex Buynytskyy0ea4ff42020-04-09 17:25:42 -07001441 if (mStartRequested) {
1442 start();
Alex Buynytskyybf1c0632020-03-10 15:49:29 -07001443 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001444 break;
1445 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001446 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001447 break;
1448 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001449 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001450 break;
1451 }
1452 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1453 break;
1454 }
Alex Buynytskyy04f73912020-02-10 08:34:18 -08001455 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_READY: {
1456 break;
1457 }
1458 case IDataLoaderStatusListener::DATA_LOADER_IMAGE_NOT_READY: {
1459 break;
1460 }
Alex Buynytskyy2cf1d182020-03-17 09:33:45 -07001461 case IDataLoaderStatusListener::DATA_LOADER_UNRECOVERABLE: {
1462 // Nothing for now. Rely on externalListener to handle this.
1463 break;
1464 }
Songchun Fan3c82a302019-11-29 14:23:45 -08001465 default: {
1466 LOG(WARNING) << "Unknown data loader status: " << newStatus
1467 << " for mount: " << mountId;
1468 break;
1469 }
1470 }
1471
1472 return binder::Status::ok();
1473}
1474
Alex Buynytskyy1d892162020-04-03 23:00:19 -07001475void IncrementalService::AppOpsListener::opChanged(int32_t, const String16&) {
1476 incrementalService.onAppOpChanged(packageName);
Alex Buynytskyy96e350b2020-04-02 20:03:47 -07001477}
1478
Alex Buynytskyyf4156792020-04-07 14:26:55 -07001479binder::Status IncrementalService::IncrementalServiceConnector::setStorageParams(
1480 bool enableReadLogs, int32_t* _aidl_return) {
1481 *_aidl_return = incrementalService.setStorageParams(storage, enableReadLogs);
1482 return binder::Status::ok();
1483}
1484
Songchun Fan3c82a302019-11-29 14:23:45 -08001485} // namespace android::incremental