blob: b302f52f3e1dfeceff3e9506d045e9153eaa96ce [file] [log] [blame]
Mike Lockwood94afecf2012-10-24 10:45:23 -07001/*
2** Copyright 2008, The Android Open Source Project
3**
Dave Allisond9370732014-01-30 14:19:23 -08004** 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
Mike Lockwood94afecf2012-10-24 10:45:23 -07007**
Dave Allisond9370732014-01-30 14:19:23 -08008** http://www.apache.org/licenses/LICENSE-2.0
Mike Lockwood94afecf2012-10-24 10:45:23 -07009**
Dave Allisond9370732014-01-30 14:19:23 -080010** 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
Mike Lockwood94afecf2012-10-24 10:45:23 -070014** limitations under the License.
15*/
16
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070017#include "InstalldNativeService.h"
Andreas Gampe02d0de52015-11-11 20:43:16 -080018
19#include <errno.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070020#include <fts.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080021#include <inttypes.h>
Keun young Park144a9892021-10-13 16:43:58 -070022#include <stdio.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080023#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070024#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080025#include <sys/capability.h>
26#include <sys/file.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080027#include <sys/ioctl.h>
28#include <sys/mman.h>
Ricky Waiff9d3ea2019-11-18 18:18:24 +000029#include <sys/mount.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080030#include <sys/resource.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080031#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070032#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070033#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000034#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070035#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080036#include <unistd.h>
Samiul Islamc40dff52022-01-14 16:24:48 +000037#include <algorithm>
38#include <filesystem>
39#include <fstream>
40#include <functional>
41#include <regex>
Samiul Islam92f5cf02022-02-03 12:45:51 +000042#include <unordered_set>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070043
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000044#include <android-base/file.h>
Andreas Gampeafa58d12016-06-03 16:09:32 -070045#include <android-base/logging.h>
Oli Lanc7789572020-03-16 18:18:41 +000046#include <android-base/parseint.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070047#include <android-base/properties.h>
Narayan Kamathe63ca7d2019-01-14 15:21:52 +000048#include <android-base/scopeguard.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080049#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070050#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010051#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080052#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080053#include <cutils/fs.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070054#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070055#include <cutils/sched_policy.h>
Shikha Malhotra976ae002022-02-26 15:39:53 +000056#include <linux/quota.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070057#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070058#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080059#include <private/android_filesystem_config.h>
Martijn Coenen771cc342020-02-19 23:26:56 +010060#include <private/android_projectid_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070061#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080062#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070063#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070064
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070065#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070066#include "globals.h"
67#include "installd_deps.h"
68#include "otapreopt_utils.h"
69#include "utils.h"
Eric Holk0ebbe0f2019-01-09 18:17:27 -080070#include "view_compiler.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070071
Jeff Sharkey88ddd942017-01-17 18:05:54 -070072#include "CacheTracker.h"
Felka Chang2a0a2462019-11-20 14:20:40 +080073#include "CrateManager.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070074#include "MatchExtensionGen.h"
Risan5f308262018-10-26 12:06:58 -060075#include "QuotaUtils.h"
Zim23457d02022-08-17 12:57:41 +010076#include "SysTrace.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070077
Andreas Gampe02d0de52015-11-11 20:43:16 -080078#ifndef LOG_TAG
79#define LOG_TAG "installd"
80#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070081
Alex Buynytskyy779447d2021-11-22 17:06:53 -080082#define GRANULAR_LOCKS
Alex Buynytskyy4fef8862021-11-21 16:09:33 -080083
Oli Lanc7789572020-03-16 18:18:41 +000084using android::base::ParseUint;
Samiul Islam92f5cf02022-02-03 12:45:51 +000085using android::base::Split;
Jeff Sharkey41ea4242015-04-09 11:34:03 -070086using android::base::StringPrintf;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070087using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070088
Andreas Gampe02d0de52015-11-11 20:43:16 -080089namespace android {
90namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070091
Nikita Ioffe8e4d3462019-01-21 17:56:03 +000092// An uuid used in unit tests.
93static constexpr const char* kTestUuid = "TEST";
94
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000095static constexpr const mode_t kRollbackFolderMode = 0700;
96
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070097static constexpr const char* kCpPath = "/system/bin/cp";
98static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -070099
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000100static constexpr const char* kDataMirrorCePath = "/data_mirror/data_ce";
101static constexpr const char* kDataMirrorDePath = "/data_mirror/data_de";
Sanjana Sunil691163d2022-03-28 19:15:54 +0000102static constexpr const char* kMiscMirrorCePath = "/data_mirror/misc_ce";
103static constexpr const char* kMiscMirrorDePath = "/data_mirror/misc_de";
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000104
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -0700105static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +0000106
Andreas Gampe0354bd02016-06-27 14:25:30 -0700107static constexpr const char* PKG_LIB_POSTFIX = "/lib";
108static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
109static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
110
Zim0ce832d2019-12-03 17:03:58 +0000111static constexpr const char* kFuseProp = "persist.sys.fuse";
Victor Hsieh99de5162017-10-06 14:44:14 -0700112
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000113/**
114 * Property to control if app data isolation is enabled.
115 */
116static constexpr const char* kAppDataIsolationEnabledProperty = "persist.zygote.app_data_isolation";
Zim1edb92a2020-01-09 08:48:00 +0000117static constexpr const char* kMntSdcardfs = "/mnt/runtime/default/";
118static constexpr const char* kMntFuse = "/mnt/pass_through/0/";
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000119
120static std::atomic<bool> sAppDataIsolationEnabled(false);
121
Shikha Malhotradcf469b2022-03-23 11:53:58 +0000122/**
123 * Flag to control if project ids are supported for internal storage
124 */
125static std::atomic<bool> sUsingProjectIdsFlag(false);
126static std::once_flag flag;
127
Jeff Sharkey0274c972016-12-06 09:32:04 -0700128namespace {
129
Jeff Sharkey423e7462016-12-09 18:18:43 -0700130static binder::Status ok() {
131 return binder::Status::ok();
132}
133
134static binder::Status exception(uint32_t code, const std::string& msg) {
Jeff Sharkey8e9bf352018-02-27 11:40:45 -0700135 LOG(ERROR) << msg << " (" << code << ")";
Jeff Sharkey423e7462016-12-09 18:18:43 -0700136 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
137}
138
139static binder::Status error() {
140 return binder::Status::fromServiceSpecificError(errno);
141}
142
143static binder::Status error(const std::string& msg) {
144 PLOG(ERROR) << msg;
145 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
146}
147
148static binder::Status error(uint32_t code, const std::string& msg) {
149 LOG(ERROR) << msg << " (" << code << ")";
150 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
151}
152
Jeff Sharkey0274c972016-12-06 09:32:04 -0700153binder::Status checkUid(uid_t expectedUid) {
154 uid_t uid = IPCThreadState::self()->getCallingUid();
155 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700156 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700157 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700158 return exception(binder::Status::EX_SECURITY,
159 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
160 }
161}
162
Jooyung Han149be4a2020-01-23 12:45:10 +0900163binder::Status checkArgumentUuid(const std::optional<std::string>& uuid) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700164 if (!uuid || is_valid_filename(*uuid)) {
165 return ok();
166 } else {
167 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
168 StringPrintf("UUID %s is malformed", uuid->c_str()));
169 }
170}
171
Jooyung Han149be4a2020-01-23 12:45:10 +0900172binder::Status checkArgumentUuidTestOrNull(const std::optional<std::string>& uuid) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000173 if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
174 return ok();
175 } else {
176 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
177 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
178 }
179}
180
Jeff Sharkey423e7462016-12-09 18:18:43 -0700181binder::Status checkArgumentPackageName(const std::string& packageName) {
Greg Kaiser6d758fc2019-03-26 08:55:32 -0700182 if (is_valid_package_name(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700183 return ok();
184 } else {
185 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
186 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700187 }
188}
189
Jeff Sharkey53594302018-02-24 18:59:39 -0700190binder::Status checkArgumentPath(const std::string& path) {
191 if (path.empty()) {
192 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
193 }
194 if (path[0] != '/') {
195 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
196 StringPrintf("Path %s is relative", path.c_str()));
197 }
198 if ((path + '/').find("/../") != std::string::npos) {
199 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
200 StringPrintf("Path %s is shady", path.c_str()));
201 }
202 for (const char& c : path) {
203 if (c == '\0' || c == '\n') {
204 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
205 StringPrintf("Path %s is malformed", path.c_str()));
206 }
207 }
208 return ok();
209}
210
Jooyung Han149be4a2020-01-23 12:45:10 +0900211binder::Status checkArgumentPath(const std::optional<std::string>& path) {
Jeff Sharkey53594302018-02-24 18:59:39 -0700212 if (path) {
213 return checkArgumentPath(*path);
214 } else {
215 return ok();
216 }
217}
218
Alex Buynytskyyd04631f2022-08-12 15:14:41 -0700219binder::Status checkArgumentFileName(const std::string& path) {
220 if (path.empty()) {
221 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing name");
222 }
223 for (const char& c : path) {
224 if (c == '\0' || c == '\n' || c == '/') {
225 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
226 StringPrintf("Name %s is malformed", path.c_str()));
227 }
228 }
229 return ok();
230}
231
Jeff Sharkey0274c972016-12-06 09:32:04 -0700232#define ENFORCE_UID(uid) { \
233 binder::Status status = checkUid((uid)); \
234 if (!status.isOk()) { \
235 return status; \
236 } \
237}
238
Steven Moreland36945362023-07-05 20:29:10 +0000239// we could have tighter checks, but this is only to avoid hard errors. Negative values are defined
240// in UserHandle.java and carry specific meanings that may not be handled by certain APIs here.
241#define ENFORCE_VALID_USER(userId) \
242 { \
243 if (static_cast<uid_t>(std::abs(userId)) >= \
244 std::numeric_limits<uid_t>::max() / AID_USER_OFFSET) { \
245 return error("userId invalid: " + std::to_string(userId)); \
246 } \
247 }
248
Jeff Sharkey423e7462016-12-09 18:18:43 -0700249#define CHECK_ARGUMENT_UUID(uuid) { \
250 binder::Status status = checkArgumentUuid((uuid)); \
251 if (!status.isOk()) { \
252 return status; \
253 } \
254}
255
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000256#define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) { \
257 auto status = checkArgumentUuidTestOrNull(uuid); \
258 if (!status.isOk()) { \
259 return status; \
260 } \
261} \
262
Jeff Sharkey423e7462016-12-09 18:18:43 -0700263#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
264 binder::Status status = \
265 checkArgumentPackageName((packageName)); \
266 if (!status.isOk()) { \
267 return status; \
268 } \
269}
270
Jeff Sharkey53594302018-02-24 18:59:39 -0700271#define CHECK_ARGUMENT_PATH(path) { \
272 binder::Status status = checkArgumentPath((path)); \
273 if (!status.isOk()) { \
274 return status; \
275 } \
276}
277
Alex Buynytskyyd04631f2022-08-12 15:14:41 -0700278#define CHECK_ARGUMENT_FILE_NAME(path) \
279 { \
280 binder::Status status = checkArgumentFileName((path)); \
281 if (!status.isOk()) { \
282 return status; \
283 } \
284 }
285
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800286#ifdef GRANULAR_LOCKS
287
288/**
289 * This class obtains in constructor and keeps the local strong pointer to the RefLock.
290 * On destruction, it checks if there are any other strong pointers, and remove the map entry if
291 * this was the last one.
292 */
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800293template <class Key, class Mutex>
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800294struct LocalLockHolder {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800295 using WeakPointer = std::weak_ptr<Mutex>;
296 using StrongPointer = std::shared_ptr<Mutex>;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800297 using Map = std::unordered_map<Key, WeakPointer>;
298 using MapLock = std::recursive_mutex;
299
300 LocalLockHolder(Key key, Map& map, MapLock& mapLock)
301 : mKey(std::move(key)), mMap(map), mMapLock(mapLock) {
302 std::lock_guard lock(mMapLock);
303 auto& weakPtr = mMap[mKey];
304
305 // Check if the RefLock is still alive.
306 mRefLock = weakPtr.lock();
307 if (!mRefLock) {
308 // Create a new lock.
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800309 mRefLock = std::make_shared<Mutex>();
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800310 weakPtr = mRefLock;
311 }
312 }
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800313 LocalLockHolder(LocalLockHolder&& other) noexcept
314 : mKey(std::move(other.mKey)),
315 mMap(other.mMap),
316 mMapLock(other.mMapLock),
317 mRefLock(std::move(other.mRefLock)) {
318 other.mRefLock.reset();
319 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800320 ~LocalLockHolder() {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800321 if (!mRefLock) {
322 return;
323 }
324
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800325 std::lock_guard lock(mMapLock);
326 // Clear the strong pointer.
327 mRefLock.reset();
328 auto found = mMap.find(mKey);
329 if (found == mMap.end()) {
330 return;
331 }
332 const auto& weakPtr = found->second;
333 // If this was the last pointer then it's ok to remove the map entry.
334 if (weakPtr.expired()) {
335 mMap.erase(found);
336 }
337 }
338
339 void lock() { mRefLock->lock(); }
340 void unlock() { mRefLock->unlock(); }
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800341 void lock_shared() { mRefLock->lock_shared(); }
342 void unlock_shared() { mRefLock->unlock_shared(); }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800343
344private:
345 Key mKey;
346 Map& mMap;
347 MapLock& mMapLock;
348 StrongPointer mRefLock;
349};
350
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800351using UserLock = LocalLockHolder<userid_t, std::shared_mutex>;
352using UserWriteLockGuard = std::unique_lock<UserLock>;
353using UserReadLockGuard = std::shared_lock<UserLock>;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800354
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800355using PackageLock = LocalLockHolder<std::string, std::recursive_mutex>;
356using PackageLockGuard = std::lock_guard<PackageLock>;
357
358#define LOCK_USER() \
359 UserLock localUserLock(userId, mUserIdLock, mLock); \
360 UserWriteLockGuard userLock(localUserLock)
361
362#define LOCK_USER_READ() \
363 UserLock localUserLock(userId, mUserIdLock, mLock); \
364 UserReadLockGuard userLock(localUserLock)
365
366#define LOCK_PACKAGE() \
367 PackageLock localPackageLock(packageName, mPackageNameLock, mLock); \
368 PackageLockGuard packageLock(localPackageLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800369
370#define LOCK_PACKAGE_USER() \
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800371 LOCK_USER_READ(); \
372 LOCK_PACKAGE()
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800373
374#else
375
376#define LOCK_USER() std::lock_guard lock(mLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800377#define LOCK_PACKAGE() std::lock_guard lock(mLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800378#define LOCK_PACKAGE_USER() \
379 (void)userId; \
380 std::lock_guard lock(mLock)
381
382#endif // GRANULAR_LOCKS
383
Jeff Sharkey0274c972016-12-06 09:32:04 -0700384} // namespace
385
386status_t InstalldNativeService::start() {
387 IPCThreadState::self()->disableBackgroundScheduling(true);
388 status_t ret = BinderService<InstalldNativeService>::publish();
389 if (ret != android::OK) {
390 return ret;
391 }
392 sp<ProcessState> ps(ProcessState::self());
393 ps->startThreadPool();
394 ps->giveThreadPoolName();
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000395 sAppDataIsolationEnabled = android::base::GetBoolProperty(
Ricky Wai30f947d2019-12-19 17:24:48 +0000396 kAppDataIsolationEnabledProperty, true);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700397 return android::OK;
398}
399
Alex Buynytskyy17b12dc2022-09-12 20:57:24 -0700400status_t InstalldNativeService::dump(int fd, const Vector<String16>& /* args */) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700401 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600402 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Keun young Park144a9892021-10-13 16:43:58 -0700403 dprintf(fd, "Storage mounts:\n");
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600404 for (const auto& n : mStorageMounts) {
Keun young Park144a9892021-10-13 16:43:58 -0700405 dprintf(fd, " %s = %s\n", n.first.c_str(), n.second.c_str());
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600406 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700407 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700408
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700409 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600410 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Keun young Park144a9892021-10-13 16:43:58 -0700411 dprintf(fd, "Per-UID cache quotas:\n");
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700412 for (const auto& n : mCacheQuotas) {
Keun young Park144a9892021-10-13 16:43:58 -0700413 dprintf(fd, " %d = %" PRId64 "\n", n.first, n.second);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700414 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700415 }
416
Keun young Park144a9892021-10-13 16:43:58 -0700417 dprintf(fd, "is_dexopt_blocked:%d\n", android::installd::is_dexopt_blocked());
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700418
Jeff Sharkey0274c972016-12-06 09:32:04 -0700419 return NO_ERROR;
420}
421
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600422/**
423 * Perform restorecon of the given path, but only perform recursive restorecon
424 * if the label of that top-level file actually changed. This can save us
425 * significant time by avoiding no-op traversals of large filesystem trees.
426 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700427static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
428 bool existing) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700429 ScopedTrace tracer("restorecon-lazy");
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600430 int res = 0;
431 char* before = nullptr;
432 char* after = nullptr;
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000433 if (!existing) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700434 ScopedTrace tracer("new-path");
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000435 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
436 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
437 PLOG(ERROR) << "Failed recursive restorecon for " << path;
438 goto fail;
439 }
440 return res;
441 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600442
443 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
444 // libselinux. Not needed here.
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600445 if (lgetfilecon(path.c_str(), &before) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600446 PLOG(ERROR) << "Failed before getfilecon for " << path;
447 goto fail;
448 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700449 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600450 PLOG(ERROR) << "Failed top-level restorecon for " << path;
451 goto fail;
452 }
Jeff Sharkey8567ebf2016-10-31 11:22:19 -0600453 if (lgetfilecon(path.c_str(), &after) < 0) {
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600454 PLOG(ERROR) << "Failed after getfilecon for " << path;
455 goto fail;
456 }
457
458 // If the initial top-level restorecon above changed the label, then go
459 // back and restorecon everything recursively
Jeff Vander Stoep4689cdc2021-06-28 18:59:47 +0200460 if (strcmp(before, after)) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700461 ScopedTrace tracer("label-change");
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700462 if (existing) {
463 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
464 << path << "; running recursive restorecon";
465 }
Jeff Sharkey0274c972016-12-06 09:32:04 -0700466 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600467 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
468 PLOG(ERROR) << "Failed recursive restorecon for " << path;
469 goto fail;
470 }
471 }
472
473 goto done;
474fail:
475 res = -1;
476done:
477 free(before);
478 free(after);
479 return res;
480}
Shikha Malhotra976ae002022-02-26 15:39:53 +0000481static bool internal_storage_has_project_id() {
482 // The following path is populated in setFirstBoot, so if this file is present
Shikha Malhotradcf469b2022-03-23 11:53:58 +0000483 // then project ids can be used. Using call once to cache the result of this check
484 // to avoid having to check the file presence again and again.
485 std::call_once(flag, []() {
486 auto using_project_ids =
487 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
488 sUsingProjectIdsFlag = access(using_project_ids.c_str(), F_OK) == 0;
489 });
Shikha Malhotra8f55b3d2022-04-04 14:11:43 +0000490 // return sUsingProjectIdsFlag;
491 return false;
Shikha Malhotra976ae002022-02-26 15:39:53 +0000492}
493
494static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid, gid_t gid,
495 long project_id) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700496 {
497 ScopedTrace tracer("prepare-dir");
498 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
499 PLOG(ERROR) << "Failed to prepare " << path;
500 return -1;
501 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600502 }
Shikha Malhotra976ae002022-02-26 15:39:53 +0000503 if (internal_storage_has_project_id()) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700504 ScopedTrace tracer("set-quota");
Shikha Malhotra976ae002022-02-26 15:39:53 +0000505 return set_quota_project_id(path, project_id, true);
506 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600507 return 0;
508}
509
Shikha Malhotra976ae002022-02-26 15:39:53 +0000510static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
511 uid_t uid, gid_t gid, long project_id) {
512 auto path = StringPrintf("%s/%s", parent.c_str(), name);
Alex Buynytskyya203d712023-06-08 12:56:15 -0700513 int ret;
514 {
515 ScopedTrace tracer("prepare-cache-dir");
516 ret = prepare_app_cache_dir(parent, name, target_mode, uid, gid);
517 }
Shikha Malhotra976ae002022-02-26 15:39:53 +0000518 if (ret == 0 && internal_storage_has_project_id()) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700519 ScopedTrace tracer("set-quota-cache-dir");
Shikha Malhotra976ae002022-02-26 15:39:53 +0000520 return set_quota_project_id(path, project_id, true);
521 }
522 return ret;
523}
524
Calin Juravled2affb82017-11-28 17:41:43 -0800525static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700526 ScopedTrace tracer("prepare-app-profile");
Calin Juravled2affb82017-11-28 17:41:43 -0800527 int32_t uid = multiuser_get_uid(userId, appId);
528 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
529 if (shared_app_gid == -1) {
530 // TODO(calin): this should no longer be possible but do not continue if we don't get
531 // a valid shared gid.
532 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
533 return true;
534 }
535
536 const std::string profile_dir =
537 create_primary_current_profile_package_dir_path(userId, packageName);
538 // read-write-execute only for the app user.
539 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
540 PLOG(ERROR) << "Failed to prepare " << profile_dir;
541 return false;
542 }
Alan Stokes928d2c12020-12-09 10:11:24 +0000543 if (selinux_android_restorecon(profile_dir.c_str(), 0)) {
544 PLOG(ERROR) << "Failed to restorecon " << profile_dir;
545 return false;
546 }
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800547
Calin Juravled2affb82017-11-28 17:41:43 -0800548 const std::string ref_profile_path =
549 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800550
551 // Prepare the reference profile directory. Note that we use the non strict version of
552 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
553 // This is particularly important given that in O there were some fixes for how the
554 // shared_app_gid is computed.
555 //
556 // Note that by the time we get here we know that we are using a correct uid (otherwise
557 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
558 // are sure that the gid being used belongs to the owning app and not someone else.
559 //
560 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
561 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800562 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
563 return false;
564 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800565
Calin Juravled2affb82017-11-28 17:41:43 -0800566 return true;
567}
568
John Wu84e8f242021-10-21 11:50:41 -0700569static bool chown_app_dir(const std::string& path, uid_t uid, uid_t previousUid, gid_t cacheGid) {
570 FTS* fts;
571 char *argv[] = { (char*) path.c_str(), nullptr };
572 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
573 return false;
574 }
575 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
576 if (p->fts_info == FTS_D && p->fts_level == 1
577 && (strcmp(p->fts_name, "cache") == 0
578 || strcmp(p->fts_name, "code_cache") == 0)) {
579 // Mark cache dirs
580 p->fts_number = 1;
581 } else {
582 // Inherit parent's number
583 p->fts_number = p->fts_parent->fts_number;
584 }
585
586 switch (p->fts_info) {
587 case FTS_D:
588 case FTS_F:
589 case FTS_SL:
590 case FTS_SLNONE:
591 if (p->fts_statp->st_uid == previousUid) {
592 if (lchown(p->fts_path, uid, p->fts_number ? cacheGid : uid) != 0) {
593 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
594 }
595 } else {
596 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected UID "
597 << p->fts_statp->st_uid << " instead of " << previousUid;
598 }
599 break;
600 }
601 }
602 fts_close(fts);
603 return true;
604}
605
606static void chown_app_profile_dir(const std::string &packageName, int32_t appId, int32_t userId) {
607 uid_t uid = multiuser_get_uid(userId, appId);
608 gid_t sharedGid = multiuser_get_shared_gid(userId, appId);
609
610 const std::string profile_dir =
611 create_primary_current_profile_package_dir_path(userId, packageName);
612 char *argv[] = { (char*) profile_dir.c_str(), nullptr };
613 if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
614 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
615 switch (p->fts_info) {
616 case FTS_D:
617 case FTS_F:
618 case FTS_SL:
619 case FTS_SLNONE:
620 if (lchown(p->fts_path, uid, uid) != 0) {
621 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
622 }
623 break;
624 }
625 }
626 fts_close(fts);
627 }
628
629 const std::string ref_profile_path =
630 create_primary_reference_profile_package_dir_path(packageName);
631 argv[0] = (char *) ref_profile_path.c_str();
632 if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
633 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
634 if (p->fts_info == FTS_D && p->fts_level == 0) {
635 if (chown(p->fts_path, AID_SYSTEM, sharedGid) != 0) {
636 PLOG(WARNING) << "Failed to chown " << p->fts_path;
637 }
638 continue;
639 }
640 switch (p->fts_info) {
641 case FTS_D:
642 case FTS_F:
643 case FTS_SL:
644 case FTS_SLNONE:
645 if (lchown(p->fts_path, sharedGid, sharedGid) != 0) {
646 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
647 }
648 break;
649 }
650 }
651 fts_close(fts);
652 }
653}
654
Mohammad Samiul Islama73327a2022-03-09 09:59:32 +0000655static binder::Status createAppDataDirs(const std::string& path, int32_t uid, int32_t gid,
John Wu841a8022022-04-05 21:17:54 +0000656 int32_t previousUid, int32_t cacheGid,
Samiul Islam8621e552022-03-30 16:26:45 +0100657 const std::string& seInfo, mode_t targetMode,
658 long projectIdApp, long projectIdCache) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700659 ScopedTrace tracer("create-dirs");
John Wu84e8f242021-10-21 11:50:41 -0700660 struct stat st{};
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000661 bool parent_dir_exists = (stat(path.c_str(), &st) == 0);
662
663 auto cache_path = StringPrintf("%s/%s", path.c_str(), "cache");
664 auto code_cache_path = StringPrintf("%s/%s", path.c_str(), "code_cache");
665 bool cache_exists = (access(cache_path.c_str(), F_OK) == 0);
666 bool code_cache_exists = (access(code_cache_path.c_str(), F_OK) == 0);
667
668 if (parent_dir_exists) {
John Wu841a8022022-04-05 21:17:54 +0000669 if (previousUid > 0 && previousUid != uid) {
670 if (!chown_app_dir(path, uid, previousUid, cacheGid)) {
John Wu84e8f242021-10-21 11:50:41 -0700671 return error("Failed to chown " + path);
672 }
673 }
674 }
675
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000676 // Prepare only the parent app directory
Samiul Islam8621e552022-03-30 16:26:45 +0100677 if (prepare_app_dir(path, targetMode, uid, gid, projectIdApp) ||
678 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid, projectIdCache) ||
679 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid, projectIdCache)) {
John Wu84e8f242021-10-21 11:50:41 -0700680 return error("Failed to prepare " + path);
681 }
682
683 // Consider restorecon over contents if label changed
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000684 if (restorecon_app_data_lazy(path, seInfo, uid, parent_dir_exists)) {
John Wu84e8f242021-10-21 11:50:41 -0700685 return error("Failed to restorecon " + path);
686 }
687
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000688 // If the parent dir exists, the restorecon would already have been done
689 // as a part of the recursive restorecon above
690 if (parent_dir_exists && !cache_exists
691 && restorecon_app_data_lazy(cache_path, seInfo, uid, false)) {
692 return error("Failed to restorecon " + cache_path);
693 }
694
695 // If the parent dir exists, the restorecon would already have been done
696 // as a part of the recursive restorecon above
697 if (parent_dir_exists && !code_cache_exists
698 && restorecon_app_data_lazy(code_cache_path, seInfo, uid, false)) {
699 return error("Failed to restorecon " + code_cache_path);
700 }
John Wu84e8f242021-10-21 11:50:41 -0700701 return ok();
702}
703
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800704binder::Status InstalldNativeService::createAppDataLocked(
705 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
706 int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
707 int32_t targetSdkVersion, int64_t* _aidl_return) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700708 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000709 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700710 CHECK_ARGUMENT_UUID(uuid);
711 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700712
713 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
714 const char* pkgname = packageName.c_str();
715
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700716 // Assume invalid inode unless filled in below
717 if (_aidl_return != nullptr) *_aidl_return = -1;
718
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700719 int32_t uid = multiuser_get_uid(userId, appId);
John Wu84e8f242021-10-21 11:50:41 -0700720
John Wu841a8022022-04-05 21:17:54 +0000721 // If previousAppId > 0, an app is changing its app ID
722 int32_t previousUid =
723 previousAppId > 0 ? (int32_t)multiuser_get_uid(userId, previousAppId) : -1;
John Wu84e8f242021-10-21 11:50:41 -0700724
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700725 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700726 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
727
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700728 // If UID doesn't have a specific cache GID, use UID value
729 if (cacheGid == -1) {
730 cacheGid = uid;
731 }
732
Samiul Islam8621e552022-03-30 16:26:45 +0100733 long projectIdApp = get_project_id(uid, PROJECT_ID_APP_START);
734 long projectIdCache = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
735
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700736 if (flags & FLAG_STORAGE_CE) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700737 ScopedTrace tracer("ce");
Jeff Sharkey0274c972016-12-06 09:32:04 -0700738 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700739
John Wu841a8022022-04-05 21:17:54 +0000740 auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
Samiul Islam8621e552022-03-30 16:26:45 +0100741 projectIdApp, projectIdCache);
John Wu84e8f242021-10-21 11:50:41 -0700742 if (!status.isOk()) {
743 return status;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600744 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600745
746 // Remember inode numbers of cache directories so that we can clear
747 // contents while CE storage is locked
748 if (write_path_inode(path, "cache", kXattrInodeCache) ||
749 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700750 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700751 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700752
753 // And return the CE inode of the top-level data directory so we can
754 // clear contents while CE storage is locked
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000755 if (_aidl_return != nullptr) {
756 ino_t result;
757 if (get_path_inode(path, &result) != 0) {
758 return error("Failed to get_path_inode for " + path);
759 }
760 *_aidl_return = static_cast<uint64_t>(result);
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700761 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700762 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700763 if (flags & FLAG_STORAGE_DE) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700764 ScopedTrace tracer("de");
Jeff Sharkey0274c972016-12-06 09:32:04 -0700765 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700766
John Wu841a8022022-04-05 21:17:54 +0000767 auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
Samiul Islam8621e552022-03-30 16:26:45 +0100768 projectIdApp, projectIdCache);
John Wu84e8f242021-10-21 11:50:41 -0700769 if (!status.isOk()) {
770 return status;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600771 }
John Wu841a8022022-04-05 21:17:54 +0000772 if (previousUid > 0 && previousUid != uid) {
John Wu3b383372022-02-09 02:21:39 -0800773 chown_app_profile_dir(packageName, appId, userId);
774 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600775
Calin Juravled2affb82017-11-28 17:41:43 -0800776 if (!prepare_app_profile_dir(packageName, appId, userId)) {
777 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000778 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700779 }
Samiul Islamc40dff52022-01-14 16:24:48 +0000780
Samiul Islam7d5b1da2022-02-21 15:23:36 +0000781 if (flags & FLAG_STORAGE_SDK) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700782 ScopedTrace tracer("sdk");
Samiul Islam92f5cf02022-02-03 12:45:51 +0000783 // Safe to ignore status since we can retry creating this by calling reconcileSdkData
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000784 auto ignore = createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000785 if (!ignore.isOk()) {
786 PLOG(WARNING) << "Failed to create sdk data package directory for " << packageName;
Samiul Islamc40dff52022-01-14 16:24:48 +0000787 }
Samiul Islam92f5cf02022-02-03 12:45:51 +0000788 } else {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700789 ScopedTrace tracer("destroy-sdk");
Samiul Islam92f5cf02022-02-03 12:45:51 +0000790 // Package does not need sdk storage. Remove it.
Rishabh Singhe84b0b12022-02-02 20:56:13 +0000791 destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
Samiul Islamc40dff52022-01-14 16:24:48 +0000792 }
793
794 return ok();
795}
796
797/**
Samiul Islam92f5cf02022-02-03 12:45:51 +0000798 * Responsible for creating /data/misc_{ce|de}/user/0/sdksandbox/<package-name> directory and other
Samiul Islamc40dff52022-01-14 16:24:48 +0000799 * app level sub directories, such as ./shared
800 */
Samiul Islam92f5cf02022-02-03 12:45:51 +0000801binder::Status InstalldNativeService::createSdkSandboxDataPackageDirectory(
Samiul Islamc40dff52022-01-14 16:24:48 +0000802 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000803 int32_t appId, int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +0000804 ENFORCE_VALID_USER(userId);
805
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000806 int32_t sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
807 if (sdkSandboxUid == -1) {
808 // There no valid sdk sandbox process for this app. Skip creation of data directory
Samiul Islamc40dff52022-01-14 16:24:48 +0000809 return ok();
810 }
811
Samiul Islamc40dff52022-01-14 16:24:48 +0000812 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
813
814 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +0000815 for (int currentFlag : storageFlags) {
Samiul Islamc40dff52022-01-14 16:24:48 +0000816 if ((flags & currentFlag) == 0) {
817 continue;
818 }
819 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
820
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000821 // /data/misc_{ce,de}/<user-id>/sdksandbox directory gets created by vold
Samiul Islamc40dff52022-01-14 16:24:48 +0000822 // during user creation
823
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000824 // Prepare the package directory
Samiul Islam92f5cf02022-02-03 12:45:51 +0000825 auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
826 packageName.c_str());
827#if SDK_DEBUG
828 LOG(DEBUG) << "Creating app-level sdk data directory: " << packagePath;
829#endif
830
Shikha Malhotra976ae002022-02-26 15:39:53 +0000831 if (prepare_app_dir(packagePath, 0751, AID_SYSTEM, AID_SYSTEM, 0)) {
Samiul Islam92f5cf02022-02-03 12:45:51 +0000832 return error("Failed to prepare " + packagePath);
Samiul Islamc40dff52022-01-14 16:24:48 +0000833 }
Samiul Islamc40dff52022-01-14 16:24:48 +0000834 }
835
Jeff Sharkey423e7462016-12-09 18:18:43 -0700836 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700837}
838
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600839binder::Status InstalldNativeService::createAppData(
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800840 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
841 int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
842 int32_t targetSdkVersion, int64_t* _aidl_return) {
843 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000844 ENFORCE_VALID_USER(userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800845 CHECK_ARGUMENT_UUID(uuid);
846 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
847 LOCK_PACKAGE_USER();
848 return createAppDataLocked(uuid, packageName, userId, flags, appId, previousAppId, seInfo,
849 targetSdkVersion, _aidl_return);
850}
851
852binder::Status InstalldNativeService::createAppData(
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600853 const android::os::CreateAppDataArgs& args,
854 android::os::CreateAppDataResult* _aidl_return) {
855 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000856 ENFORCE_VALID_USER(args.userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800857 // Locking is performed depeer in the callstack.
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600858
859 int64_t ceDataInode = -1;
860 auto status = createAppData(args.uuid, args.packageName, args.userId, args.flags, args.appId,
John Wu84e8f242021-10-21 11:50:41 -0700861 args.previousAppId, args.seInfo, args.targetSdkVersion, &ceDataInode);
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600862 _aidl_return->ceDataInode = ceDataInode;
863 _aidl_return->exceptionCode = status.exceptionCode();
864 _aidl_return->exceptionMessage = status.exceptionMessage();
865 return ok();
866}
867
868binder::Status InstalldNativeService::createAppDataBatched(
869 const std::vector<android::os::CreateAppDataArgs>& args,
870 std::vector<android::os::CreateAppDataResult>* _aidl_return) {
871 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000872 for (const auto& arg : args) {
873 ENFORCE_VALID_USER(arg.userId);
874 }
875
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800876 // Locking is performed depeer in the callstack.
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600877
878 std::vector<android::os::CreateAppDataResult> results;
John Wu84e8f242021-10-21 11:50:41 -0700879 for (const auto &arg : args) {
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600880 android::os::CreateAppDataResult result;
881 createAppData(arg, &result);
882 results.push_back(result);
883 }
884 *_aidl_return = results;
885 return ok();
886}
887
Samiul Islam92f5cf02022-02-03 12:45:51 +0000888binder::Status InstalldNativeService::reconcileSdkData(
889 const android::os::ReconcileSdkDataArgs& args) {
Steven Moreland36945362023-07-05 20:29:10 +0000890 ENFORCE_VALID_USER(args.userId);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000891 // Locking is performed depeer in the callstack.
892
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000893 return reconcileSdkData(args.uuid, args.packageName, args.subDirNames, args.userId, args.appId,
894 args.previousAppId, args.seInfo, args.flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000895}
896
897/**
898 * Reconciles per-sdk directory under app-level sdk data directory.
899
900 * E.g. `/data/misc_ce/0/sdksandbox/<package-name>/<sdkPackageName>-<randomSuffix>
901 *
902 * - If the sdk data package directory is missing, we create it first.
903 * - If sdkPackageNames is empty, we delete sdk package directory since it's not needed anymore.
904 * - If a sdk level directory we need to prepare already exist, we skip creating it again. This
905 * is to avoid having same per-sdk directory with different suffix.
906 * - If a sdk level directory exist which is absent from sdkPackageNames, we remove it.
907 */
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000908binder::Status InstalldNativeService::reconcileSdkData(const std::optional<std::string>& uuid,
909 const std::string& packageName,
910 const std::vector<std::string>& subDirNames,
911 int userId, int appId, int previousAppId,
912 const std::string& seInfo, int flags) {
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +0000913 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000914 ENFORCE_VALID_USER(userId);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000915 CHECK_ARGUMENT_UUID(uuid);
916 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000917 LOCK_PACKAGE_USER();
918
919#if SDK_DEBUG
920 LOG(DEBUG) << "Creating per sdk data directory for: " << packageName;
921#endif
922
923 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
924
Samiul Islam92f5cf02022-02-03 12:45:51 +0000925 // Prepare the sdk package directory in case it's missing
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000926 const auto status =
927 createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000928 if (!status.isOk()) {
929 return status;
930 }
931
932 auto res = ok();
933 // We have to create sdk data for CE and DE storage
934 const int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
935 for (int currentFlag : storageFlags) {
936 if ((flags & currentFlag) == 0) {
937 continue;
938 }
939 const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
940
Samiul Islam92f5cf02022-02-03 12:45:51 +0000941 const auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
942 packageName.c_str());
Samiul Islam92f5cf02022-02-03 12:45:51 +0000943
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000944 // Remove existing sub-directories not referred in subDirNames
945 const std::unordered_set<std::string> expectedSubDirNames(subDirNames.begin(),
946 subDirNames.end());
947 const auto subDirHandler = [&packagePath, &expectedSubDirNames,
948 &res](const std::string& subDirName) {
Samiul Islam92f5cf02022-02-03 12:45:51 +0000949 // Remove the per-sdk directory if it is not referred in
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000950 // expectedSubDirNames
951 if (expectedSubDirNames.find(subDirName) == expectedSubDirNames.end()) {
952 auto path = packagePath + "/" + subDirName;
953 if (delete_dir_contents_and_dir(path) != 0) {
954 res = error("Failed to delete " + path);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000955 return;
956 }
Samiul Islam92f5cf02022-02-03 12:45:51 +0000957 }
958 };
959 const int ec = foreach_subdir(packagePath, subDirHandler);
960 if (ec != 0) {
961 res = error("Failed to process subdirs for " + packagePath);
962 continue;
963 }
964
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000965 // Now create the subDirNames
966 for (const auto& subDirName : subDirNames) {
967 const std::string path =
968 create_data_misc_sdk_sandbox_sdk_path(uuid_, isCeData, userId,
969 packageName.c_str(), subDirName.c_str());
Samiul Islam92f5cf02022-02-03 12:45:51 +0000970
971 // Create the directory along with cache and code_cache
972 const int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
973 if (cacheGid == -1) {
974 return exception(binder::Status::EX_ILLEGAL_STATE,
975 StringPrintf("cacheGid cannot be -1 for sdk data"));
976 }
977 const int32_t sandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
978 int32_t previousSandboxUid = multiuser_get_sdk_sandbox_uid(userId, previousAppId);
Samiul Islam8621e552022-03-30 16:26:45 +0100979 int32_t appUid = multiuser_get_uid(userId, appId);
980 long projectIdApp = get_project_id(appUid, PROJECT_ID_APP_START);
981 long projectIdCache = get_project_id(appUid, PROJECT_ID_APP_CACHE_START);
982 auto status =
John Wu841a8022022-04-05 21:17:54 +0000983 createAppDataDirs(path, sandboxUid, AID_NOBODY, previousSandboxUid, cacheGid,
Samiul Islam8621e552022-03-30 16:26:45 +0100984 seInfo, 0700 | S_ISGID, projectIdApp, projectIdCache);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000985 if (!status.isOk()) {
986 res = status;
987 continue;
988 }
989 }
990 }
991
992 return res;
993}
994
Jooyung Han149be4a2020-01-23 12:45:10 +0900995binder::Status InstalldNativeService::migrateAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -0700996 const std::string& packageName, int32_t userId, int32_t flags) {
997 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000998 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700999 CHECK_ARGUMENT_UUID(uuid);
1000 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001001 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001002
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001003 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1004 const char* pkgname = packageName.c_str();
1005
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001006 // This method only exists to upgrade system apps that have requested
1007 // forceDeviceEncrypted, so their default storage always lives in a
1008 // consistent location. This only works on non-FBE devices, since we
1009 // never want to risk exposing data on a device with real CE/DE storage.
1010
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001011 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
1012 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001013
1014 // If neither directory is marked as default, assume CE is default
1015 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
1016 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
1017 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001018 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001019 }
1020 }
1021
1022 // Migrate default data location if needed
1023 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
1024 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
1025
1026 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
1027 LOG(WARNING) << "Requested default storage " << target
1028 << " is not active; migrating from " << source;
1029 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001030 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001031 }
1032 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001033 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001034 }
1035 }
1036
Jeff Sharkey423e7462016-12-09 18:18:43 -07001037 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001038}
1039
Calin Juravle6a1648e2016-02-01 12:12:16 +00001040
Calin Juravle562de812018-01-20 23:34:18 -08001041binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
1042 const std::string& profileName) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001043 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001044 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyydf2fb612022-08-12 15:42:01 -07001045 CHECK_ARGUMENT_FILE_NAME(profileName);
1046 if (!base::EndsWith(profileName, ".prof")) {
1047 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
1048 StringPrintf("Profile name %s does not end with .prof",
1049 profileName.c_str()));
1050 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001051 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001052
Jeff Sharkey423e7462016-12-09 18:18:43 -07001053 binder::Status res = ok();
Calin Juravle562de812018-01-20 23:34:18 -08001054 if (!clear_primary_reference_profile(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001055 res = error("Failed to clear reference profile for " + packageName);
1056 }
Calin Juravle562de812018-01-20 23:34:18 -08001057 if (!clear_primary_current_profiles(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001058 res = error("Failed to clear current profiles for " + packageName);
1059 }
1060 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001061}
1062
Jooyung Han149be4a2020-01-23 12:45:10 +09001063binder::Status InstalldNativeService::clearAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001064 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1065 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001066 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001067 CHECK_ARGUMENT_UUID(uuid);
1068 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001069 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001070
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001071 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1072 const char* pkgname = packageName.c_str();
1073
Jeff Sharkey423e7462016-12-09 18:18:43 -07001074 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001075 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001076 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001077 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1078 path = read_path_inode(path, "cache", kXattrInodeCache);
1079 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1080 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
1081 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001082 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001083 if (delete_dir_contents(path) != 0) {
1084 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +09001085 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
1086 remove_path_xattr(path, kXattrInodeCache);
1087 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001088 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001089 }
1090 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001091 if (flags & FLAG_STORAGE_DE) {
John Wu84e8f242021-10-21 11:50:41 -07001092 std::string suffix;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001093 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1094 suffix = CACHE_DIR_POSTFIX;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001095 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1096 suffix = CODE_CACHE_DIR_POSTFIX;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001097 }
1098
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001099 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001100 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001101 if (delete_dir_contents(path) != 0) {
1102 res = error("Failed to delete contents of " + path);
1103 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001104 }
1105 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001106 if (flags & FLAG_STORAGE_EXTERNAL) {
1107 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1108 for (const auto& n : mStorageMounts) {
1109 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +00001110
1111 if (android::base::GetBoolProperty(kFuseProp, false)) {
1112 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1113 if (std::regex_match(extPath, re)) {
1114 extPath += "/" + std::to_string(userId);
1115 }
1116 } else {
1117 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1118 extPath += StringPrintf("/%d", userId);
1119 } else if (userId != 0) {
1120 // TODO: support devices mounted under secondary users
1121 continue;
1122 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001123 }
Zim0ce832d2019-12-03 17:03:58 +00001124
Jeff Sharkey6e175692019-05-14 14:55:33 -06001125 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1126 // Clear only cached data from shared storage
1127 auto path = StringPrintf("%s/Android/data/%s/cache", extPath.c_str(), pkgname);
1128 if (delete_dir_contents(path, true) != 0) {
1129 res = error("Failed to delete contents of " + path);
1130 }
1131 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1132 // No code cache on shared storage
1133 } else {
1134 // Clear everything on shared storage
1135 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
1136 if (delete_dir_contents(path, true) != 0) {
1137 res = error("Failed to delete contents of " + path);
1138 }
1139 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
1140 if (delete_dir_contents(path, true) != 0) {
1141 res = error("Failed to delete contents of " + path);
1142 }
Martijn Coenen24a93072020-01-08 10:10:43 +01001143 // Note that we explicitly don't delete OBBs - those are only removed on
1144 // app uninstall.
Jeff Sharkey6e175692019-05-14 14:55:33 -06001145 }
1146 }
1147 }
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001148 auto status = clearSdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1149 if (!status.isOk()) {
1150 res = status;
1151 }
1152 return res;
1153}
1154
1155binder::Status InstalldNativeService::clearSdkSandboxDataPackageDirectory(
1156 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1157 int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00001158 ENFORCE_VALID_USER(userId);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001159 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1160 const char* pkgname = packageName.c_str();
1161
1162 binder::Status res = ok();
1163 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1164 for (int i = 0; i < 2; i++) {
1165 int currentFlag = storageFlags[i];
1166 if ((flags & currentFlag) == 0) {
1167 continue;
1168 }
1169 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1170 std::string suffix;
1171 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1172 suffix = CACHE_DIR_POSTFIX;
1173 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1174 suffix = CODE_CACHE_DIR_POSTFIX;
1175 }
1176
1177 auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1178 if (access(appPath.c_str(), F_OK) != 0) continue;
1179 const auto subDirHandler = [&appPath, &res, &suffix](const std::string& filename) {
1180 auto filepath = appPath + "/" + filename + suffix;
1181 if (delete_dir_contents(filepath, true) != 0) {
1182 res = error("Failed to clear contents of " + filepath);
1183 }
1184 };
1185 const int ec = foreach_subdir(appPath, subDirHandler);
1186 if (ec != 0) {
1187 res = error("Failed to process subdirs for " + appPath);
1188 }
1189 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001190 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001191}
1192
Calin Juravle76268c52017-03-09 13:19:42 -08001193static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +01001194 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -08001195 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +01001196 /*ignore_if_missing*/ true);
1197}
1198
Calin Juravle76268c52017-03-09 13:19:42 -08001199static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +01001200 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -08001201 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +01001202 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +00001203}
1204
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001205binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
1206 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001207 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001208 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001209
Jeff Sharkey423e7462016-12-09 18:18:43 -07001210 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +00001211 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1212 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -08001213 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001214 res = error("Failed to destroy current profiles for " + packageName);
1215 }
Calin Juravleedae6692016-03-23 13:55:31 +00001216 }
Calin Juravle76268c52017-03-09 13:19:42 -08001217 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001218 res = error("Failed to destroy reference profile for " + packageName);
1219 }
1220 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +00001221}
1222
Jiakai Zhangee00e3b2022-03-24 15:03:04 +00001223binder::Status InstalldNativeService::deleteReferenceProfile(const std::string& packageName,
1224 const std::string& profileName) {
1225 ENFORCE_UID(AID_SYSTEM);
1226 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1227 LOCK_PACKAGE();
1228
1229 // This function only supports primary dex'es.
1230 std::string path =
1231 create_reference_profile_path(packageName, profileName, /*is_secondary_dex=*/false);
1232 if (unlink(path.c_str()) != 0) {
1233 if (errno == ENOENT) {
1234 return ok();
1235 } else {
1236 return error("Failed to delete profile " + profileName + " for " + packageName);
1237 }
1238 }
1239 return ok();
1240}
1241
Jooyung Han149be4a2020-01-23 12:45:10 +09001242binder::Status InstalldNativeService::destroyAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001243 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1244 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001245 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001246 CHECK_ARGUMENT_UUID(uuid);
1247 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001248 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001249
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001250 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1251 const char* pkgname = packageName.c_str();
1252
Jeff Sharkey423e7462016-12-09 18:18:43 -07001253 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001254 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001255 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08001256 if (rename_delete_dir_contents_and_dir(path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001257 res = error("Failed to delete " + path);
1258 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001259 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001260 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001261 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08001262 if (rename_delete_dir_contents_and_dir(path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001263 res = error("Failed to delete " + path);
1264 }
Alan Stokesd983cc72020-02-14 14:36:58 +00001265 if ((flags & FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES) == 0) {
1266 destroy_app_current_profiles(packageName, userId);
1267 // TODO(calin): If the package is still installed by other users it's probably
1268 // beneficial to keep the reference profile around.
1269 // Verify if it's ok to do that.
1270 destroy_app_reference_profile(packageName);
1271 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001272 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001273 if (flags & FLAG_STORAGE_EXTERNAL) {
1274 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1275 for (const auto& n : mStorageMounts) {
1276 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +00001277
1278 if (android::base::GetBoolProperty(kFuseProp, false)) {
1279 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1280 if (std::regex_match(extPath, re)) {
1281 extPath += "/" + std::to_string(userId);
1282 }
1283 } else {
1284 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1285 extPath += StringPrintf("/%d", userId);
1286 } else if (userId != 0) {
1287 // TODO: support devices mounted under secondary users
1288 continue;
1289 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001290 }
Zim0ce832d2019-12-03 17:03:58 +00001291
Jeff Sharkey6e175692019-05-14 14:55:33 -06001292 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001293 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001294 res = error("Failed to delete contents of " + path);
1295 }
1296 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001297 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001298 res = error("Failed to delete contents of " + path);
1299 }
1300 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001301 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001302 res = error("Failed to delete contents of " + path);
1303 }
1304 }
1305 }
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001306 auto status = destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1307 if (!status.isOk()) {
1308 res = status;
1309 }
1310 return res;
1311}
1312
1313binder::Status InstalldNativeService::destroySdkSandboxDataPackageDirectory(
1314 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1315 int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00001316 ENFORCE_VALID_USER(userId);
1317
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001318 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1319 const char* pkgname = packageName.c_str();
1320
1321 binder::Status res = ok();
1322 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1323 for (int i = 0; i < 2; i++) {
1324 int currentFlag = storageFlags[i];
1325 if ((flags & currentFlag) == 0) {
1326 continue;
1327 }
1328 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1329 auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1330 if (rename_delete_dir_contents_and_dir(appPath) != 0) {
1331 res = error("Failed to delete " + appPath);
1332 }
1333 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001334 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001335}
1336
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001337static gid_t get_cache_gid(uid_t uid) {
1338 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
1339 return (gid != -1) ? gid : uid;
1340}
1341
Jooyung Han149be4a2020-01-23 12:45:10 +09001342binder::Status InstalldNativeService::fixupAppData(const std::optional<std::string>& uuid,
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001343 int32_t flags) {
1344 ENFORCE_UID(AID_SYSTEM);
1345 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001346
1347 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001348 for (auto userId : get_known_users(uuid_)) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001349 LOCK_USER();
Zim23457d02022-08-17 12:57:41 +01001350 atrace_pm_begin("fixup user");
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001351 FTS* fts;
1352 FTSENT* p;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001353 auto ce_path = create_data_user_ce_path(uuid_, userId);
1354 auto de_path = create_data_user_de_path(uuid_, userId);
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001355 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001356 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001357 return error("Failed to fts_open");
1358 }
1359 while ((p = fts_read(fts)) != nullptr) {
1360 if (p->fts_info == FTS_D && p->fts_level == 1) {
1361 // Track down inodes of cache directories
1362 uint64_t raw = 0;
1363 ino_t inode_cache = 0;
1364 ino_t inode_code_cache = 0;
1365 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1366 inode_cache = raw;
1367 }
1368 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1369 inode_code_cache = raw;
1370 }
1371
1372 // Figure out expected GID of each child
1373 FTSENT* child = fts_children(fts, 0);
1374 while (child != nullptr) {
1375 if ((child->fts_statp->st_ino == inode_cache)
1376 || (child->fts_statp->st_ino == inode_code_cache)
1377 || !strcmp(child->fts_name, "cache")
1378 || !strcmp(child->fts_name, "code_cache")) {
1379 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
1380 } else {
1381 child->fts_number = p->fts_statp->st_uid;
1382 }
1383 child = child->fts_link;
1384 }
1385 } else if (p->fts_level >= 2) {
1386 if (p->fts_level > 2) {
1387 // Inherit GID from parent once we're deeper into tree
1388 p->fts_number = p->fts_parent->fts_number;
1389 }
1390
1391 uid_t uid = p->fts_parent->fts_statp->st_uid;
1392 gid_t cache_gid = get_cache_gid(uid);
1393 gid_t expected = p->fts_number;
1394 gid_t actual = p->fts_statp->st_gid;
1395 if (actual == expected) {
1396#if FIXUP_DEBUG
1397 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
1398#endif
1399 if (!(flags & FLAG_FORCE)) {
1400 fts_set(fts, p, FTS_SKIP);
1401 }
1402 } else if ((actual == uid) || (actual == cache_gid)) {
1403 // Only consider fixing up when current GID belongs to app
1404 if (p->fts_info != FTS_D) {
1405 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
1406 << " instead of " << expected;
1407 }
1408 switch (p->fts_info) {
1409 case FTS_DP:
1410 // If we're moving towards cache GID, we need to set S_ISGID
1411 if (expected == cache_gid) {
1412 if (chmod(p->fts_path, 02771) != 0) {
1413 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1414 }
1415 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001416 [[fallthrough]]; // also set GID
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001417 case FTS_F:
1418 if (chown(p->fts_path, -1, expected) != 0) {
1419 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1420 }
1421 break;
1422 case FTS_SL:
1423 case FTS_SLNONE:
1424 if (lchown(p->fts_path, -1, expected) != 0) {
1425 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1426 }
1427 break;
1428 }
1429 } else {
1430 // Ignore all other GID transitions, since they're kinda shady
1431 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
1432 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -06001433 if (!(flags & FLAG_FORCE)) {
1434 fts_set(fts, p, FTS_SKIP);
1435 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001436 }
1437 }
1438 }
1439 fts_close(fts);
Zim23457d02022-08-17 12:57:41 +01001440 atrace_pm_end();
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001441 }
1442 return ok();
1443}
1444
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001445static int32_t copy_directory_recursive(const char* from, const char* to) {
Dario Freni918beeb2021-12-22 01:00:01 +00001446 char* argv[] =
1447 {(char*)kCpPath,
1448 (char*)"-F", /* delete any existing destination file first (--remove-destination) */
1449 (char*)"--preserve=mode,ownership,timestamps,xattr", /* preserve properties */
1450 (char*)"-R", /* recurse into subdirectories (DEST must be a directory) */
1451 (char*)"-P", /* Do not follow symlinks [default] */
1452 (char*)"-d", /* don't dereference symlinks */
1453 (char*)from,
1454 (char*)to};
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001455
1456 LOG(DEBUG) << "Copying " << from << " to " << to;
Tom Cherrye79cde52019-09-25 16:51:56 -07001457 return logwrap_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, LOG_ALOG, false, nullptr);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001458}
1459
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001460binder::Status InstalldNativeService::snapshotAppData(const std::optional<std::string>& volumeUuid,
1461 const std::string& packageName,
1462 int32_t userId, int32_t snapshotId,
1463 int32_t storageFlags, int64_t* _aidl_return) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001464 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001465 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001466 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001467 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001468 LOCK_PACKAGE_USER();
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001469
1470 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1471 const char* package_name = packageName.c_str();
1472
1473 binder::Status res = ok();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001474 // Default result to 0, it will be populated with inode of ce data snapshot
1475 // if FLAG_STORAGE_CE has been passed.
1476 if (_aidl_return != nullptr) *_aidl_return = 0;
1477
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001478 bool clear_ce_on_exit = false;
1479 bool clear_de_on_exit = false;
1480
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001481 auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &userId, &package_name,
1482 &snapshotId] {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001483 if (clear_de_on_exit) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001484 auto to = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1485 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001486 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1487 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1488 }
1489 }
1490
1491 if (clear_ce_on_exit) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001492 auto to = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1493 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001494 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1495 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1496 }
1497 }
1498 };
1499
1500 auto scope_guard = android::base::make_scope_guard(deleter);
1501
JW Wang1d643c72020-10-06 13:42:41 +08001502 if (storageFlags & FLAG_STORAGE_DE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001503 auto from = create_data_user_de_package_path(volume_uuid, userId, package_name);
1504 auto to = create_data_misc_de_rollback_path(volume_uuid, userId, snapshotId);
1505 auto rollback_package_path =
1506 create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1507 package_name);
JW Wang1d643c72020-10-06 13:42:41 +08001508
1509 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1510 if (rc != 0) {
1511 return error(rc, "Failed to create folder " + to);
1512 }
1513
1514 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1515 if (rc != 0) {
1516 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1517 }
1518
1519 // Check if we have data to copy.
1520 if (access(from.c_str(), F_OK) == 0) {
1521 rc = copy_directory_recursive(from.c_str(), to.c_str());
1522 }
1523 if (rc != 0) {
1524 res = error(rc, "Failed copying " + from + " to " + to);
1525 clear_de_on_exit = true;
1526 return res;
1527 }
1528 }
1529
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001530 // The app may not have any data at all, in which case it's OK to skip here.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001531 auto from_ce = create_data_user_ce_package_path(volume_uuid, userId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001532 if (access(from_ce.c_str(), F_OK) != 0) {
1533 LOG(INFO) << "Missing source " << from_ce;
1534 return ok();
1535 }
1536
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001537 // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001538 binder::Status clear_cache_result =
1539 clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001540 if (!clear_cache_result.isOk()) {
1541 // It should be fine to continue snapshot if we for some reason failed
1542 // to clear cache.
1543 LOG(WARNING) << "Failed to clear cache of app " << packageName;
1544 }
1545
1546 // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001547 binder::Status clear_code_cache_result =
1548 clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY,
1549 0);
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001550 if (!clear_code_cache_result.isOk()) {
1551 // It should be fine to continue snapshot if we for some reason failed
1552 // to clear code_cache.
1553 LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
1554 }
1555
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001556 if (storageFlags & FLAG_STORAGE_CE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001557 auto from = create_data_user_ce_package_path(volume_uuid, userId, package_name);
1558 auto to = create_data_misc_ce_rollback_path(volume_uuid, userId, snapshotId);
1559 auto rollback_package_path =
1560 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1561 package_name);
Nikita Ioffe835ae772019-01-23 16:32:13 +00001562
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001563 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1564 if (rc != 0) {
1565 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +00001566 }
1567
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001568 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1569 if (rc != 0) {
1570 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1571 }
1572
1573 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001574 if (rc != 0) {
1575 res = error(rc, "Failed copying " + from + " to " + to);
1576 clear_ce_on_exit = true;
1577 return res;
1578 }
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001579 if (_aidl_return != nullptr) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001580 auto ce_snapshot_path =
1581 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1582 package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001583 rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
1584 if (rc != 0) {
1585 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
1586 clear_ce_on_exit = true;
1587 return res;
1588 }
1589 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001590 }
1591
1592 return res;
1593}
1594
1595binder::Status InstalldNativeService::restoreAppDataSnapshot(
Jooyung Han149be4a2020-01-23 12:45:10 +09001596 const std::optional<std::string>& volumeUuid, const std::string& packageName,
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001597 const int32_t appId, const std::string& seInfo, const int32_t userId,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001598 const int32_t snapshotId, int32_t storageFlags) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001599 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001600 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001601 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001602 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001603 LOCK_PACKAGE_USER();
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001604
1605 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1606 const char* package_name = packageName.c_str();
1607
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001608 auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1609 package_name);
1610 auto from_de = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1611 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001612
1613 const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
1614 (access(from_ce.c_str(), F_OK) == 0);
1615 const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
1616 (access(from_de.c_str(), F_OK) == 0);
1617
1618 if (!needs_ce_rollback && !needs_de_rollback) {
1619 return ok();
1620 }
1621
1622 // We know we're going to rollback one of the CE or DE data, so we clear
1623 // application data first. Note that it's possible that we're asked to
1624 // restore both CE & DE data but that one of the restores fail. Leaving the
1625 // app with no data in those cases is arguably better than leaving the app
1626 // with mismatched / stale data.
1627 LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001628 // It's fine to pass 0 as ceDataInode here, because restoreAppDataSnapshot
1629 // can only be called when user unlocks the phone, meaning that CE user data
1630 // is decrypted.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001631 binder::Status res =
1632 clearAppData(volumeUuid, packageName, userId, storageFlags, 0 /* ceDataInode */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001633 if (!res.isOk()) {
1634 return res;
1635 }
1636
1637 if (needs_ce_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001638 auto to_ce = create_data_user_ce_path(volume_uuid, userId);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001639 int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
1640 if (rc != 0) {
1641 res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
1642 return res;
1643 }
JW Wangfda19ec2020-05-18 16:54:08 +08001644 delete_dir_contents_and_dir(from_ce, true /* ignore_if_missing */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001645 }
1646
1647 if (needs_de_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001648 auto to_de = create_data_user_de_path(volume_uuid, userId);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001649 int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
1650 if (rc != 0) {
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001651 if (needs_ce_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001652 auto ce_data = create_data_user_ce_package_path(volume_uuid, userId, package_name);
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001653 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
1654 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
1655 LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
1656 }
1657 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001658 res = error(rc, "Failed copying " + from_de + " to " + to_de);
1659 return res;
1660 }
JW Wangfda19ec2020-05-18 16:54:08 +08001661 delete_dir_contents_and_dir(from_de, true /* ignore_if_missing */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001662 }
1663
1664 // Finally, restore the SELinux label on the app data.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001665 return restoreconAppData(volumeUuid, packageName, userId, storageFlags, appId, seInfo);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001666}
1667
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001668binder::Status InstalldNativeService::destroyAppDataSnapshot(
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001669 const std::optional<std::string>& volumeUuid, const std::string& packageName,
1670 const int32_t userId, const int64_t ceSnapshotInode, const int32_t snapshotId,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001671 int32_t storageFlags) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001672 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001673 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001674 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1675 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001676 LOCK_PACKAGE_USER();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001677
1678 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1679 const char* package_name = packageName.c_str();
1680
1681 if (storageFlags & FLAG_STORAGE_DE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001682 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid, userId,
1683 snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001684
1685 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
1686 if (res != 0) {
1687 return error(res, "Failed clearing snapshot " + de_snapshot_path);
1688 }
1689 }
1690
1691 if (storageFlags & FLAG_STORAGE_CE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001692 auto ce_snapshot_path =
1693 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1694 package_name, ceSnapshotInode);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001695 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
1696 if (res != 0) {
1697 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
1698 }
1699 }
1700 return ok();
1701}
1702
Oli Lanc7789572020-03-16 18:18:41 +00001703binder::Status InstalldNativeService::destroyCeSnapshotsNotSpecified(
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001704 const std::optional<std::string>& volumeUuid, const int32_t userId,
Oli Lanc7789572020-03-16 18:18:41 +00001705 const std::vector<int32_t>& retainSnapshotIds) {
1706 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001707 ENFORCE_VALID_USER(userId);
Oli Lanc7789572020-03-16 18:18:41 +00001708 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001709 LOCK_USER();
Oli Lanc7789572020-03-16 18:18:41 +00001710
1711 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1712
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001713 auto base_path = create_data_misc_ce_rollback_base_path(volume_uuid, userId);
Oli Lanc7789572020-03-16 18:18:41 +00001714
1715 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(base_path.c_str()), closedir);
1716 if (!dir) {
1717 return error(-1, "Failed to open rollback base dir " + base_path);
1718 }
1719
1720 struct dirent* ent;
1721 while ((ent = readdir(dir.get()))) {
1722 if (ent->d_type != DT_DIR) {
1723 continue;
1724 }
1725
1726 uint snapshot_id;
1727 bool parse_ok = ParseUint(ent->d_name, &snapshot_id);
1728 if (parse_ok &&
1729 std::find(retainSnapshotIds.begin(), retainSnapshotIds.end(),
1730 snapshot_id) == retainSnapshotIds.end()) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001731 auto rollback_path =
1732 create_data_misc_ce_rollback_path(volume_uuid, userId, snapshot_id);
Oli Lanc7789572020-03-16 18:18:41 +00001733 int res = delete_dir_contents_and_dir(rollback_path, true /* ignore_if_missing */);
1734 if (res != 0) {
1735 return error(res, "Failed clearing snapshot " + rollback_path);
1736 }
1737 }
1738 }
1739 return ok();
1740}
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001741
Jooyung Han149be4a2020-01-23 12:45:10 +09001742binder::Status InstalldNativeService::moveCompleteApp(const std::optional<std::string>& fromUuid,
1743 const std::optional<std::string>& toUuid, const std::string& packageName,
Songchun Fandc2083f2020-02-18 17:45:46 -08001744 int32_t appId, const std::string& seInfo,
Songchun Fanaed33372020-02-05 12:02:22 -08001745 int32_t targetSdkVersion, const std::string& fromCodePath) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001746 ENFORCE_UID(AID_SYSTEM);
1747 CHECK_ARGUMENT_UUID(fromUuid);
1748 CHECK_ARGUMENT_UUID(toUuid);
1749 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001750 LOCK_PACKAGE();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001751
1752 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1753 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1754 const char* package_name = packageName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001755
Jeff Sharkey423e7462016-12-09 18:18:43 -07001756 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001757 std::vector<userid_t> users = get_known_users(from_uuid);
1758
Songchun Fandc2083f2020-02-18 17:45:46 -08001759 auto to_app_package_path_parent = create_data_app_path(to_uuid);
1760 auto to_app_package_path = StringPrintf("%s/%s", to_app_package_path_parent.c_str(),
1761 android::base::Basename(fromCodePath).c_str());
1762
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001763 // Copy app
1764 {
Songchun Fandc2083f2020-02-18 17:45:46 -08001765 int rc = copy_directory_recursive(fromCodePath.c_str(), to_app_package_path_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001766 if (rc != 0) {
Songchun Fandc2083f2020-02-18 17:45:46 -08001767 res = error(rc, "Failed copying " + fromCodePath + " to " + to_app_package_path);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001768 goto fail;
1769 }
1770
Songchun Fandc2083f2020-02-18 17:45:46 -08001771 if (selinux_android_restorecon(to_app_package_path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
1772 res = error("Failed to restorecon " + to_app_package_path);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001773 goto fail;
1774 }
1775 }
1776
1777 // Copy private data for all known users
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001778 for (auto userId : users) {
1779 LOCK_USER();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001780
1781 // Data source may not exist for all users; that's okay
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001782 auto from_ce = create_data_user_ce_package_path(from_uuid, userId, package_name);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001783 if (access(from_ce.c_str(), F_OK) != 0) {
1784 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001785 continue;
1786 }
1787
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001788 if (!createAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1789 appId, /* previousAppId */ -1, seInfo, targetSdkVersion, nullptr)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001790 .isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001791 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001792 goto fail;
1793 }
Jeff Sharkey51c94492016-05-10 17:46:39 -06001794 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001795 auto from = create_data_user_de_package_path(from_uuid, userId, package_name);
1796 auto to = create_data_user_de_path(to_uuid, userId);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001797
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001798 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001799 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001800 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001801 goto fail;
1802 }
1803 }
1804 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001805 auto from = create_data_user_ce_package_path(from_uuid, userId, package_name);
1806 auto to = create_data_user_ce_path(to_uuid, userId);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001807
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001808 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001809 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001810 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001811 goto fail;
1812 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001813 }
1814
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001815 if (!restoreconAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1816 appId, seInfo)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001817 .isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001818 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001819 goto fail;
1820 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001821 }
1822
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001823 // Copy sdk data for all known users
1824 for (auto userId : users) {
1825 LOCK_USER();
1826
1827 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1828 for (int currentFlag : storageFlags) {
1829 const bool isCeData = currentFlag == FLAG_STORAGE_CE;
1830
1831 const auto from = create_data_misc_sdk_sandbox_package_path(from_uuid, isCeData, userId,
1832 package_name);
1833 if (access(from.c_str(), F_OK) != 0) {
1834 LOG(INFO) << "Missing source " << from;
1835 continue;
1836 }
1837 const auto to = create_data_misc_sdk_sandbox_path(to_uuid, isCeData, userId);
1838
1839 const int rc = copy_directory_recursive(from.c_str(), to.c_str());
1840 if (rc != 0) {
1841 res = error(rc, "Failed copying " + from + " to " + to);
1842 goto fail;
1843 }
1844 }
1845
1846 if (!restoreconSdkDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1847 appId, seInfo)
1848 .isOk()) {
1849 res = error("Failed to restorecon");
1850 goto fail;
1851 }
1852 }
Jeff Sharkey31f08982015-07-07 13:31:37 -07001853 // We let the framework scan the new location and persist that before
1854 // deleting the data in the old location; this ordering ensures that
1855 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001856 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001857
1858fail:
1859 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001860 {
Songchun Fandc2083f2020-02-18 17:45:46 -08001861 if (delete_dir_contents(to_app_package_path.c_str(), 1, nullptr) != 0) {
1862 LOG(WARNING) << "Failed to rollback " << to_app_package_path;
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001863 }
1864 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001865 for (auto userId : users) {
1866 LOCK_USER();
Jeff Sharkey51c94492016-05-10 17:46:39 -06001867 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001868 auto to = create_data_user_de_package_path(to_uuid, userId, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001869 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001870 LOG(WARNING) << "Failed to rollback " << to;
1871 }
1872 }
1873 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001874 auto to = create_data_user_ce_package_path(to_uuid, userId, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001875 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001876 LOG(WARNING) << "Failed to rollback " << to;
1877 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001878 }
1879 }
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001880 for (auto userId : users) {
1881 LOCK_USER();
1882 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1883 for (int currentFlag : storageFlags) {
1884 const bool isCeData = currentFlag == FLAG_STORAGE_CE;
1885 const auto to = create_data_misc_sdk_sandbox_package_path(to_uuid, isCeData, userId,
1886 package_name);
1887 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1888 LOG(WARNING) << "Failed to rollback " << to;
1889 }
1890 }
1891 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001892 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001893}
1894
Jooyung Han149be4a2020-01-23 12:45:10 +09001895binder::Status InstalldNativeService::createUserData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001896 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
1897 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001898 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001899 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001900 LOCK_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001901
Alex Buynytskyya203d712023-06-08 12:56:15 -07001902 ScopedTrace tracer("create-user-data");
1903
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001904 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001905 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001906 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001907 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001908 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07001909 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001910 }
1911 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06001912
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07001913 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001914}
1915
Jooyung Han149be4a2020-01-23 12:45:10 +09001916binder::Status InstalldNativeService::destroyUserData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001917 int32_t userId, int32_t flags) {
1918 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001919 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001920 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001921 LOCK_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001922
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001923 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07001924 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001925 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001926 auto path = create_data_user_de_path(uuid_, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00001927 // Contents only, as vold is responsible for the user_de dir itself.
1928 if (delete_dir_contents(path, true) != 0) {
1929 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001930 }
Rishabh Singh8d784372022-03-09 15:54:46 +00001931 auto sdk_sandbox_de_path =
1932 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
1933 if (delete_dir_contents_and_dir(sdk_sandbox_de_path, true) != 0) {
1934 res = error("Failed to delete " + sdk_sandbox_de_path);
1935 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001936 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001937 path = create_data_misc_legacy_path(userId);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001938 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001939 res = error("Failed to delete " + path);
1940 }
Calin Juravle114f0812017-03-08 19:05:07 -08001941 path = create_primary_cur_profile_dir_path(userId);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001942 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001943 res = error("Failed to delete " + path);
1944 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001945 }
Robin Lee095c7632014-04-25 15:05:19 +01001946 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001947 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001948 auto path = create_data_user_ce_path(uuid_, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00001949 // Contents only, as vold is responsible for the user_ce dir itself.
1950 if (delete_dir_contents(path, true) != 0) {
1951 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001952 }
Rishabh Singh8d784372022-03-09 15:54:46 +00001953 auto sdk_sandbox_ce_path =
1954 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
1955 if (delete_dir_contents_and_dir(sdk_sandbox_ce_path, true) != 0) {
1956 res = error("Failed to delete " + sdk_sandbox_ce_path);
1957 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06001958 path = findDataMediaPath(uuid, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00001959 // Contents only, as vold is responsible for the media dir itself.
1960 if (delete_dir_contents(path, true) != 0) {
1961 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001962 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06001963 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001964 return res;
Robin Lee095c7632014-04-25 15:05:19 +01001965}
1966
Jooyung Han149be4a2020-01-23 12:45:10 +09001967binder::Status InstalldNativeService::freeCache(const std::optional<std::string>& uuid,
Neharika Jali0e542312021-10-25 06:41:24 +00001968 int64_t targetFreeBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001969 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001970 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001971#ifndef GRANULAR_LOCKS
1972 std::lock_guard lock(mLock);
1973#endif // !GRANULAR_LOCKS
Jeff Sharkey423e7462016-12-09 18:18:43 -07001974
Jooyung Han149be4a2020-01-23 12:45:10 +09001975 auto uuidString = uuid.value_or("");
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001976 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001977 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001978 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Neharika Jali1d667a22021-10-25 19:36:18 +00001979 auto defy_target = (flags & FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07001980
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001981 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001982 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001983 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001984 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001985
Jeff Sharkey60f8a532017-05-30 14:38:42 -06001986 int64_t needed = targetFreeBytes - free;
Neharika Jali1d667a22021-10-25 19:36:18 +00001987 if (!defy_target) {
1988 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
1989 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001990
Neharika Jali1d667a22021-10-25 19:36:18 +00001991 if (free >= targetFreeBytes) {
1992 return ok();
1993 }
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06001994 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001995
Jeff Sharkey88ddd942017-01-17 18:05:54 -07001996 if (flags & FLAG_FREE_CACHE_V2) {
1997 // This new cache strategy fairly removes files from UIDs by deleting
1998 // files from the UIDs which are most over their allocated quota
1999
2000 // 1. Create trackers for every known UID
Zim23457d02022-08-17 12:57:41 +01002001 atrace_pm_begin("create");
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002002 const auto users = get_known_users(uuid_);
2003#ifdef GRANULAR_LOCKS
2004 std::vector<UserLock> userLocks;
2005 userLocks.reserve(users.size());
2006 std::vector<UserWriteLockGuard> lockGuards;
2007 lockGuards.reserve(users.size());
2008#endif // GRANULAR_LOCKS
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002009 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002010 for (auto userId : users) {
2011#ifdef GRANULAR_LOCKS
2012 userLocks.emplace_back(userId, mUserIdLock, mLock);
2013 lockGuards.emplace_back(userLocks.back());
2014#endif // GRANULAR_LOCKS
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002015 FTS *fts;
2016 FTSENT *p;
Samiul Islama2198092022-05-07 23:22:45 +01002017
2018 // Create a list of data paths whose children have cache directories
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002019 auto ce_path = create_data_user_ce_path(uuid_, userId);
2020 auto de_path = create_data_user_de_path(uuid_, userId);
2021 auto media_path = findDataMediaPath(uuid, userId) + "/Android/data/";
Samiul Islama2198092022-05-07 23:22:45 +01002022 auto ce_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2023 auto de_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
2024
2025 std::vector<std::string> dataPaths = {ce_path, de_path, media_path};
2026 foreach_subdir(ce_sdk_path, [&ce_sdk_path, &dataPaths](const std::string subDir) {
2027 const auto fullpath = ce_sdk_path + "/" + subDir;
2028 dataPaths.push_back(fullpath);
2029 });
2030 foreach_subdir(de_sdk_path, [&de_sdk_path, &dataPaths](const std::string subDir) {
2031 const auto fullpath = de_sdk_path + "/" + subDir;
2032 dataPaths.push_back((char*)fullpath.c_str());
2033 });
2034
2035 char* argv[dataPaths.size() + 1];
2036 for (unsigned int i = 0; i < dataPaths.size(); i++) {
2037 argv[i] = (char*)dataPaths[i].c_str();
2038 }
2039 argv[dataPaths.size()] = nullptr;
2040
Yi Konge7bf3772018-07-17 16:16:24 -07002041 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002042 return error("Failed to fts_open");
2043 }
Yi Konge7bf3772018-07-17 16:16:24 -07002044 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002045 if (p->fts_info == FTS_D && p->fts_level == 1) {
2046 uid_t uid = p->fts_statp->st_uid;
Samiul Islama2198092022-05-07 23:22:45 +01002047
2048 // If uid belongs to sdk sandbox, then the cache should be attributed to the
2049 // original client app.
2050 const auto client_uid = multiuser_convert_sdk_sandbox_to_app_uid(uid);
2051 const bool isSandboxUid = (client_uid != (uid_t)-1);
2052 if (isSandboxUid) uid = client_uid;
2053
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002054 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
2055 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
2056 + AID_APP_START;
2057 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002058 auto search = trackers.find(uid);
2059 if (search != trackers.end()) {
2060 search->second->addDataPath(p->fts_path);
2061 } else {
2062 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06002063 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002064 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002065 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002066 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002067 tracker->cacheQuota = mCacheQuotas[uid];
2068 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002069 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002070#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002071 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002072#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002073 tracker->cacheQuota = 67108864;
2074 }
2075 trackers[uid] = tracker;
2076 }
2077 fts_set(fts, p, FTS_SKIP);
2078 }
2079 }
2080 fts_close(fts);
2081 }
Zim23457d02022-08-17 12:57:41 +01002082 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002083
2084 // 2. Populate tracker stats and insert into priority queue
Zim23457d02022-08-17 12:57:41 +01002085 atrace_pm_begin("populate");
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002086 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
2087 return (left->getCacheRatio() < right->getCacheRatio());
2088 };
2089 std::priority_queue<std::shared_ptr<CacheTracker>,
2090 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
2091 for (const auto& it : trackers) {
2092 it.second->loadStats();
2093 queue.push(it.second);
2094 }
Zim23457d02022-08-17 12:57:41 +01002095 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002096
2097 // 3. Bounce across the queue, freeing items from whichever tracker is
2098 // the most over their assigned quota
Zim23457d02022-08-17 12:57:41 +01002099 atrace_pm_begin("bounce");
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002100 std::shared_ptr<CacheTracker> active;
2101 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07002102 // Only look at apps under quota when explicitly requested
2103 if (active && (active->getCacheRatio() < 10000)
2104 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
2105 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
2106 << " isn't over quota, and defy not requested";
2107 break;
2108 }
2109
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002110 // Find the best tracker to work with; this might involve swapping
2111 // if the active tracker is no longer the most over quota
2112 bool nextBetter = active && !queue.empty()
2113 && active->getCacheRatio() < queue.top()->getCacheRatio();
2114 if (!active || nextBetter) {
2115 if (active) {
2116 // Current tracker still has items, so we'll consider it
2117 // again later once it bubbles up to surface
2118 queue.push(active);
2119 }
2120 active = queue.top(); queue.pop();
2121 active->ensureItems();
2122 continue;
2123 }
2124
2125 // If no items remain, go find another tracker
2126 if (active->items.empty()) {
2127 active = nullptr;
2128 continue;
2129 } else {
2130 auto item = active->items.back();
2131 active->items.pop_back();
2132
2133 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
2134 if (!noop) {
2135 item->purge();
2136 }
2137 active->cacheUsed -= item->size;
2138 needed -= item->size;
2139 }
2140
Neharika Jali1d667a22021-10-25 19:36:18 +00002141 if (!defy_target) {
2142 // Verify that we're actually done before bailing, since sneaky
2143 // apps might be using hardlinks
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002144 if (needed <= 0) {
Neharika Jali1d667a22021-10-25 19:36:18 +00002145 free = data_disk_free(data_path);
2146 needed = targetFreeBytes - free;
2147 if (needed <= 0) {
2148 break;
2149 } else {
2150 LOG(WARNING) << "Expected to be done but still need " << needed;
2151 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002152 }
2153 }
2154 }
Zim23457d02022-08-17 12:57:41 +01002155 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002156
2157 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06002158 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07002159 }
2160
Neharika Jali1d667a22021-10-25 19:36:18 +00002161 if (!defy_target) {
2162 free = data_disk_free(data_path);
2163 if (free >= targetFreeBytes) {
2164 return ok();
2165 } else {
2166 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
2167 targetFreeBytes, data_path.c_str(), free));
2168 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002169 } else {
Neharika Jali1d667a22021-10-25 19:36:18 +00002170 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002171 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002172}
2173
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002174binder::Status InstalldNativeService::rmdex(const std::string& codePath,
2175 const std::string& instructionSet) {
2176 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002177 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002178
Mike Lockwood94afecf2012-10-24 10:45:23 -07002179 char dex_path[PKG_PATH_MAX];
2180
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002181 const char* path = codePath.c_str();
2182 const char* instruction_set = instructionSet.c_str();
2183
Jeff Sharkey770180a2014-09-08 17:14:26 -07002184 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002185 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07002186 }
2187
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002188 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002189 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002190 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002191
2192 ALOGV("unlink %s\n", dex_path);
2193 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07002194 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
2195 // but could not be unlinked.
2196 if (errno != ENOENT) {
2197 return error(StringPrintf("Failed to unlink %s", dex_path));
2198 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002199 }
Calin Juravle249f2d32017-05-03 17:22:27 -07002200 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002201}
2202
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002203struct stats {
2204 int64_t codeSize;
2205 int64_t dataSize;
2206 int64_t cacheSize;
2207};
2208
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002209#if MEASURE_DEBUG
2210static std::string toString(std::vector<int64_t> values) {
2211 std::stringstream res;
2212 res << "[";
2213 for (size_t i = 0; i < values.size(); i++) {
2214 res << values[i];
2215 if (i < values.size() - 1) {
2216 res << ",";
2217 }
2218 }
2219 res << "]";
2220 return res.str();
2221}
2222#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002223
Shikha Malhotra976ae002022-02-26 15:39:53 +00002224// On devices without sdcardfs, if internal and external are on
2225// the same volume, a uid such as u0_a123 is used for both
2226// internal and external storage; therefore, subtract that
2227// amount from internal to make sure we don't count it double.
2228// This needs to happen for data, cache and OBB
2229static void deductDoubleSpaceIfNeeded(stats* stats, int64_t doubleSpaceToBeDeleted, uid_t uid,
2230 const std::string& uuid) {
2231 if (!supports_sdcardfs()) {
2232 stats->dataSize -= doubleSpaceToBeDeleted;
2233 long obbProjectId = get_project_id(uid, PROJECT_ID_EXT_OBB_START);
2234 int64_t appObbSize = GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2235 stats->dataSize -= appObbSize;
2236 }
2237}
2238
Risan5f308262018-10-26 12:06:58 -06002239static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002240 int32_t appId, struct stats* stats, struct stats* extStats) {
Shikha Malhotra976ae002022-02-26 15:39:53 +00002241 int64_t space, doubleSpaceToBeDeleted = 0;
Martijn Coenen771cc342020-02-19 23:26:56 +01002242 uid_t uid = multiuser_get_uid(userId, appId);
Shikha Malhotra976ae002022-02-26 15:39:53 +00002243 static const bool supportsProjectId = internal_storage_has_project_id();
2244
2245 if (extStats != nullptr) {
2246 space = get_occupied_app_space_external(uuid, userId, appId);
2247
2248 if (space != -1) {
2249 extStats->dataSize += space;
2250 doubleSpaceToBeDeleted += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002251 }
2252
Shikha Malhotra976ae002022-02-26 15:39:53 +00002253 space = get_occupied_app_cache_space_external(uuid, userId, appId);
2254 if (space != -1) {
2255 extStats->dataSize += space; // cache counts for "data"
2256 extStats->cacheSize += space;
2257 doubleSpaceToBeDeleted += space;
2258 }
2259 }
2260
2261 if (stats != nullptr) {
2262 if (!supportsProjectId) {
2263 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002264 stats->dataSize += space;
2265 }
Shikha Malhotra976ae002022-02-26 15:39:53 +00002266 deductDoubleSpaceIfNeeded(stats, doubleSpaceToBeDeleted, uid, uuid);
2267 int sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
2268 if (sdkSandboxUid != -1) {
2269 if ((space = GetOccupiedSpaceForUid(uuid, sdkSandboxUid)) != -1) {
2270 stats->dataSize += space;
2271 }
2272 }
2273 int cacheGid = multiuser_get_cache_gid(userId, appId);
2274 if (cacheGid != -1) {
2275 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
2276 stats->cacheSize += space;
2277 }
2278 }
2279 } else {
2280 long projectId = get_project_id(uid, PROJECT_ID_APP_START);
2281 if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
2282 stats->dataSize += space;
2283 }
2284 projectId = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
2285 if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
Risan5f308262018-10-26 12:06:58 -06002286 stats->cacheSize += space;
Shikha Malhotra976ae002022-02-26 15:39:53 +00002287 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002288 }
2289 }
2290
2291 int sharedGid = multiuser_get_shared_gid(0, appId);
2292 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06002293 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
2294 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002295 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002296 }
2297 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002298}
2299
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002300static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07002301 DIR *d;
2302 int dfd;
2303 struct dirent *de;
2304 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002305
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002306 d = opendir(path.c_str());
2307 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002308 if (errno != ENOENT) {
2309 PLOG(WARNING) << "Failed to open " << path;
2310 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002311 return;
2312 }
2313 dfd = dirfd(d);
2314 while ((de = readdir(d))) {
2315 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002316
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002317 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002318 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002319 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002320 }
2321
2322 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002323 if (!strcmp(name, ".")) {
2324 // Don't recurse, but still count node size
2325 } else if (!strcmp(name, "..")) {
2326 // Don't recurse or count node size
2327 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002328 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002329 // Measure all children nodes
2330 size = 0;
2331 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002332 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002333
2334 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
2335 stats->cacheSize += size;
2336 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002337 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002338
2339 // Legacy symlink isn't owned by app
2340 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
2341 continue;
2342 }
2343
2344 // Everything found inside is considered data
2345 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002346 }
2347 closedir(d);
2348}
2349
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002350void collectManualStatsForSubDirectories(const std::string& path, struct stats* stats) {
2351 const auto subDirHandler = [&path, &stats](const std::string& subDir) {
2352 auto fullpath = path + "/" + subDir;
2353 collectManualStats(fullpath, stats);
2354 };
2355 foreach_subdir(path, subDirHandler);
2356}
2357
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002358static void collectManualStatsForUser(const std::string& path, struct stats* stats,
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002359 bool exclude_apps = false,
2360 bool is_sdk_sandbox_storage = false) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002361 DIR *d;
2362 int dfd;
2363 struct dirent *de;
2364 struct stat s;
2365
2366 d = opendir(path.c_str());
2367 if (d == nullptr) {
2368 if (errno != ENOENT) {
2369 PLOG(WARNING) << "Failed to open " << path;
2370 }
2371 return;
2372 }
2373 dfd = dirfd(d);
2374 while ((de = readdir(d))) {
2375 if (de->d_type == DT_DIR) {
2376 const char *name = de->d_name;
2377 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
2378 continue;
2379 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002380 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002381 if (!strcmp(name, ".") || !strcmp(name, "..")) {
2382 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002383 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002384 continue;
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002385 } else if (is_sdk_sandbox_storage) {
2386 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2387 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2388 collectManualStatsForSubDirectories(StringPrintf("%s/%s", path.c_str(), name),
2389 stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002390 } else {
2391 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
2392 }
2393 }
2394 }
2395 closedir(d);
2396}
2397
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002398static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
2399 FTS *fts;
2400 FTSENT *p;
2401 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07002402 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002403 PLOG(ERROR) << "Failed to fts_open " << path;
2404 return;
2405 }
Yi Konge7bf3772018-07-17 16:16:24 -07002406 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002407 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002408 switch (p->fts_info) {
2409 case FTS_D:
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002410 if (p->fts_level == 3
2411 && !strcmp(p->fts_parent->fts_name, "obb")
2412 && !strcmp(p->fts_parent->fts_parent->fts_name, "Android")) {
2413 p->fts_number = 1;
2414 } else if (p->fts_level == 4
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002415 && !strcmp(p->fts_name, "cache")
2416 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
2417 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002418 p->fts_number = 2;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002419 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002420 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002421 case FTS_DEFAULT:
2422 case FTS_F:
2423 case FTS_SL:
2424 case FTS_SLNONE:
2425 int64_t size = (p->fts_statp->st_blocks * 512);
2426 if (p->fts_number == 1) {
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002427 stats->codeSize += size;
2428 } else {
2429 if (p->fts_number == 2) {
2430 stats->cacheSize += size;
2431 }
2432 stats->dataSize += size;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002433 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002434 break;
2435 }
2436 }
2437 fts_close(fts);
2438}
Shikha Malhotraaae96442021-11-25 10:52:50 +00002439static bool ownsExternalStorage(int32_t appId) {
Shikha Malhotra976ae002022-02-26 15:39:53 +00002440 // if project id calculation is supported then, there is no need to
2441 // calculate in a different way and project_id based calculation can work
2442 if (internal_storage_has_project_id()) {
2443 return false;
2444 }
2445
Shikha Malhotraaae96442021-11-25 10:52:50 +00002446 // Fetch external storage owner appid and check if it is the same as the
2447 // current appId whose size is calculated
2448 struct stat s;
2449 auto _picDir = StringPrintf("%s/Pictures", create_data_media_path(nullptr, 0).c_str());
2450 // check if the stat are present
2451 if (stat(_picDir.c_str(), &s) == 0) {
2452 // fetch the appId from the uid of the media app
2453 return ((int32_t)multiuser_get_app_id(s.st_uid) == appId);
2454 }
2455 return false;
2456}
Jooyung Han149be4a2020-01-23 12:45:10 +09002457binder::Status InstalldNativeService::getAppSize(const std::optional<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002458 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
2459 int32_t appId, const std::vector<int64_t>& ceDataInodes,
2460 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002461 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002462 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyya6823ef2022-02-28 14:18:19 -08002463 if (packageNames.size() != ceDataInodes.size()) {
2464 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
2465 "packageNames/ceDataInodes size mismatch.");
2466 }
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002467 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002468 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2469 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002470 for (const auto& codePath : codePaths) {
2471 CHECK_ARGUMENT_PATH(codePath);
2472 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002473 // NOTE: Locking is relaxed on this method, since it's limited to
2474 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07002475
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002476 // When modifying this logic, always verify using tests:
2477 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
2478
2479#if MEASURE_DEBUG
2480 LOG(INFO) << "Measuring user " << userId << " app " << appId;
2481#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002482
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002483 // Here's a summary of the common storage locations across the platform,
2484 // and how they're each tagged:
2485 //
2486 // /data/app/com.example UID system
2487 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002488 // /data/user/0/com.example UID u0_a10 GID u0_a10
2489 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
2490 // /data/media/0/foo.txt UID u0_media_rw
2491 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
2492 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
2493 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
2494 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002495
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002496 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002497 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002498 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002499 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002500
Jooyung Han149be4a2020-01-23 12:45:10 +09002501 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002502 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002503
Risan5f308262018-10-26 12:06:58 -06002504 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002505 flags &= ~FLAG_USE_QUOTA;
2506 }
2507
Zim23457d02022-08-17 12:57:41 +01002508 atrace_pm_begin("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002509 for (const auto& packageName : packageNames) {
Jeff Sharkey6d775c52019-03-22 13:46:20 -06002510 auto obbCodePath = create_data_media_package_path(uuid_, userId,
2511 "obb", packageName.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002512 calculate_tree_size(obbCodePath, &extStats.codeSize);
2513 }
Zim23457d02022-08-17 12:57:41 +01002514 atrace_pm_end();
Shikha Malhotraaae96442021-11-25 10:52:50 +00002515 // Calculating the app size of the external storage owning app in a manual way, since
2516 // calculating it through quota apis also includes external media storage in the app storage
2517 // numbers
2518 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START && !ownsExternalStorage(appId)) {
Zim23457d02022-08-17 12:57:41 +01002519 atrace_pm_begin("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002520 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002521 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002522 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002523 }
Zim23457d02022-08-17 12:57:41 +01002524 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002525
Zim23457d02022-08-17 12:57:41 +01002526 atrace_pm_begin("quota");
Risan5f308262018-10-26 12:06:58 -06002527 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Zim23457d02022-08-17 12:57:41 +01002528 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002529 } else {
Zim23457d02022-08-17 12:57:41 +01002530 atrace_pm_begin("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002531 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002532 calculate_tree_size(codePath, &stats.codeSize);
2533 }
Zim23457d02022-08-17 12:57:41 +01002534 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002535
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002536 for (size_t i = 0; i < packageNames.size(); i++) {
2537 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002538
Zim23457d02022-08-17 12:57:41 +01002539 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002540 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
2541 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002542 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
2543 collectManualStats(dePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002544 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002545
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002546 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2547 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2548 if (appId >= AID_APP_START && appId <= AID_APP_END) {
Zim23457d02022-08-17 12:57:41 +01002549 atrace_pm_begin("sdksandbox");
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002550 auto sdkSandboxCePath =
2551 create_data_misc_sdk_sandbox_package_path(uuid_, true, userId, pkgname);
2552 collectManualStatsForSubDirectories(sdkSandboxCePath, &stats);
2553 auto sdkSandboxDePath =
2554 create_data_misc_sdk_sandbox_package_path(uuid_, false, userId, pkgname);
2555 collectManualStatsForSubDirectories(sdkSandboxDePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002556 atrace_pm_end();
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002557 }
2558
Jeff Sharkey06a61842017-04-15 12:03:31 -06002559 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002560 atrace_pm_begin("profiles");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002561 calculate_tree_size(
2562 create_primary_current_profile_package_dir_path(userId, pkgname),
2563 &stats.dataSize);
2564 calculate_tree_size(
2565 create_primary_reference_profile_package_dir_path(pkgname),
2566 &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002567 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002568 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002569
Zim23457d02022-08-17 12:57:41 +01002570 atrace_pm_begin("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002571 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002572 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002573 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002574 calculate_tree_size(mediaPath, &extStats.dataSize);
Zim23457d02022-08-17 12:57:41 +01002575 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002576 }
2577
Jeff Sharkey06a61842017-04-15 12:03:31 -06002578 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002579 atrace_pm_begin("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002580 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06002581 if (sharedGid != -1) {
2582 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2583 sharedGid, -1);
2584 }
Zim23457d02022-08-17 12:57:41 +01002585 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002586 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002587 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002588
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002589 std::vector<int64_t> ret;
2590 ret.push_back(stats.codeSize);
2591 ret.push_back(stats.dataSize);
2592 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002593 ret.push_back(extStats.codeSize);
2594 ret.push_back(extStats.dataSize);
2595 ret.push_back(extStats.cacheSize);
2596#if MEASURE_DEBUG
2597 LOG(DEBUG) << "Final result " << toString(ret);
2598#endif
2599 *_aidl_return = ret;
2600 return ok();
2601}
2602
Martijn Coenen771cc342020-02-19 23:26:56 +01002603struct external_sizes {
2604 int64_t audioSize;
2605 int64_t videoSize;
2606 int64_t imageSize;
2607 int64_t totalSize; // excludes OBBs (Android/obb), but includes app data + cache
2608 int64_t obbSize;
2609};
2610
2611#define PER_USER_RANGE 100000
2612
2613static long getProjectIdForUser(int userId, long projectId) {
2614 return userId * PER_USER_RANGE + projectId;
2615}
2616
2617static external_sizes getExternalSizesForUserWithQuota(const std::string& uuid, int32_t userId, const std::vector<int32_t>& appIds) {
2618 struct external_sizes sizes = {};
2619 int64_t space;
2620
2621 if (supports_sdcardfs()) {
2622 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
2623 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
2624 sizes.totalSize = space;
2625 }
2626
2627 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
2628 if ((space = GetOccupiedSpaceForGid(uuid, audioGid)) != -1) {
2629 sizes.audioSize = space;
2630 }
2631
2632 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
2633 if ((space = GetOccupiedSpaceForGid(uuid, videoGid)) != -1) {
2634 sizes.videoSize = space;
2635 }
2636
2637 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
2638 if ((space = GetOccupiedSpaceForGid(uuid, imageGid)) != -1) {
2639 sizes.imageSize = space;
2640 }
2641
2642 if ((space = GetOccupiedSpaceForGid(uuid, AID_MEDIA_OBB)) != -1) {
2643 sizes.obbSize = space;
2644 }
2645 } else {
2646 int64_t totalSize = 0;
2647 long defaultProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_DEFAULT);
2648 if ((space = GetOccupiedSpaceForProjectId(uuid, defaultProjectId)) != -1) {
2649 // This is all files that are not audio/video/images, excluding
2650 // OBBs and app-private data
2651 totalSize += space;
2652 }
2653
2654 long audioProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_AUDIO);
2655 if ((space = GetOccupiedSpaceForProjectId(uuid, audioProjectId)) != -1) {
2656 sizes.audioSize = space;
2657 totalSize += space;
2658 }
2659
2660 long videoProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_VIDEO);
2661 if ((space = GetOccupiedSpaceForProjectId(uuid, videoProjectId)) != -1) {
2662 sizes.videoSize = space;
2663 totalSize += space;
2664 }
2665
2666 long imageProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_IMAGE);
2667 if ((space = GetOccupiedSpaceForProjectId(uuid, imageProjectId)) != -1) {
2668 sizes.imageSize = space;
2669 totalSize += space;
2670 }
2671
2672 int64_t totalAppDataSize = 0;
2673 int64_t totalAppCacheSize = 0;
2674 int64_t totalAppObbSize = 0;
2675 for (auto appId : appIds) {
2676 if (appId >= AID_APP_START) {
2677 // App data
2678 uid_t uid = multiuser_get_uid(userId, appId);
2679 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
2680 totalAppDataSize += GetOccupiedSpaceForProjectId(uuid, projectId);
2681
2682 // App cache
2683 long cacheProjectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
2684 totalAppCacheSize += GetOccupiedSpaceForProjectId(uuid, cacheProjectId);
2685
2686 // App OBBs
2687 long obbProjectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
2688 totalAppObbSize += GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2689 }
2690 }
2691 // Total size should include app data + cache
2692 totalSize += totalAppDataSize;
2693 totalSize += totalAppCacheSize;
2694 sizes.totalSize = totalSize;
2695
2696 // Only OBB is separate
2697 sizes.obbSize = totalAppObbSize;
2698 }
2699
2700 return sizes;
2701}
2702
Jooyung Han149be4a2020-01-23 12:45:10 +09002703binder::Status InstalldNativeService::getUserSize(const std::optional<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002704 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2705 std::vector<int64_t>* _aidl_return) {
2706 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002707 ENFORCE_VALID_USER(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002708 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002709 // NOTE: Locking is relaxed on this method, since it's limited to
2710 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002711
2712 // When modifying this logic, always verify using tests:
2713 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
2714
2715#if MEASURE_DEBUG
2716 LOG(INFO) << "Measuring user " << userId;
2717#endif
2718
2719 struct stats stats;
2720 struct stats extStats;
2721 memset(&stats, 0, sizeof(stats));
2722 memset(&extStats, 0, sizeof(extStats));
2723
Jooyung Han149be4a2020-01-23 12:45:10 +09002724 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002725 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2726
Risan5f308262018-10-26 12:06:58 -06002727 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002728 flags &= ~FLAG_USE_QUOTA;
2729 }
2730
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002731 if (flags & FLAG_USE_QUOTA) {
Zim23457d02022-08-17 12:57:41 +01002732 atrace_pm_begin("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002733 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002734 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002735
Zim23457d02022-08-17 12:57:41 +01002736 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002737 auto cePath = create_data_user_ce_path(uuid_, userId);
2738 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002739 auto dePath = create_data_user_de_path(uuid_, userId);
2740 collectManualStatsForUser(dePath, &stats, true);
Zim23457d02022-08-17 12:57:41 +01002741 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002742
Jeff Sharkey06a61842017-04-15 12:03:31 -06002743 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002744 atrace_pm_begin("profile");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002745 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2746 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
2747 auto refProfilePath = create_primary_ref_profile_dir_path();
2748 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002749 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002750 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002751
Zim23457d02022-08-17 12:57:41 +01002752 atrace_pm_begin("external");
Martijn Coenen771cc342020-02-19 23:26:56 +01002753 auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2754 extStats.dataSize += sizes.totalSize;
2755 extStats.codeSize += sizes.obbSize;
Zim23457d02022-08-17 12:57:41 +01002756 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002757
Jeff Sharkey06a61842017-04-15 12:03:31 -06002758 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002759 atrace_pm_begin("dalvik");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002760 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2761 -1, -1, true);
2762 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
2763 -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002764 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002765 }
Zim23457d02022-08-17 12:57:41 +01002766 atrace_pm_begin("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002767 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002768 for (auto appId : appIds) {
2769 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06002770 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002771#if MEASURE_DEBUG
2772 // Sleep to make sure we don't lose logs
2773 usleep(1);
2774#endif
2775 }
2776 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002777 extStats.dataSize = dataSize;
Zim23457d02022-08-17 12:57:41 +01002778 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002779 } else {
Zim23457d02022-08-17 12:57:41 +01002780 atrace_pm_begin("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002781 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002782 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002783
Zim23457d02022-08-17 12:57:41 +01002784 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002785 auto cePath = create_data_user_ce_path(uuid_, userId);
2786 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002787 auto dePath = create_data_user_de_path(uuid_, userId);
2788 collectManualStatsForUser(dePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002789 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002790
Zim23457d02022-08-17 12:57:41 +01002791 atrace_pm_begin("sdksandbox");
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002792 auto sdkSandboxCePath = create_data_misc_sdk_sandbox_path(uuid_, true, userId);
2793 collectManualStatsForUser(sdkSandboxCePath, &stats, false, true);
2794 auto sdkSandboxDePath = create_data_misc_sdk_sandbox_path(uuid_, false, userId);
2795 collectManualStatsForUser(sdkSandboxDePath, &stats, false, true);
Zim23457d02022-08-17 12:57:41 +01002796 atrace_pm_end();
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002797
Jeff Sharkey06a61842017-04-15 12:03:31 -06002798 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002799 atrace_pm_begin("profile");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002800 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2801 calculate_tree_size(userProfilePath, &stats.dataSize);
2802 auto refProfilePath = create_primary_ref_profile_dir_path();
2803 calculate_tree_size(refProfilePath, &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002804 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002805 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002806
Zim23457d02022-08-17 12:57:41 +01002807 atrace_pm_begin("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002808 auto dataMediaPath = create_data_media_path(uuid_, userId);
2809 collectManualExternalStatsForUser(dataMediaPath, &extStats);
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002810
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002811#if MEASURE_DEBUG
2812 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002813 << extStats.cacheSize << " code " << extStats.codeSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002814#endif
Zim23457d02022-08-17 12:57:41 +01002815 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002816
Jeff Sharkey06a61842017-04-15 12:03:31 -06002817 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002818 atrace_pm_begin("dalvik");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002819 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
2820 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
Zim23457d02022-08-17 12:57:41 +01002821 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002822 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002823 }
2824
2825 std::vector<int64_t> ret;
2826 ret.push_back(stats.codeSize);
2827 ret.push_back(stats.dataSize);
2828 ret.push_back(stats.cacheSize);
2829 ret.push_back(extStats.codeSize);
2830 ret.push_back(extStats.dataSize);
2831 ret.push_back(extStats.cacheSize);
2832#if MEASURE_DEBUG
2833 LOG(DEBUG) << "Final result " << toString(ret);
2834#endif
2835 *_aidl_return = ret;
2836 return ok();
2837}
2838
Jooyung Han149be4a2020-01-23 12:45:10 +09002839binder::Status InstalldNativeService::getExternalSize(const std::optional<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002840 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2841 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002842 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002843 ENFORCE_VALID_USER(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002844 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002845 // NOTE: Locking is relaxed on this method, since it's limited to
2846 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002847
2848 // When modifying this logic, always verify using tests:
2849 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
2850
2851#if MEASURE_DEBUG
2852 LOG(INFO) << "Measuring external " << userId;
2853#endif
2854
Jooyung Han149be4a2020-01-23 12:45:10 +09002855 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002856 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2857
2858 int64_t totalSize = 0;
2859 int64_t audioSize = 0;
2860 int64_t videoSize = 0;
2861 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002862 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06002863 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002864
Risan5f308262018-10-26 12:06:58 -06002865 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002866 flags &= ~FLAG_USE_QUOTA;
2867 }
2868
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002869 if (flags & FLAG_USE_QUOTA) {
Zim23457d02022-08-17 12:57:41 +01002870 atrace_pm_begin("quota");
Martijn Coenen771cc342020-02-19 23:26:56 +01002871 auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2872 totalSize = sizes.totalSize;
2873 audioSize = sizes.audioSize;
2874 videoSize = sizes.videoSize;
2875 imageSize = sizes.imageSize;
2876 obbSize = sizes.obbSize;
Zim23457d02022-08-17 12:57:41 +01002877 atrace_pm_end();
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002878
Zim23457d02022-08-17 12:57:41 +01002879 atrace_pm_begin("apps");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002880 struct stats extStats;
2881 memset(&extStats, 0, sizeof(extStats));
2882 for (auto appId : appIds) {
2883 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06002884 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002885 }
2886 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06002887 appSize = extStats.dataSize;
Zim23457d02022-08-17 12:57:41 +01002888 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002889 } else {
Zim23457d02022-08-17 12:57:41 +01002890 atrace_pm_begin("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002891 FTS *fts;
2892 FTSENT *p;
2893 auto path = create_data_media_path(uuid_, userId);
2894 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07002895 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002896 return error("Failed to fts_open " + path);
2897 }
Yi Konge7bf3772018-07-17 16:16:24 -07002898 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002899 char* ext;
2900 int64_t size = (p->fts_statp->st_blocks * 512);
2901 switch (p->fts_info) {
2902 case FTS_F:
2903 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06002904 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002905 ext = strrchr(p->fts_name, '.');
2906 if (ext != nullptr) {
2907 switch (MatchExtension(++ext)) {
2908 case AID_MEDIA_AUDIO: audioSize += size; break;
2909 case AID_MEDIA_VIDEO: videoSize += size; break;
2910 case AID_MEDIA_IMAGE: imageSize += size; break;
2911 }
2912 }
2913 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002914 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002915 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06002916 // Ignore data belonging to specific apps
2917 p->fts_number = p->fts_parent->fts_number;
2918 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
2919 p->fts_number = 1;
2920 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002921 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002922 case FTS_DEFAULT:
2923 case FTS_SL:
2924 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002925 if (p->fts_parent->fts_number == 1) {
2926 appSize += size;
2927 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002928 totalSize += size;
2929 break;
2930 }
2931 }
2932 fts_close(fts);
Zim23457d02022-08-17 12:57:41 +01002933 atrace_pm_end();
Jeff Sharkeya0136982017-07-06 11:29:37 -06002934
Zim23457d02022-08-17 12:57:41 +01002935 atrace_pm_begin("obb");
Jeff Sharkey6d775c52019-03-22 13:46:20 -06002936 auto obbPath = StringPrintf("%s/Android/obb",
2937 create_data_media_path(uuid_, userId).c_str());
Jeff Sharkeya0136982017-07-06 11:29:37 -06002938 calculate_tree_size(obbPath, &obbSize);
Chuwei Xu5d64ddf2019-12-04 15:32:18 +08002939 if (!(flags & FLAG_USE_QUOTA)) {
2940 totalSize -= obbSize;
2941 }
Zim23457d02022-08-17 12:57:41 +01002942 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002943 }
2944
2945 std::vector<int64_t> ret;
2946 ret.push_back(totalSize);
2947 ret.push_back(audioSize);
2948 ret.push_back(videoSize);
2949 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002950 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06002951 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002952#if MEASURE_DEBUG
2953 LOG(DEBUG) << "Final result " << toString(ret);
2954#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002955 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002956 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002957}
2958
Felka Chang2a0a2462019-11-20 14:20:40 +08002959binder::Status InstalldNativeService::getAppCrates(
Jooyung Han149be4a2020-01-23 12:45:10 +09002960 const std::optional<std::string>& uuid,
Felka Chang2a0a2462019-11-20 14:20:40 +08002961 const std::vector<std::string>& packageNames, int32_t userId,
Jooyung Han149be4a2020-01-23 12:45:10 +09002962 std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
Felka Chang2a0a2462019-11-20 14:20:40 +08002963 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002964 ENFORCE_VALID_USER(userId);
Felka Chang2a0a2462019-11-20 14:20:40 +08002965 CHECK_ARGUMENT_UUID(uuid);
2966 for (const auto& packageName : packageNames) {
2967 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2968 }
Felka Chang4df87f62020-02-11 19:08:43 +08002969#ifdef ENABLE_STORAGE_CRATES
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002970 LOCK_PACKAGE_USER();
Felka Chang2a0a2462019-11-20 14:20:40 +08002971
Jooyung Han149be4a2020-01-23 12:45:10 +09002972 auto retVector = std::vector<std::optional<CrateMetadata>>();
Felka Chang2a0a2462019-11-20 14:20:40 +08002973 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2974
Jooyung Han149be4a2020-01-23 12:45:10 +09002975 std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
2976 [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
Felka Chang2a0a2462019-11-20 14:20:40 +08002977 if (cratedFolder == nullptr) {
2978 return;
2979 }
Jooyung Han149be4a2020-01-23 12:45:10 +09002980 retVector.push_back(std::move(crateMetadata));
Felka Chang2a0a2462019-11-20 14:20:40 +08002981 };
2982
2983 for (const auto& packageName : packageNames) {
2984#if CRATE_DEBUG
2985 LOG(DEBUG) << "packageName = " << packageName;
2986#endif
2987 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageName);
2988 crateManager->traverseAllCrates(onCreateCrate);
2989 }
2990
2991#if CRATE_DEBUG
Jooyung Han149be4a2020-01-23 12:45:10 +09002992 LOG(WARNING) << "retVector.size() =" << retVector.size();
2993 for (auto& item : retVector) {
Jooyung Hand520e802020-03-03 02:56:34 +09002994 CrateManager::dump(*item);
Felka Chang2a0a2462019-11-20 14:20:40 +08002995 }
2996#endif
2997
2998 *_aidl_return = std::move(retVector);
Felka Chang4df87f62020-02-11 19:08:43 +08002999#else // ENABLE_STORAGE_CRATES
Jooyung Han149be4a2020-01-23 12:45:10 +09003000 _aidl_return->reset();
Felka Chang4df87f62020-02-11 19:08:43 +08003001
3002 /* prevent compile warning fail */
3003 if (userId < 0) {
3004 return error();
3005 }
3006#endif // ENABLE_STORAGE_CRATES
Felka Chang2a0a2462019-11-20 14:20:40 +08003007 return ok();
3008}
3009
3010binder::Status InstalldNativeService::getUserCrates(
Jooyung Han149be4a2020-01-23 12:45:10 +09003011 const std::optional<std::string>& uuid, int32_t userId,
3012 std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
Felka Chang2a0a2462019-11-20 14:20:40 +08003013 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003014 ENFORCE_VALID_USER(userId);
Felka Chang2a0a2462019-11-20 14:20:40 +08003015 CHECK_ARGUMENT_UUID(uuid);
Felka Chang4df87f62020-02-11 19:08:43 +08003016#ifdef ENABLE_STORAGE_CRATES
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003017 LOCK_USER();
Felka Chang2a0a2462019-11-20 14:20:40 +08003018
3019 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jooyung Han149be4a2020-01-23 12:45:10 +09003020 auto retVector = std::vector<std::optional<CrateMetadata>>();
Felka Chang2a0a2462019-11-20 14:20:40 +08003021
Jooyung Han149be4a2020-01-23 12:45:10 +09003022 std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3023 [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
Felka Chang2a0a2462019-11-20 14:20:40 +08003024 if (cratedFolder == nullptr) {
3025 return;
3026 }
Jooyung Hand520e802020-03-03 02:56:34 +09003027 retVector.push_back(std::move(crateMetadata));
Felka Chang2a0a2462019-11-20 14:20:40 +08003028 };
3029
3030 std::function<void(FTSENT*)> onHandingPackage = [&](FTSENT* packageDir) -> void {
3031 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageDir->fts_name);
3032 crateManager->traverseAllCrates(onCreateCrate);
3033 };
3034 CrateManager::traverseAllPackagesForUser(uuid, userId, onHandingPackage);
3035
3036#if CRATE_DEBUG
Jooyung Han149be4a2020-01-23 12:45:10 +09003037 LOG(DEBUG) << "retVector.size() =" << retVector.size();
3038 for (auto& item : retVector) {
Jooyung Hand520e802020-03-03 02:56:34 +09003039 CrateManager::dump(*item);
Felka Chang2a0a2462019-11-20 14:20:40 +08003040 }
3041#endif
3042
3043 *_aidl_return = std::move(retVector);
Felka Chang4df87f62020-02-11 19:08:43 +08003044#else // ENABLE_STORAGE_CRATES
Jooyung Han149be4a2020-01-23 12:45:10 +09003045 _aidl_return->reset();
Felka Chang4df87f62020-02-11 19:08:43 +08003046
3047 /* prevent compile warning fail */
3048 if (userId < 0) {
3049 return error();
3050 }
3051#endif // ENABLE_STORAGE_CRATES
Felka Chang2a0a2462019-11-20 14:20:40 +08003052 return ok();
3053}
3054
Jooyung Han149be4a2020-01-23 12:45:10 +09003055binder::Status InstalldNativeService::setAppQuota(const std::optional<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003056 int32_t userId, int32_t appId, int64_t cacheQuota) {
3057 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003058 ENFORCE_VALID_USER(userId);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003059 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003060 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003061
3062 int32_t uid = multiuser_get_uid(userId, appId);
3063 mCacheQuotas[uid] = cacheQuota;
3064
3065 return ok();
3066}
3067
David Sehr6727c2d2016-05-17 16:06:22 -07003068// Dumps the contents of a profile file, using pkgname's dex files for pretty
3069// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003070binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Martin Stjernholmfd000402022-04-11 18:04:59 +01003071 const std::string& profileName,
3072 const std::string& codePath,
3073 bool dumpClassesAndMethods, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003074 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003075 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003076 CHECK_ARGUMENT_PATH(codePath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003077 LOCK_PACKAGE();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003078
Martin Stjernholmfd000402022-04-11 18:04:59 +01003079 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath, dumpClassesAndMethods);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003080 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07003081}
3082
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003083// Copy the contents of a system profile over the data profile.
3084binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08003085 int32_t packageUid, const std::string& packageName, const std::string& profileName,
3086 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003087 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyyd04631f2022-08-12 15:14:41 -07003088 CHECK_ARGUMENT_PATH(systemProfile);
3089 if (!base::EndsWith(systemProfile, ".prof")) {
3090 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3091 StringPrintf("System profile path %s does not end with .prof",
3092 systemProfile.c_str()));
3093 }
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003094 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyyd04631f2022-08-12 15:14:41 -07003095 CHECK_ARGUMENT_FILE_NAME(profileName);
3096 if (!base::EndsWith(profileName, ".prof")) {
3097 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3098 StringPrintf("Profile name %s does not end with .prof",
3099 profileName.c_str()));
3100 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003101 LOCK_PACKAGE();
Calin Juravle562de812018-01-20 23:34:18 -08003102 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003103 return ok();
3104}
3105
Andreas Gampe4d0f8252016-03-20 11:30:28 -07003106// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003107binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle3b758282021-06-08 08:04:52 -07003108 const std::string& profileName, int* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003109 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003110 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003111 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07003112
Calin Juravle562de812018-01-20 23:34:18 -08003113 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003114 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07003115}
3116
Calin Juravlec41dac22017-12-05 12:29:15 -08003117binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08003118 const std::string& packageName, const std::string& profileName,
3119 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08003120 ENFORCE_UID(AID_SYSTEM);
3121 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003122 LOCK_PACKAGE();
Calin Juravle29591732017-11-20 17:46:19 -08003123
Calin Juravlee61189e2018-01-23 19:54:11 -08003124 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08003125 return ok();
3126}
3127
3128binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003129 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08003130 ENFORCE_UID(AID_SYSTEM);
3131 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003132 LOCK_PACKAGE();
Calin Juravle29591732017-11-20 17:46:19 -08003133
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003134 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08003135 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003136 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08003137 }
3138 return ok();
3139}
3140
Jooyung Han149be4a2020-01-23 12:45:10 +09003141static const char* getCStr(const std::optional<std::string>& data,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003142 const char* default_value = nullptr) {
Jooyung Han149be4a2020-01-23 12:45:10 +09003143 return data ? data->c_str() : default_value;
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003144}
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003145binder::Status InstalldNativeService::dexopt(
3146 const std::string& apkPath, int32_t uid, const std::string& packageName,
3147 const std::string& instructionSet, int32_t dexoptNeeded,
3148 const std::optional<std::string>& outputPath, int32_t dexFlags,
Jooyung Han149be4a2020-01-23 12:45:10 +09003149 const std::string& compilerFilter, const std::optional<std::string>& uuid,
3150 const std::optional<std::string>& classLoaderContext,
3151 const std::optional<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
3152 const std::optional<std::string>& profileName,
3153 const std::optional<std::string>& dexMetadataPath,
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003154 const std::optional<std::string>& compilationReason, bool* aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003155 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003156 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07003157 CHECK_ARGUMENT_PATH(apkPath);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003158 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003159 CHECK_ARGUMENT_PATH(outputPath);
3160 CHECK_ARGUMENT_PATH(dexMetadataPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003161 const auto userId = multiuser_get_user_id(uid);
3162 LOCK_PACKAGE_USER();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003163
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07003164 const char* oat_dir = getCStr(outputPath);
3165 const char* instruction_set = instructionSet.c_str();
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003166 if (oat_dir != nullptr && !createOatDir(packageName, oat_dir, instruction_set).isOk()) {
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07003167 // Can't create oat dir - let dexopt use cache dir.
3168 oat_dir = nullptr;
3169 }
3170
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003171 const char* apk_path = apkPath.c_str();
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003172 const char* pkgname = packageName.c_str();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003173 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003174 const char* volume_uuid = getCStr(uuid);
3175 const char* class_loader_context = getCStr(classLoaderContext);
3176 const char* se_info = getCStr(seInfo);
3177 const char* profile_name = getCStr(profileName);
3178 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08003179 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08003180 std::string error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07003181 bool completed = false; // not necessary but for compiler
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003182 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07003183 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Keun young Park65578d62021-06-28 17:52:05 -07003184 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg,
3185 &completed);
3186 *aidl_return = completed;
Andreas Gampe023b2242018-02-28 16:03:25 -08003187 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003188}
3189
Keun young Park65578d62021-06-28 17:52:05 -07003190binder::Status InstalldNativeService::controlDexOptBlocking(bool block) {
3191 android::installd::control_dexopt_blocking(block);
3192 return ok();
3193}
3194
Eric Holk0ebbe0f2019-01-09 18:17:27 -08003195binder::Status InstalldNativeService::compileLayouts(const std::string& apkPath,
3196 const std::string& packageName,
3197 const std ::string& outDexFile, int uid,
3198 bool* _aidl_return) {
3199 const char* apk_path = apkPath.c_str();
3200 const char* package_name = packageName.c_str();
3201 const char* out_dex_file = outDexFile.c_str();
3202 *_aidl_return = android::installd::view_compiler(apk_path, package_name, out_dex_file, uid);
3203 return *_aidl_return ? ok() : error("viewcompiler failed");
3204}
3205
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003206binder::Status InstalldNativeService::linkNativeLibraryDirectory(
Jooyung Han149be4a2020-01-23 12:45:10 +09003207 const std::optional<std::string>& uuid, const std::string& packageName,
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003208 const std::string& nativeLibPath32, int32_t userId) {
3209 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003210 CHECK_ARGUMENT_UUID(uuid);
3211 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003212 CHECK_ARGUMENT_PATH(nativeLibPath32);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003213 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07003214
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003215 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3216 const char* pkgname = packageName.c_str();
3217 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003218 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07003219 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003220
Jeff Sharkey423e7462016-12-09 18:18:43 -07003221 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
3222 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07003223
3224 const char* pkgdir = _pkgdir.c_str();
3225 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003226
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003227 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003228 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003229 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003230
Nick Kralevich85958b62019-01-30 12:32:21 -08003231 char *con = nullptr;
3232 if (lgetfilecon(pkgdir, &con) < 0) {
3233 return error("Failed to lgetfilecon " + _pkgdir);
3234 }
3235
Mike Lockwood94afecf2012-10-24 10:45:23 -07003236 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08003237 res = error("Failed to chown " + _pkgdir);
3238 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07003239 }
3240
3241 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003242 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003243 goto out;
3244 }
3245
3246 if (lstat(libsymlink, &libStat) < 0) {
3247 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003248 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003249 goto out;
3250 }
3251 } else {
3252 if (S_ISDIR(libStat.st_mode)) {
Yi Konge7bf3772018-07-17 16:16:24 -07003253 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003254 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003255 goto out;
3256 }
3257 } else if (S_ISLNK(libStat.st_mode)) {
3258 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003259 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003260 goto out;
3261 }
3262 }
3263 }
3264
3265 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003266 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003267 goto out;
3268 }
3269
Nick Kralevich85958b62019-01-30 12:32:21 -08003270 if (lsetfilecon(libsymlink, con) < 0) {
3271 res = error("Failed to lsetfilecon " + _libsymlink);
3272 goto out;
3273 }
3274
Mike Lockwood94afecf2012-10-24 10:45:23 -07003275out:
Nick Kralevich85958b62019-01-30 12:32:21 -08003276 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003277 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003278 auto msg = "Failed to cleanup chmod " + _pkgdir;
3279 if (res.isOk()) {
3280 res = error(msg);
3281 } else {
3282 PLOG(ERROR) << msg;
3283 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003284 }
3285
3286 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003287 auto msg = "Failed to cleanup chown " + _pkgdir;
3288 if (res.isOk()) {
3289 res = error(msg);
3290 } else {
3291 PLOG(ERROR) << msg;
3292 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003293 }
3294
Jeff Sharkey423e7462016-12-09 18:18:43 -07003295 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07003296}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01003297
Jooyung Han149be4a2020-01-23 12:45:10 +09003298binder::Status InstalldNativeService::restoreconAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003299 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
3300 const std::string& seInfo) {
3301 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003302 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003303 CHECK_ARGUMENT_UUID(uuid);
3304 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003305 LOCK_PACKAGE_USER();
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08003306 return restoreconAppDataLocked(uuid, packageName, userId, flags, appId, seInfo);
3307}
3308
3309binder::Status InstalldNativeService::restoreconAppDataLocked(
3310 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3311 int32_t flags, int32_t appId, const std::string& seInfo) {
3312 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003313 ENFORCE_VALID_USER(userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08003314 CHECK_ARGUMENT_UUID(uuid);
3315 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003316
3317 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05003318
Robert Craigda30dc72014-03-27 10:21:12 -04003319 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003320 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003321 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3322 const char* pkgName = packageName.c_str();
3323 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04003324
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003325 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07003326 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003327 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003328 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003329 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07003330 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003331 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07003332 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003333 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003334 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003335 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07003336 }
Robert Craige9887e42014-02-20 10:25:56 -05003337 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07003338 return res;
Robert Craige9887e42014-02-20 10:25:56 -05003339}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01003340
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00003341binder::Status InstalldNativeService::restoreconSdkDataLocked(
3342 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3343 int32_t flags, int32_t appId, const std::string& seInfo) {
3344 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003345 ENFORCE_VALID_USER(userId);
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00003346 CHECK_ARGUMENT_UUID(uuid);
3347 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3348
3349 binder::Status res = ok();
3350
3351 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
3352 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
3353 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3354 const char* pkgName = packageName.c_str();
3355 const char* seinfo = seInfo.c_str();
3356
3357 uid_t uid = multiuser_get_sdk_sandbox_uid(userId, appId);
3358 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
3359 for (int currentFlag : storageFlags) {
3360 if ((flags & currentFlag) == 0) {
3361 continue;
3362 }
3363 const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
3364 const auto packagePath =
3365 create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgName);
3366 if (access(packagePath.c_str(), F_OK) != 0) {
3367 LOG(INFO) << "Missing source " << packagePath;
3368 continue;
3369 }
3370 const auto subDirHandler = [&packagePath, &seinfo, &uid, &seflags,
3371 &res](const std::string& subDir) {
3372 const auto& fullpath = packagePath + "/" + subDir;
3373 if (selinux_android_restorecon_pkgdir(fullpath.c_str(), seinfo, uid, seflags) < 0) {
3374 res = error("restorecon failed for " + fullpath);
3375 }
3376 };
3377 const auto ec = foreach_subdir(packagePath, subDirHandler);
3378 if (ec != 0) {
3379 res = error("Failed to restorecon for subdirs of " + packagePath);
3380 }
3381 }
3382 return res;
3383}
3384
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003385binder::Status InstalldNativeService::createOatDir(const std::string& packageName,
3386 const std::string& oatDir,
3387 const std::string& instructionSet) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003388 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003389 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003390 CHECK_ARGUMENT_PATH(oatDir);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003391 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003392
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003393 const char* oat_dir = oatDir.c_str();
3394 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003395 char oat_instr_dir[PKG_PATH_MAX];
3396
3397 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003398 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003399 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07003400 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003401 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003402 }
3403 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003404 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003405 }
3406 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07003407 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003408 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003409 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07003410 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003411}
3412
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003413binder::Status InstalldNativeService::rmPackageDir(const std::string& packageName,
3414 const std::string& packageDir) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003415 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07003416 CHECK_ARGUMENT_PATH(packageDir);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003417 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003418
Jeff Sharkey423e7462016-12-09 18:18:43 -07003419 if (validate_apk_path(packageDir.c_str())) {
3420 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003421 }
Oleksandr Peletskyid2be6322019-01-24 17:59:45 +01003422 if (rm_package_dir(packageDir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003423 return error("Failed to delete " + packageDir);
3424 }
3425 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003426}
3427
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003428binder::Status InstalldNativeService::linkFile(const std::string& packageName,
3429 const std::string& relativePath,
3430 const std::string& fromBase,
3431 const std::string& toBase) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003432 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003433 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003434 CHECK_ARGUMENT_PATH(fromBase);
3435 CHECK_ARGUMENT_PATH(toBase);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003436 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003437
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003438 const char* relative_path = relativePath.c_str();
3439 const char* from_base = fromBase.c_str();
3440 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01003441 char from_path[PKG_PATH_MAX];
3442 char to_path[PKG_PATH_MAX];
3443 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
3444 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
3445
3446 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003447 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003448 }
3449
3450 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003451 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003452 }
3453
Jeff Sharkey423e7462016-12-09 18:18:43 -07003454 if (link(from_path, to_path) < 0) {
3455 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003456 }
3457
Jeff Sharkey423e7462016-12-09 18:18:43 -07003458 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01003459}
3460
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003461binder::Status InstalldNativeService::moveAb(const std::string& packageName,
3462 const std::string& apkPath,
3463 const std::string& instructionSet,
3464 const std::string& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003465 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003466 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003467 CHECK_ARGUMENT_PATH(apkPath);
3468 CHECK_ARGUMENT_PATH(outputPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003469 LOCK_PACKAGE();
Jeff Sharkey90aff262016-12-12 14:28:24 -07003470
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003471 const char* apk_path = apkPath.c_str();
3472 const char* instruction_set = instructionSet.c_str();
3473 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07003474
Jeff Sharkey90aff262016-12-12 14:28:24 -07003475 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003476 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08003477}
3478
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003479binder::Status InstalldNativeService::deleteOdex(const std::string& packageName,
3480 const std::string& apkPath,
3481 const std::string& instructionSet,
3482 const std::optional<std::string>& outputPath,
3483 int64_t* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003484 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003485 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003486 CHECK_ARGUMENT_PATH(apkPath);
3487 CHECK_ARGUMENT_PATH(outputPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003488 LOCK_PACKAGE();
Jeff Sharkey90aff262016-12-12 14:28:24 -07003489
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003490 const char* apk_path = apkPath.c_str();
3491 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07003492 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003493
Calin Juravleea214ad2021-06-11 09:17:20 -07003494 *_aidl_return = delete_odex(apk_path, instruction_set, oat_dir);
3495 return *_aidl_return == -1 ? error() : ok();
Andreas Gampe3964da02016-09-09 17:07:04 -07003496}
3497
Calin Juravlebd968362017-01-25 01:17:17 -08003498binder::Status InstalldNativeService::reconcileSecondaryDexFile(
3499 const std::string& dexPath, const std::string& packageName, int32_t uid,
Jooyung Han149be4a2020-01-23 12:45:10 +09003500 const std::vector<std::string>& isas, const std::optional<std::string>& volumeUuid,
Calin Juravlebd968362017-01-25 01:17:17 -08003501 int32_t storage_flag, bool* _aidl_return) {
3502 ENFORCE_UID(AID_SYSTEM);
3503 CHECK_ARGUMENT_UUID(volumeUuid);
3504 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003505 CHECK_ARGUMENT_PATH(dexPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003506 const auto userId = multiuser_get_user_id(uid);
3507 LOCK_PACKAGE_USER();
Jeff Sharkey53594302018-02-24 18:59:39 -07003508
Calin Juravlebd968362017-01-25 01:17:17 -08003509 bool result = android::installd::reconcile_secondary_dex_file(
3510 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
3511 return result ? ok() : error();
3512}
3513
Alan Stokes753dc712017-10-16 10:56:00 +01003514binder::Status InstalldNativeService::hashSecondaryDexFile(
3515 const std::string& dexPath, const std::string& packageName, int32_t uid,
Jooyung Han149be4a2020-01-23 12:45:10 +09003516 const std::optional<std::string>& volumeUuid, int32_t storageFlag,
Alan Stokes753dc712017-10-16 10:56:00 +01003517 std::vector<uint8_t>* _aidl_return) {
3518 ENFORCE_UID(AID_SYSTEM);
3519 CHECK_ARGUMENT_UUID(volumeUuid);
3520 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003521 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01003522
3523 // mLock is not taken here since we will never modify the file system.
3524 // If a file is modified just as we are reading it this may result in an
3525 // anomalous hash, but that's ok.
3526 bool result = android::installd::hash_secondary_dex_file(
3527 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
3528 return result ? ok() : error();
3529}
Shikha Malhotra976ae002022-02-26 15:39:53 +00003530/**
3531 * Returns true if ioctl feature (F2FS_IOC_FS{GET,SET}XATTR) is supported as
3532 * these were introduced in Linux 4.14, so kernel versions before that will fail
3533 * while setting project id attributes. Only when these features are enabled,
3534 * storage calculation using project_id is enabled
3535 */
3536bool check_if_ioctl_feature_is_supported() {
3537 bool result = false;
3538 auto temp_path = StringPrintf("%smisc/installd/ioctl_check", android_data_dir.c_str());
3539 if (access(temp_path.c_str(), F_OK) != 0) {
3540 int fd = open(temp_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644);
Shikha Malhotrac18afa82022-04-01 22:13:39 +00003541 result = set_quota_project_id(temp_path, 0, false) == 0;
Shikha Malhotra976ae002022-02-26 15:39:53 +00003542 close(fd);
3543 // delete the temp file
3544 remove(temp_path.c_str());
3545 }
3546 return result;
3547}
3548
3549binder::Status InstalldNativeService::setFirstBoot() {
3550 ENFORCE_UID(AID_SYSTEM);
3551 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3552 std::string uuid;
3553 if (GetOccupiedSpaceForProjectId(uuid, 0) != -1 && check_if_ioctl_feature_is_supported()) {
3554 auto first_boot_path =
3555 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
3556 if (access(first_boot_path.c_str(), F_OK) != 0) {
3557 close(open(first_boot_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644));
3558 }
3559 }
3560 return ok();
3561}
Alan Stokes753dc712017-10-16 10:56:00 +01003562
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003563binder::Status InstalldNativeService::invalidateMounts() {
3564 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003565 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003566
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003567 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06003568
3569#if !BYPASS_QUOTA
3570 if (!InvalidateQuotaMounts()) {
3571 return error("Failed to read mounts");
3572 }
3573#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003574
3575 std::ifstream in("/proc/mounts");
3576 if (!in.is_open()) {
3577 return error("Failed to read mounts");
3578 }
3579
3580 std::string source;
3581 std::string target;
3582 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003583 while (!in.eof()) {
3584 std::getline(in, source, ' ');
3585 std::getline(in, target, ' ');
3586 std::getline(in, ignored);
3587
Zim0ce832d2019-12-03 17:03:58 +00003588 if (android::base::GetBoolProperty(kFuseProp, false)) {
Zim1edb92a2020-01-09 08:48:00 +00003589 if (target.find(kMntFuse) == 0) {
Zim0ce832d2019-12-03 17:03:58 +00003590 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3591 mStorageMounts[source] = target;
3592 }
3593 } else {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003594#if !BYPASS_SDCARDFS
Zim1edb92a2020-01-09 08:48:00 +00003595 if (target.find(kMntSdcardfs) == 0) {
Zim0ce832d2019-12-03 17:03:58 +00003596 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3597 mStorageMounts[source] = target;
3598 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003599#endif
Zim0ce832d2019-12-03 17:03:58 +00003600 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003601 }
3602 return ok();
3603}
3604
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003605// Mount volume's CE and DE storage to mirror
Ricky Wai2a4983f2020-02-07 14:25:45 +00003606binder::Status InstalldNativeService::tryMountDataMirror(
Jooyung Han149be4a2020-01-23 12:45:10 +09003607 const std::optional<std::string>& uuid) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003608 ENFORCE_UID(AID_SYSTEM);
3609 CHECK_ARGUMENT_UUID(uuid);
3610 if (!sAppDataIsolationEnabled) {
3611 return ok();
3612 }
3613 if (!uuid) {
3614 return error("Should not happen, mounting uuid == null");
3615 }
3616
3617 const char* uuid_ = uuid->c_str();
Ricky Wai2a4983f2020-02-07 14:25:45 +00003618
Alex Buynytskyy40c45ba2021-11-18 15:16:27 -08003619 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3620
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003621 std::string mirrorVolCePath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003622 if (fs_prepare_dir(mirrorVolCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003623 return error("Failed to create CE data mirror");
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003624 }
Ricky Wai2a4983f2020-02-07 14:25:45 +00003625
3626 std::string mirrorVolDePath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003627 if (fs_prepare_dir(mirrorVolDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003628 return error("Failed to create DE data mirror");
3629 }
3630
3631 std::string mirrorVolMiscCePath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003632 if (fs_prepare_dir(mirrorVolMiscCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003633 return error("Failed to create CE misc mirror");
3634 }
3635
3636 std::string mirrorVolMiscDePath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003637 if (fs_prepare_dir(mirrorVolMiscDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003638 return error("Failed to create DE misc mirror");
Ricky Wai2a4983f2020-02-07 14:25:45 +00003639 }
3640
3641 auto cePath = StringPrintf("%s/user", create_data_path(uuid_).c_str());
3642 auto dePath = StringPrintf("%s/user_de", create_data_path(uuid_).c_str());
Sanjana Sunil691163d2022-03-28 19:15:54 +00003643 auto miscCePath = StringPrintf("%s/misc_ce", create_data_path(uuid_).c_str());
3644 auto miscDePath = StringPrintf("%s/misc_de", create_data_path(uuid_).c_str());
Ricky Wai2a4983f2020-02-07 14:25:45 +00003645
3646 if (access(cePath.c_str(), F_OK) != 0) {
3647 return error("Cannot access CE path: " + cePath);
3648 }
3649 if (access(dePath.c_str(), F_OK) != 0) {
3650 return error("Cannot access DE path: " + dePath);
3651 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003652 if (access(miscCePath.c_str(), F_OK) != 0) {
3653 return error("Cannot access misc CE path: " + cePath);
3654 }
3655 if (access(miscDePath.c_str(), F_OK) != 0) {
3656 return error("Cannot access misc DE path: " + dePath);
3657 }
Ricky Wai2a4983f2020-02-07 14:25:45 +00003658
3659 struct stat ceStat, mirrorCeStat;
3660 if (stat(cePath.c_str(), &ceStat) != 0) {
3661 return error("Failed to stat " + cePath);
3662 }
3663 if (stat(mirrorVolCePath.c_str(), &mirrorCeStat) != 0) {
3664 return error("Failed to stat " + mirrorVolCePath);
3665 }
3666
Eric Biggersab9ea462022-05-26 00:28:09 +00003667 if (mirrorCeStat.st_ino == ceStat.st_ino && mirrorCeStat.st_dev == ceStat.st_dev) {
Ricky Wai2a4983f2020-02-07 14:25:45 +00003668 // As it's being called by prepareUserStorage, it can be called multiple times.
3669 // Hence, we if we mount it already, we should skip it.
Eric Biggersab9ea462022-05-26 00:28:09 +00003670 LOG(INFO) << "CE dir is mounted already: " + cePath;
Ricky Wai2a4983f2020-02-07 14:25:45 +00003671 return ok();
3672 }
3673
3674 // Mount CE mirror
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003675 if (TEMP_FAILURE_RETRY(mount(cePath.c_str(), mirrorVolCePath.c_str(), NULL,
3676 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3677 return error("Failed to mount " + mirrorVolCePath);
3678 }
3679
3680 // Mount DE mirror
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003681 if (TEMP_FAILURE_RETRY(mount(dePath.c_str(), mirrorVolDePath.c_str(), NULL,
3682 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3683 return error("Failed to mount " + mirrorVolDePath);
3684 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003685
3686 // Mount misc CE mirror
3687 if (TEMP_FAILURE_RETRY(mount(miscCePath.c_str(), mirrorVolMiscCePath.c_str(), NULL,
3688 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3689 nullptr)) == -1) {
3690 return error("Failed to mount " + mirrorVolMiscCePath);
3691 }
3692
3693 // Mount misc DE mirror
3694 if (TEMP_FAILURE_RETRY(mount(miscDePath.c_str(), mirrorVolMiscDePath.c_str(), NULL,
3695 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3696 nullptr)) == -1) {
3697 return error("Failed to mount " + mirrorVolMiscDePath);
3698 }
3699
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003700 return ok();
3701}
3702
3703// Unmount volume's CE and DE storage from mirror
3704binder::Status InstalldNativeService::onPrivateVolumeRemoved(
Jooyung Han149be4a2020-01-23 12:45:10 +09003705 const std::optional<std::string>& uuid) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003706 ENFORCE_UID(AID_SYSTEM);
3707 CHECK_ARGUMENT_UUID(uuid);
3708 if (!sAppDataIsolationEnabled) {
3709 return ok();
3710 }
3711 if (!uuid) {
3712 // It happens when private volume failed to mount.
3713 LOG(INFO) << "Ignore unmount uuid=null";
3714 return ok();
3715 }
3716 const char* uuid_ = uuid->c_str();
3717
3718 binder::Status res = ok();
3719
3720 std::string mirrorCeVolPath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
3721 std::string mirrorDeVolPath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
Sanjana Sunil691163d2022-03-28 19:15:54 +00003722 std::string mirrorMiscCeVolPath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
3723 std::string mirrorMiscDeVolPath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003724
Alex Buynytskyy40c45ba2021-11-18 15:16:27 -08003725 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3726
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003727 // Unmount CE storage
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003728 if (TEMP_FAILURE_RETRY(umount(mirrorCeVolPath.c_str())) != 0) {
3729 if (errno != ENOENT) {
3730 res = error(StringPrintf("Failed to umount %s %s", mirrorCeVolPath.c_str(),
3731 strerror(errno)));
3732 }
3733 }
3734 if (delete_dir_contents_and_dir(mirrorCeVolPath, true) != 0) {
3735 res = error("Failed to delete " + mirrorCeVolPath);
3736 }
3737
3738 // Unmount DE storage
3739 if (TEMP_FAILURE_RETRY(umount(mirrorDeVolPath.c_str())) != 0) {
3740 if (errno != ENOENT) {
3741 res = error(StringPrintf("Failed to umount %s %s", mirrorDeVolPath.c_str(),
3742 strerror(errno)));
3743 }
3744 }
3745 if (delete_dir_contents_and_dir(mirrorDeVolPath, true) != 0) {
3746 res = error("Failed to delete " + mirrorDeVolPath);
3747 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003748
3749 // Unmount misc CE storage
3750 if (TEMP_FAILURE_RETRY(umount(mirrorMiscCeVolPath.c_str())) != 0) {
3751 if (errno != ENOENT) {
3752 res = error(StringPrintf("Failed to umount %s %s", mirrorMiscCeVolPath.c_str(),
3753 strerror(errno)));
3754 }
3755 }
3756 if (delete_dir_contents_and_dir(mirrorMiscCeVolPath, true) != 0) {
3757 res = error("Failed to delete " + mirrorMiscCeVolPath);
3758 }
3759
3760 // Unmount misc DE storage
3761 if (TEMP_FAILURE_RETRY(umount(mirrorMiscDeVolPath.c_str())) != 0) {
3762 if (errno != ENOENT) {
3763 res = error(StringPrintf("Failed to umount %s %s", mirrorMiscDeVolPath.c_str(),
3764 strerror(errno)));
3765 }
3766 }
3767 if (delete_dir_contents_and_dir(mirrorMiscDeVolPath, true) != 0) {
3768 res = error("Failed to delete " + mirrorMiscDeVolPath);
3769 }
3770
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003771 return res;
3772}
3773
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003774std::string InstalldNativeService::findDataMediaPath(
Jooyung Han149be4a2020-01-23 12:45:10 +09003775 const std::optional<std::string>& uuid, userid_t userid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003776 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3777 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3778 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
3779 auto resolved = mStorageMounts[path];
3780 if (resolved.empty()) {
3781 LOG(WARNING) << "Failed to find storage mount for " << path;
3782 resolved = path;
3783 }
3784 return StringPrintf("%s/%u", resolved.c_str(), userid);
3785}
3786
Jeff Sharkey325b8c92017-02-21 10:00:53 -07003787binder::Status InstalldNativeService::isQuotaSupported(
Jooyung Han149be4a2020-01-23 12:45:10 +09003788 const std::optional<std::string>& uuid, bool* _aidl_return) {
3789 *_aidl_return = IsQuotaSupported(uuid.value_or(""));
Jeff Sharkey325b8c92017-02-21 10:00:53 -07003790 return ok();
3791}
3792
Calin Juravlebc5ab872018-01-18 22:32:58 -08003793binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
3794 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
Jooyung Han149be4a2020-01-23 12:45:10 +09003795 const std::optional<std::string>& dexMetadata, bool* _aidl_return) {
Calin Juravlebc5ab872018-01-18 22:32:58 -08003796 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003797 ENFORCE_VALID_USER(userId);
Calin Juravlebc5ab872018-01-18 22:32:58 -08003798 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003799 CHECK_ARGUMENT_PATH(codePath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003800 LOCK_PACKAGE_USER();
Calin Juravlebc5ab872018-01-18 22:32:58 -08003801
3802 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
3803 dexMetadata);
3804 return ok();
3805}
3806
Narayan Kamath28ab93b2019-05-15 18:29:44 +01003807binder::Status InstalldNativeService::migrateLegacyObbData() {
3808 ENFORCE_UID(AID_SYSTEM);
3809 // NOTE: The lint warning doesn't apply to the use of system(3) with
3810 // absolute parse and no command line arguments.
Cole Faustf6cd58a2022-09-01 17:34:36 -07003811 if (system("/system/bin/migrate_legacy_obb_data") != 0) { // NOLINT(cert-env33-c)
Narayan Kamath28ab93b2019-05-15 18:29:44 +01003812 LOG(ERROR) << "Unable to migrate legacy obb data";
3813 }
3814
3815 return ok();
3816}
3817
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003818binder::Status InstalldNativeService::cleanupInvalidPackageDirs(
3819 const std::optional<std::string>& uuid, int32_t userId, int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00003820 ENFORCE_VALID_USER(userId);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003821 const char* uuid_cstr = uuid ? uuid->c_str() : nullptr;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003822
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003823 if (flags & FLAG_STORAGE_CE) {
3824 auto ce_path = create_data_user_ce_path(uuid_cstr, userId);
3825 cleanup_invalid_package_dirs_under_path(ce_path);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00003826 auto sdksandbox_ce_path =
3827 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/true, userId);
3828 cleanup_invalid_package_dirs_under_path(sdksandbox_ce_path);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003829 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003830
3831 if (flags & FLAG_STORAGE_DE) {
3832 auto de_path = create_data_user_de_path(uuid_cstr, userId);
3833 cleanup_invalid_package_dirs_under_path(de_path);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00003834 auto sdksandbox_de_path =
3835 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/false, userId);
3836 cleanup_invalid_package_dirs_under_path(sdksandbox_de_path);
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003837 }
3838
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003839 return ok();
3840}
3841
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00003842binder::Status InstalldNativeService::getOdexVisibility(
3843 const std::string& packageName, const std::string& apkPath,
3844 const std::string& instructionSet, const std::optional<std::string>& outputPath,
3845 int32_t* _aidl_return) {
3846 ENFORCE_UID(AID_SYSTEM);
3847 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3848 CHECK_ARGUMENT_PATH(apkPath);
3849 CHECK_ARGUMENT_PATH(outputPath);
3850 LOCK_PACKAGE();
3851
3852 const char* apk_path = apkPath.c_str();
3853 const char* instruction_set = instructionSet.c_str();
3854 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
3855
3856 *_aidl_return = get_odex_visibility(apk_path, instruction_set, oat_dir);
3857 return *_aidl_return == -1 ? error() : ok();
3858}
3859
Andreas Gampe02d0de52015-11-11 20:43:16 -08003860} // namespace installd
3861} // namespace android