blob: 1347450a7765dfbe80b1ede914682080b86e2d5d [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>
Victor Hsiehc7ab5642023-07-28 15:07:55 -070022#include <linux/fsverity.h>
Keun young Park144a9892021-10-13 16:43:58 -070023#include <stdio.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080024#include <stdlib.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070025#include <string.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080026#include <sys/capability.h>
27#include <sys/file.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080028#include <sys/ioctl.h>
29#include <sys/mman.h>
Ricky Waiff9d3ea2019-11-18 18:18:24 +000030#include <sys/mount.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080031#include <sys/resource.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080032#include <sys/stat.h>
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -070033#include <sys/statvfs.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070034#include <sys/types.h>
Calin Juravle6a1648e2016-02-01 12:12:16 +000035#include <sys/wait.h>
Jeff Sharkeycc6281c2016-02-06 19:46:09 -070036#include <sys/xattr.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080037#include <unistd.h>
Samiul Islamc40dff52022-01-14 16:24:48 +000038#include <algorithm>
39#include <filesystem>
40#include <fstream>
41#include <functional>
42#include <regex>
Samiul Islam92f5cf02022-02-03 12:45:51 +000043#include <unordered_set>
Jeff Sharkey41ea4242015-04-09 11:34:03 -070044
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000045#include <android-base/file.h>
Andreas Gampeafa58d12016-06-03 16:09:32 -070046#include <android-base/logging.h>
Oli Lanc7789572020-03-16 18:18:41 +000047#include <android-base/parseint.h>
Jeff Sharkeyf29a3bc2018-01-08 10:40:19 -070048#include <android-base/properties.h>
Narayan Kamathe63ca7d2019-01-14 15:21:52 +000049#include <android-base/scopeguard.h>
Elliott Hughese4ec9eb2015-12-04 15:39:32 -080050#include <android-base/stringprintf.h>
David Sehr6727c2d2016-05-17 16:06:22 -070051#include <android-base/strings.h>
Roland Levillain64b59cc2016-04-05 16:41:12 +010052#include <android-base/unique_fd.h>
Victor Hsieh3f16dd62018-01-13 13:43:11 -080053#include <cutils/ashmem.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080054#include <cutils/fs.h>
Victor Hsiehc7ab5642023-07-28 15:07:55 -070055#include <cutils/misc.h>
Jeff Sharkey90aff262016-12-12 14:28:24 -070056#include <cutils/properties.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070057#include <cutils/sched_policy.h>
Shikha Malhotra976ae002022-02-26 15:39:53 +000058#include <linux/quota.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070059#include <log/log.h> // TODO: Move everything to base/logging.
Jeff Sharkeye3637242015-04-08 20:56:42 -070060#include <logwrap/logwrap.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080061#include <private/android_filesystem_config.h>
Martijn Coenen771cc342020-02-19 23:26:56 +010062#include <private/android_projectid_config.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070063#include <selinux/android.h>
Andreas Gampe02d0de52015-11-11 20:43:16 -080064#include <system/thread_defs.h>
Jeff Sharkey466459b2017-01-17 15:25:01 -070065#include <utils/Trace.h>
Jeff Sharkeye3637242015-04-08 20:56:42 -070066
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070067#include "dexopt.h"
Jeff Sharkeyf3e30b92016-12-09 17:06:57 -070068#include "globals.h"
69#include "installd_deps.h"
70#include "otapreopt_utils.h"
71#include "utils.h"
Eric Holk0ebbe0f2019-01-09 18:17:27 -080072#include "view_compiler.h"
Jeff Sharkey6c2c0562016-12-07 12:12:00 -070073
Jeff Sharkey88ddd942017-01-17 18:05:54 -070074#include "CacheTracker.h"
Felka Chang2a0a2462019-11-20 14:20:40 +080075#include "CrateManager.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070076#include "MatchExtensionGen.h"
Risan5f308262018-10-26 12:06:58 -060077#include "QuotaUtils.h"
Zim23457d02022-08-17 12:57:41 +010078#include "SysTrace.h"
Jeff Sharkeydf2d7542017-01-07 09:19:35 -070079
Andreas Gampe02d0de52015-11-11 20:43:16 -080080#ifndef LOG_TAG
81#define LOG_TAG "installd"
82#endif
Jeff Sharkey41ea4242015-04-09 11:34:03 -070083
Alex Buynytskyy779447d2021-11-22 17:06:53 -080084#define GRANULAR_LOCKS
Alex Buynytskyy4fef8862021-11-21 16:09:33 -080085
Oli Lanc7789572020-03-16 18:18:41 +000086using android::base::ParseUint;
Samiul Islam92f5cf02022-02-03 12:45:51 +000087using android::base::Split;
Jeff Sharkey41ea4242015-04-09 11:34:03 -070088using android::base::StringPrintf;
Victor Hsiehc7ab5642023-07-28 15:07:55 -070089using android::base::unique_fd;
90using android::os::ParcelFileDescriptor;
Jeff Sharkey66b1a122017-01-16 20:57:45 -070091using std::endl;
Mike Lockwood94afecf2012-10-24 10:45:23 -070092
Andreas Gampe02d0de52015-11-11 20:43:16 -080093namespace android {
94namespace installd {
Mike Lockwood94afecf2012-10-24 10:45:23 -070095
Nikita Ioffe8e4d3462019-01-21 17:56:03 +000096// An uuid used in unit tests.
97static constexpr const char* kTestUuid = "TEST";
98
Nikita Ioffeb68f0d12019-02-04 11:06:37 +000099static constexpr const mode_t kRollbackFolderMode = 0700;
100
Jeff Sharkeycc6281c2016-02-06 19:46:09 -0700101static constexpr const char* kCpPath = "/system/bin/cp";
102static constexpr const char* kXattrDefault = "user.default";
Jeff Sharkeye3637242015-04-08 20:56:42 -0700103
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000104static constexpr const char* kDataMirrorCePath = "/data_mirror/data_ce";
105static constexpr const char* kDataMirrorDePath = "/data_mirror/data_de";
Sanjana Sunil691163d2022-03-28 19:15:54 +0000106static constexpr const char* kMiscMirrorCePath = "/data_mirror/misc_ce";
107static constexpr const char* kMiscMirrorDePath = "/data_mirror/misc_de";
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000108
Janis Danisevskis40bd3ef2016-06-07 10:31:27 -0700109static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
Janis Danisevskiseecb2d22016-01-12 14:45:55 +0000110
Andreas Gampe0354bd02016-06-27 14:25:30 -0700111static constexpr const char* PKG_LIB_POSTFIX = "/lib";
112static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
113static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
114
Zim0ce832d2019-12-03 17:03:58 +0000115static constexpr const char* kFuseProp = "persist.sys.fuse";
Victor Hsieh99de5162017-10-06 14:44:14 -0700116
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000117/**
118 * Property to control if app data isolation is enabled.
119 */
120static constexpr const char* kAppDataIsolationEnabledProperty = "persist.zygote.app_data_isolation";
Zim1edb92a2020-01-09 08:48:00 +0000121static constexpr const char* kMntSdcardfs = "/mnt/runtime/default/";
122static constexpr const char* kMntFuse = "/mnt/pass_through/0/";
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000123
124static std::atomic<bool> sAppDataIsolationEnabled(false);
125
Shikha Malhotradcf469b2022-03-23 11:53:58 +0000126/**
127 * Flag to control if project ids are supported for internal storage
128 */
129static std::atomic<bool> sUsingProjectIdsFlag(false);
130static std::once_flag flag;
131
Jeff Sharkey0274c972016-12-06 09:32:04 -0700132namespace {
133
Jeff Sharkey423e7462016-12-09 18:18:43 -0700134static binder::Status ok() {
135 return binder::Status::ok();
136}
137
138static binder::Status exception(uint32_t code, const std::string& msg) {
Jeff Sharkey8e9bf352018-02-27 11:40:45 -0700139 LOG(ERROR) << msg << " (" << code << ")";
Jeff Sharkey423e7462016-12-09 18:18:43 -0700140 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
141}
142
143static binder::Status error() {
144 return binder::Status::fromServiceSpecificError(errno);
145}
146
147static binder::Status error(const std::string& msg) {
148 PLOG(ERROR) << msg;
149 return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
150}
151
152static binder::Status error(uint32_t code, const std::string& msg) {
153 LOG(ERROR) << msg << " (" << code << ")";
154 return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
155}
156
Jeff Sharkey0274c972016-12-06 09:32:04 -0700157binder::Status checkUid(uid_t expectedUid) {
158 uid_t uid = IPCThreadState::self()->getCallingUid();
159 if (uid == expectedUid || uid == AID_ROOT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700160 return ok();
Jeff Sharkey0274c972016-12-06 09:32:04 -0700161 } else {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700162 return exception(binder::Status::EX_SECURITY,
163 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
164 }
165}
166
Jooyung Han149be4a2020-01-23 12:45:10 +0900167binder::Status checkArgumentUuid(const std::optional<std::string>& uuid) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700168 if (!uuid || is_valid_filename(*uuid)) {
169 return ok();
170 } else {
171 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
172 StringPrintf("UUID %s is malformed", uuid->c_str()));
173 }
174}
175
Jooyung Han149be4a2020-01-23 12:45:10 +0900176binder::Status checkArgumentUuidTestOrNull(const std::optional<std::string>& uuid) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000177 if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
178 return ok();
179 } else {
180 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
181 StringPrintf("UUID must be null or \"%s\", got: %s", kTestUuid, uuid->c_str()));
182 }
183}
184
Jeff Sharkey423e7462016-12-09 18:18:43 -0700185binder::Status checkArgumentPackageName(const std::string& packageName) {
Greg Kaiser6d758fc2019-03-26 08:55:32 -0700186 if (is_valid_package_name(packageName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700187 return ok();
188 } else {
189 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
190 StringPrintf("Package name %s is malformed", packageName.c_str()));
Jeff Sharkey0274c972016-12-06 09:32:04 -0700191 }
192}
193
Jeff Sharkey53594302018-02-24 18:59:39 -0700194binder::Status checkArgumentPath(const std::string& path) {
195 if (path.empty()) {
196 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing path");
197 }
198 if (path[0] != '/') {
199 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
200 StringPrintf("Path %s is relative", path.c_str()));
201 }
202 if ((path + '/').find("/../") != std::string::npos) {
203 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
204 StringPrintf("Path %s is shady", path.c_str()));
205 }
206 for (const char& c : path) {
207 if (c == '\0' || c == '\n') {
208 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
209 StringPrintf("Path %s is malformed", path.c_str()));
210 }
211 }
212 return ok();
213}
214
Jooyung Han149be4a2020-01-23 12:45:10 +0900215binder::Status checkArgumentPath(const std::optional<std::string>& path) {
Jeff Sharkey53594302018-02-24 18:59:39 -0700216 if (path) {
217 return checkArgumentPath(*path);
218 } else {
219 return ok();
220 }
221}
222
Alex Buynytskyyd04631f2022-08-12 15:14:41 -0700223binder::Status checkArgumentFileName(const std::string& path) {
224 if (path.empty()) {
225 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Missing name");
226 }
227 for (const char& c : path) {
228 if (c == '\0' || c == '\n' || c == '/') {
229 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
230 StringPrintf("Name %s is malformed", path.c_str()));
231 }
232 }
233 return ok();
234}
235
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700236binder::Status checkUidInAppRange(int32_t appUid) {
237 if (FIRST_APPLICATION_UID <= appUid && appUid <= LAST_APPLICATION_UID) {
238 return ok();
239 }
240 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
241 StringPrintf("UID %d is outside of the range", appUid));
242}
243
Jeff Sharkey0274c972016-12-06 09:32:04 -0700244#define ENFORCE_UID(uid) { \
245 binder::Status status = checkUid((uid)); \
246 if (!status.isOk()) { \
247 return status; \
248 } \
249}
250
Steven Moreland36945362023-07-05 20:29:10 +0000251// we could have tighter checks, but this is only to avoid hard errors. Negative values are defined
252// in UserHandle.java and carry specific meanings that may not be handled by certain APIs here.
Steven Moreland3e543b92023-09-07 20:08:15 +0000253#define ENFORCE_VALID_USER(userId) \
254 { \
255 if (static_cast<uid_t>(userId) >= std::numeric_limits<uid_t>::max() / AID_USER_OFFSET) { \
256 return error("userId invalid: " + std::to_string(userId)); \
257 } \
258 }
259
260#define ENFORCE_VALID_USER_OR_NULL(userId) \
261 { \
262 if (static_cast<uid_t>(userId) != USER_NULL) { \
263 ENFORCE_VALID_USER(userId); \
264 } \
Steven Moreland36945362023-07-05 20:29:10 +0000265 }
266
Jeff Sharkey423e7462016-12-09 18:18:43 -0700267#define CHECK_ARGUMENT_UUID(uuid) { \
268 binder::Status status = checkArgumentUuid((uuid)); \
269 if (!status.isOk()) { \
270 return status; \
271 } \
272}
273
Nikita Ioffe77be2ed2019-01-25 13:54:43 +0000274#define CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(uuid) { \
275 auto status = checkArgumentUuidTestOrNull(uuid); \
276 if (!status.isOk()) { \
277 return status; \
278 } \
279} \
280
Jeff Sharkey423e7462016-12-09 18:18:43 -0700281#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) { \
282 binder::Status status = \
283 checkArgumentPackageName((packageName)); \
284 if (!status.isOk()) { \
285 return status; \
286 } \
287}
288
Jeff Sharkey53594302018-02-24 18:59:39 -0700289#define CHECK_ARGUMENT_PATH(path) { \
290 binder::Status status = checkArgumentPath((path)); \
291 if (!status.isOk()) { \
292 return status; \
293 } \
294}
295
Alex Buynytskyyd04631f2022-08-12 15:14:41 -0700296#define CHECK_ARGUMENT_FILE_NAME(path) \
297 { \
298 binder::Status status = checkArgumentFileName((path)); \
299 if (!status.isOk()) { \
300 return status; \
301 } \
302 }
303
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700304#define CHECK_ARGUMENT_UID_IN_APP_RANGE(uid) \
305 { \
306 binder::Status status = checkUidInAppRange((uid)); \
307 if (!status.isOk()) { \
308 return status; \
309 } \
310 }
311
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800312#ifdef GRANULAR_LOCKS
313
314/**
315 * This class obtains in constructor and keeps the local strong pointer to the RefLock.
316 * On destruction, it checks if there are any other strong pointers, and remove the map entry if
317 * this was the last one.
318 */
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800319template <class Key, class Mutex>
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800320struct LocalLockHolder {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800321 using WeakPointer = std::weak_ptr<Mutex>;
322 using StrongPointer = std::shared_ptr<Mutex>;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800323 using Map = std::unordered_map<Key, WeakPointer>;
324 using MapLock = std::recursive_mutex;
325
326 LocalLockHolder(Key key, Map& map, MapLock& mapLock)
327 : mKey(std::move(key)), mMap(map), mMapLock(mapLock) {
328 std::lock_guard lock(mMapLock);
329 auto& weakPtr = mMap[mKey];
330
331 // Check if the RefLock is still alive.
332 mRefLock = weakPtr.lock();
333 if (!mRefLock) {
334 // Create a new lock.
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800335 mRefLock = std::make_shared<Mutex>();
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800336 weakPtr = mRefLock;
337 }
338 }
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800339 LocalLockHolder(LocalLockHolder&& other) noexcept
340 : mKey(std::move(other.mKey)),
341 mMap(other.mMap),
342 mMapLock(other.mMapLock),
343 mRefLock(std::move(other.mRefLock)) {
344 other.mRefLock.reset();
345 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800346 ~LocalLockHolder() {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800347 if (!mRefLock) {
348 return;
349 }
350
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800351 std::lock_guard lock(mMapLock);
352 // Clear the strong pointer.
353 mRefLock.reset();
354 auto found = mMap.find(mKey);
355 if (found == mMap.end()) {
356 return;
357 }
358 const auto& weakPtr = found->second;
359 // If this was the last pointer then it's ok to remove the map entry.
360 if (weakPtr.expired()) {
361 mMap.erase(found);
362 }
363 }
364
365 void lock() { mRefLock->lock(); }
366 void unlock() { mRefLock->unlock(); }
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800367 void lock_shared() { mRefLock->lock_shared(); }
368 void unlock_shared() { mRefLock->unlock_shared(); }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800369
370private:
371 Key mKey;
372 Map& mMap;
373 MapLock& mMapLock;
374 StrongPointer mRefLock;
375};
376
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800377using UserLock = LocalLockHolder<userid_t, std::shared_mutex>;
378using UserWriteLockGuard = std::unique_lock<UserLock>;
379using UserReadLockGuard = std::shared_lock<UserLock>;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800380
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800381using PackageLock = LocalLockHolder<std::string, std::recursive_mutex>;
382using PackageLockGuard = std::lock_guard<PackageLock>;
383
384#define LOCK_USER() \
385 UserLock localUserLock(userId, mUserIdLock, mLock); \
386 UserWriteLockGuard userLock(localUserLock)
387
388#define LOCK_USER_READ() \
389 UserLock localUserLock(userId, mUserIdLock, mLock); \
390 UserReadLockGuard userLock(localUserLock)
391
392#define LOCK_PACKAGE() \
393 PackageLock localPackageLock(packageName, mPackageNameLock, mLock); \
394 PackageLockGuard packageLock(localPackageLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800395
396#define LOCK_PACKAGE_USER() \
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800397 LOCK_USER_READ(); \
398 LOCK_PACKAGE()
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800399
400#else
401
402#define LOCK_USER() std::lock_guard lock(mLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800403#define LOCK_PACKAGE() std::lock_guard lock(mLock)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -0800404#define LOCK_PACKAGE_USER() \
405 (void)userId; \
406 std::lock_guard lock(mLock)
407
408#endif // GRANULAR_LOCKS
409
Jeff Sharkey0274c972016-12-06 09:32:04 -0700410} // namespace
411
Victor Hsiehc7ab5642023-07-28 15:07:55 -0700412binder::Status InstalldNativeService::FsveritySetupAuthToken::authenticate(
413 const ParcelFileDescriptor& authFd, int32_t appUid, int32_t userId) {
414 int open_flags = fcntl(authFd.get(), F_GETFL);
415 if (open_flags < 0) {
416 return exception(binder::Status::EX_SERVICE_SPECIFIC, "fcntl failed");
417 }
418 if ((open_flags & O_ACCMODE) != O_WRONLY && (open_flags & O_ACCMODE) != O_RDWR) {
419 return exception(binder::Status::EX_SECURITY, "Received FD with unexpected open flag");
420 }
421 if (fstat(authFd.get(), &this->mStatFromAuthFd) < 0) {
422 return exception(binder::Status::EX_SERVICE_SPECIFIC, "fstat failed");
423 }
424 if (!S_ISREG(this->mStatFromAuthFd.st_mode)) {
425 return exception(binder::Status::EX_SECURITY, "Not a regular file");
426 }
427 // Don't accept a file owned by a different app.
428 uid_t uid = multiuser_get_uid(userId, appUid);
429 if (this->mStatFromAuthFd.st_uid != uid) {
430 return exception(binder::Status::EX_SERVICE_SPECIFIC, "File not owned by appUid");
431 }
432 return ok();
433}
434
435bool InstalldNativeService::FsveritySetupAuthToken::isSameStat(const struct stat& st) const {
436 return memcmp(&st, &mStatFromAuthFd, sizeof(st)) == 0;
437}
438
Jeff Sharkey0274c972016-12-06 09:32:04 -0700439status_t InstalldNativeService::start() {
440 IPCThreadState::self()->disableBackgroundScheduling(true);
441 status_t ret = BinderService<InstalldNativeService>::publish();
442 if (ret != android::OK) {
443 return ret;
444 }
445 sp<ProcessState> ps(ProcessState::self());
446 ps->startThreadPool();
447 ps->giveThreadPoolName();
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000448 sAppDataIsolationEnabled = android::base::GetBoolProperty(
Ricky Wai30f947d2019-12-19 17:24:48 +0000449 kAppDataIsolationEnabledProperty, true);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700450 return android::OK;
451}
452
Alex Buynytskyy17b12dc2022-09-12 20:57:24 -0700453status_t InstalldNativeService::dump(int fd, const Vector<String16>& /* args */) {
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700454 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600455 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Keun young Park144a9892021-10-13 16:43:58 -0700456 dprintf(fd, "Storage mounts:\n");
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600457 for (const auto& n : mStorageMounts) {
Keun young Park144a9892021-10-13 16:43:58 -0700458 dprintf(fd, " %s = %s\n", n.first.c_str(), n.second.c_str());
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600459 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700460 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700461
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700462 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -0600463 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Keun young Park144a9892021-10-13 16:43:58 -0700464 dprintf(fd, "Per-UID cache quotas:\n");
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700465 for (const auto& n : mCacheQuotas) {
Keun young Park144a9892021-10-13 16:43:58 -0700466 dprintf(fd, " %d = %" PRId64 "\n", n.first, n.second);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -0700467 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -0700468 }
469
Keun young Park144a9892021-10-13 16:43:58 -0700470 dprintf(fd, "is_dexopt_blocked:%d\n", android::installd::is_dexopt_blocked());
Jeff Sharkey66b1a122017-01-16 20:57:45 -0700471
Jeff Sharkey0274c972016-12-06 09:32:04 -0700472 return NO_ERROR;
473}
474
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000475constexpr const char kXattrRestoreconInProgress[] = "user.restorecon_in_progress";
476
477static std::string lgetfilecon(const std::string& path) {
478 char* context;
479 if (::lgetfilecon(path.c_str(), &context) < 0) {
480 PLOG(ERROR) << "Failed to lgetfilecon for " << path;
481 return {};
482 }
483 std::string result{context};
484 free(context);
485 return result;
486}
487
488static bool getRestoreconInProgress(const std::string& path) {
489 bool inProgress = false;
490 if (getxattr(path.c_str(), kXattrRestoreconInProgress, &inProgress, sizeof(inProgress)) !=
491 sizeof(inProgress)) {
492 if (errno != ENODATA) {
493 PLOG(ERROR) << "Failed to check in-progress restorecon for " << path;
494 }
495 return false;
496 }
497 return inProgress;
498}
499
500struct RestoreconInProgress {
501 explicit RestoreconInProgress(const std::string& path) : mPath(path) {
502 bool inProgress = true;
503 if (setxattr(mPath.c_str(), kXattrRestoreconInProgress, &inProgress, sizeof(inProgress),
504 0) != 0) {
505 PLOG(ERROR) << "Failed to set in-progress restorecon for " << path;
506 }
507 }
508 ~RestoreconInProgress() {
509 if (removexattr(mPath.c_str(), kXattrRestoreconInProgress) < 0) {
510 PLOG(ERROR) << "Failed to clear in-progress restorecon for " << mPath;
511 }
512 }
513
514private:
515 const std::string& mPath;
516};
517
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600518/**
519 * Perform restorecon of the given path, but only perform recursive restorecon
520 * if the label of that top-level file actually changed. This can save us
521 * significant time by avoiding no-op traversals of large filesystem trees.
522 */
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700523static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
524 bool existing) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700525 ScopedTrace tracer("restorecon-lazy");
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000526 if (!existing) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700527 ScopedTrace tracer("new-path");
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000528 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
529 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
530 PLOG(ERROR) << "Failed recursive restorecon for " << path;
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000531 return -1;
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000532 }
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000533 return 0;
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000534 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600535
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000536 // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
537
538 // Check to see if there was an interrupted operation.
539 bool inProgress = getRestoreconInProgress(path);
540 std::string before, after;
541 if (!inProgress) {
542 if (before = lgetfilecon(path); before.empty()) {
543 PLOG(ERROR) << "Failed before getfilecon for " << path;
544 return -1;
545 }
546 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
547 PLOG(ERROR) << "Failed top-level restorecon for " << path;
548 return -1;
549 }
550 if (after = lgetfilecon(path); after.empty()) {
551 PLOG(ERROR) << "Failed after getfilecon for " << path;
552 return -1;
553 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600554 }
555
556 // If the initial top-level restorecon above changed the label, then go
557 // back and restorecon everything recursively
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000558 if (inProgress || before != after) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700559 ScopedTrace tracer("label-change");
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700560 if (existing) {
561 LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
562 << path << "; running recursive restorecon";
563 }
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000564
565 // Temporary mark the folder as "in-progress" to resume in case of reboot/other failure.
566 RestoreconInProgress fence(path);
567
Jeff Sharkey0274c972016-12-06 09:32:04 -0700568 if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600569 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
570 PLOG(ERROR) << "Failed recursive restorecon for " << path;
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000571 return -1;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600572 }
573 }
574
Alex Buynytskyyc668d562023-11-10 22:53:46 +0000575 return 0;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600576}
Shikha Malhotra976ae002022-02-26 15:39:53 +0000577static bool internal_storage_has_project_id() {
578 // The following path is populated in setFirstBoot, so if this file is present
Shikha Malhotradcf469b2022-03-23 11:53:58 +0000579 // then project ids can be used. Using call once to cache the result of this check
580 // to avoid having to check the file presence again and again.
581 std::call_once(flag, []() {
582 auto using_project_ids =
583 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
584 sUsingProjectIdsFlag = access(using_project_ids.c_str(), F_OK) == 0;
585 });
Shikha Malhotra8f55b3d2022-04-04 14:11:43 +0000586 // return sUsingProjectIdsFlag;
587 return false;
Shikha Malhotra976ae002022-02-26 15:39:53 +0000588}
589
590static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid, gid_t gid,
591 long project_id) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700592 {
593 ScopedTrace tracer("prepare-dir");
594 if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, gid) != 0) {
595 PLOG(ERROR) << "Failed to prepare " << path;
596 return -1;
597 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600598 }
Shikha Malhotra976ae002022-02-26 15:39:53 +0000599 if (internal_storage_has_project_id()) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700600 ScopedTrace tracer("set-quota");
Shikha Malhotra976ae002022-02-26 15:39:53 +0000601 return set_quota_project_id(path, project_id, true);
602 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600603 return 0;
604}
605
Shikha Malhotra976ae002022-02-26 15:39:53 +0000606static int prepare_app_cache_dir(const std::string& parent, const char* name, mode_t target_mode,
607 uid_t uid, gid_t gid, long project_id) {
608 auto path = StringPrintf("%s/%s", parent.c_str(), name);
Alex Buynytskyya203d712023-06-08 12:56:15 -0700609 int ret;
610 {
611 ScopedTrace tracer("prepare-cache-dir");
612 ret = prepare_app_cache_dir(parent, name, target_mode, uid, gid);
613 }
Shikha Malhotra976ae002022-02-26 15:39:53 +0000614 if (ret == 0 && internal_storage_has_project_id()) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700615 ScopedTrace tracer("set-quota-cache-dir");
Shikha Malhotra976ae002022-02-26 15:39:53 +0000616 return set_quota_project_id(path, project_id, true);
617 }
618 return ret;
619}
620
Calin Juravled2affb82017-11-28 17:41:43 -0800621static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700622 ScopedTrace tracer("prepare-app-profile");
Calin Juravled2affb82017-11-28 17:41:43 -0800623 int32_t uid = multiuser_get_uid(userId, appId);
624 int shared_app_gid = multiuser_get_shared_gid(userId, appId);
625 if (shared_app_gid == -1) {
626 // TODO(calin): this should no longer be possible but do not continue if we don't get
627 // a valid shared gid.
628 PLOG(WARNING) << "Invalid shared_app_gid for " << packageName;
629 return true;
630 }
631
632 const std::string profile_dir =
633 create_primary_current_profile_package_dir_path(userId, packageName);
634 // read-write-execute only for the app user.
635 if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
636 PLOG(ERROR) << "Failed to prepare " << profile_dir;
637 return false;
638 }
Alan Stokes928d2c12020-12-09 10:11:24 +0000639 if (selinux_android_restorecon(profile_dir.c_str(), 0)) {
640 PLOG(ERROR) << "Failed to restorecon " << profile_dir;
641 return false;
642 }
Calin Juravlecfcd6aa2018-01-18 20:23:17 -0800643
Calin Juravled2affb82017-11-28 17:41:43 -0800644 const std::string ref_profile_path =
645 create_primary_reference_profile_package_dir_path(packageName);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800646
647 // Prepare the reference profile directory. Note that we use the non strict version of
648 // fs_prepare_dir. This will fix the permission and the ownership to the correct values.
649 // This is particularly important given that in O there were some fixes for how the
650 // shared_app_gid is computed.
651 //
652 // Note that by the time we get here we know that we are using a correct uid (otherwise
653 // prepare_app_dir and the above fs_prepare_file_strict which check the uid). So we
654 // are sure that the gid being used belongs to the owning app and not someone else.
655 //
656 // dex2oat/profman runs under the shared app gid and it needs to read/write reference profiles.
657 if (fs_prepare_dir(ref_profile_path.c_str(), 0770, AID_SYSTEM, shared_app_gid) != 0) {
Calin Juravled2affb82017-11-28 17:41:43 -0800658 PLOG(ERROR) << "Failed to prepare " << ref_profile_path;
659 return false;
660 }
Calin Juravle6f06eb62017-11-28 18:44:53 -0800661
Calin Juravled2affb82017-11-28 17:41:43 -0800662 return true;
663}
664
John Wu84e8f242021-10-21 11:50:41 -0700665static bool chown_app_dir(const std::string& path, uid_t uid, uid_t previousUid, gid_t cacheGid) {
666 FTS* fts;
667 char *argv[] = { (char*) path.c_str(), nullptr };
668 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
669 return false;
670 }
671 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
672 if (p->fts_info == FTS_D && p->fts_level == 1
673 && (strcmp(p->fts_name, "cache") == 0
674 || strcmp(p->fts_name, "code_cache") == 0)) {
675 // Mark cache dirs
676 p->fts_number = 1;
677 } else {
678 // Inherit parent's number
679 p->fts_number = p->fts_parent->fts_number;
680 }
681
682 switch (p->fts_info) {
683 case FTS_D:
684 case FTS_F:
685 case FTS_SL:
686 case FTS_SLNONE:
687 if (p->fts_statp->st_uid == previousUid) {
688 if (lchown(p->fts_path, uid, p->fts_number ? cacheGid : uid) != 0) {
689 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
690 }
691 } else {
692 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected UID "
693 << p->fts_statp->st_uid << " instead of " << previousUid;
694 }
695 break;
696 }
697 }
698 fts_close(fts);
699 return true;
700}
701
702static void chown_app_profile_dir(const std::string &packageName, int32_t appId, int32_t userId) {
703 uid_t uid = multiuser_get_uid(userId, appId);
704 gid_t sharedGid = multiuser_get_shared_gid(userId, appId);
705
706 const std::string profile_dir =
707 create_primary_current_profile_package_dir_path(userId, packageName);
708 char *argv[] = { (char*) profile_dir.c_str(), nullptr };
709 if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
710 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
711 switch (p->fts_info) {
712 case FTS_D:
713 case FTS_F:
714 case FTS_SL:
715 case FTS_SLNONE:
716 if (lchown(p->fts_path, uid, uid) != 0) {
717 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
718 }
719 break;
720 }
721 }
722 fts_close(fts);
723 }
724
725 const std::string ref_profile_path =
726 create_primary_reference_profile_package_dir_path(packageName);
727 argv[0] = (char *) ref_profile_path.c_str();
728 if (FTS* fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr)) {
729 for (FTSENT* p; (p = fts_read(fts)) != nullptr;) {
730 if (p->fts_info == FTS_D && p->fts_level == 0) {
731 if (chown(p->fts_path, AID_SYSTEM, sharedGid) != 0) {
732 PLOG(WARNING) << "Failed to chown " << p->fts_path;
733 }
734 continue;
735 }
736 switch (p->fts_info) {
737 case FTS_D:
738 case FTS_F:
739 case FTS_SL:
740 case FTS_SLNONE:
741 if (lchown(p->fts_path, sharedGid, sharedGid) != 0) {
742 PLOG(WARNING) << "Failed to lchown " << p->fts_path;
743 }
744 break;
745 }
746 }
747 fts_close(fts);
748 }
749}
750
Mohammad Samiul Islama73327a2022-03-09 09:59:32 +0000751static binder::Status createAppDataDirs(const std::string& path, int32_t uid, int32_t gid,
John Wu841a8022022-04-05 21:17:54 +0000752 int32_t previousUid, int32_t cacheGid,
Samiul Islam8621e552022-03-30 16:26:45 +0100753 const std::string& seInfo, mode_t targetMode,
754 long projectIdApp, long projectIdCache) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700755 ScopedTrace tracer("create-dirs");
John Wu84e8f242021-10-21 11:50:41 -0700756 struct stat st{};
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000757 bool parent_dir_exists = (stat(path.c_str(), &st) == 0);
758
759 auto cache_path = StringPrintf("%s/%s", path.c_str(), "cache");
760 auto code_cache_path = StringPrintf("%s/%s", path.c_str(), "code_cache");
761 bool cache_exists = (access(cache_path.c_str(), F_OK) == 0);
762 bool code_cache_exists = (access(code_cache_path.c_str(), F_OK) == 0);
763
764 if (parent_dir_exists) {
John Wu841a8022022-04-05 21:17:54 +0000765 if (previousUid > 0 && previousUid != uid) {
766 if (!chown_app_dir(path, uid, previousUid, cacheGid)) {
John Wu84e8f242021-10-21 11:50:41 -0700767 return error("Failed to chown " + path);
768 }
769 }
770 }
771
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000772 // Prepare only the parent app directory
Samiul Islam8621e552022-03-30 16:26:45 +0100773 if (prepare_app_dir(path, targetMode, uid, gid, projectIdApp) ||
774 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid, projectIdCache) ||
775 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid, projectIdCache)) {
John Wu84e8f242021-10-21 11:50:41 -0700776 return error("Failed to prepare " + path);
777 }
778
779 // Consider restorecon over contents if label changed
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000780 if (restorecon_app_data_lazy(path, seInfo, uid, parent_dir_exists)) {
John Wu84e8f242021-10-21 11:50:41 -0700781 return error("Failed to restorecon " + path);
782 }
783
Jigar Thakkarf42c8a72021-10-28 17:24:33 +0000784 // If the parent dir exists, the restorecon would already have been done
785 // as a part of the recursive restorecon above
786 if (parent_dir_exists && !cache_exists
787 && restorecon_app_data_lazy(cache_path, seInfo, uid, false)) {
788 return error("Failed to restorecon " + cache_path);
789 }
790
791 // If the parent dir exists, the restorecon would already have been done
792 // as a part of the recursive restorecon above
793 if (parent_dir_exists && !code_cache_exists
794 && restorecon_app_data_lazy(code_cache_path, seInfo, uid, false)) {
795 return error("Failed to restorecon " + code_cache_path);
796 }
John Wu84e8f242021-10-21 11:50:41 -0700797 return ok();
798}
799
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800800binder::Status InstalldNativeService::createAppDataLocked(
801 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
802 int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000803 int32_t targetSdkVersion, int64_t* ceDataInode, int64_t* deDataInode) {
Jeff Sharkey0274c972016-12-06 09:32:04 -0700804 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000805 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -0700806 CHECK_ARGUMENT_UUID(uuid);
807 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey0274c972016-12-06 09:32:04 -0700808
809 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
810 const char* pkgname = packageName.c_str();
811
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700812 // Assume invalid inode unless filled in below
Songchun Fancb567f92023-09-11 17:04:47 +0000813 if (ceDataInode != nullptr) *ceDataInode = -1;
814 if (deDataInode != nullptr) *deDataInode = -1;
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700815
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700816 int32_t uid = multiuser_get_uid(userId, appId);
John Wu84e8f242021-10-21 11:50:41 -0700817
John Wu841a8022022-04-05 21:17:54 +0000818 // If previousAppId > 0, an app is changing its app ID
819 int32_t previousUid =
820 previousAppId > 0 ? (int32_t)multiuser_get_uid(userId, previousAppId) : -1;
John Wu84e8f242021-10-21 11:50:41 -0700821
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700822 int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -0700823 mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
824
Jeff Sharkey24ef15b2017-01-12 19:27:03 -0700825 // If UID doesn't have a specific cache GID, use UID value
826 if (cacheGid == -1) {
827 cacheGid = uid;
828 }
829
Samiul Islam8621e552022-03-30 16:26:45 +0100830 long projectIdApp = get_project_id(uid, PROJECT_ID_APP_START);
831 long projectIdCache = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
832
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700833 if (flags & FLAG_STORAGE_CE) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700834 ScopedTrace tracer("ce");
Jeff Sharkey0274c972016-12-06 09:32:04 -0700835 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700836
John Wu841a8022022-04-05 21:17:54 +0000837 auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
Samiul Islam8621e552022-03-30 16:26:45 +0100838 projectIdApp, projectIdCache);
John Wu84e8f242021-10-21 11:50:41 -0700839 if (!status.isOk()) {
840 return status;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600841 }
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -0600842
843 // Remember inode numbers of cache directories so that we can clear
844 // contents while CE storage is locked
845 if (write_path_inode(path, "cache", kXattrInodeCache) ||
846 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -0700847 return error("Failed to write_path_inode for " + path);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -0700848 }
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700849
850 // And return the CE inode of the top-level data directory so we can
851 // clear contents while CE storage is locked
Songchun Fancb567f92023-09-11 17:04:47 +0000852 if (ceDataInode != nullptr) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +0000853 ino_t result;
854 if (get_path_inode(path, &result) != 0) {
855 return error("Failed to get_path_inode for " + path);
856 }
Songchun Fancb567f92023-09-11 17:04:47 +0000857 *ceDataInode = static_cast<uint64_t>(result);
Jeff Sharkey36a900a2016-12-19 16:39:18 -0700858 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700859 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -0700860 if (flags & FLAG_STORAGE_DE) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700861 ScopedTrace tracer("de");
Jeff Sharkey0274c972016-12-06 09:32:04 -0700862 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkey35b83df2016-12-21 09:33:55 -0700863
John Wu841a8022022-04-05 21:17:54 +0000864 auto status = createAppDataDirs(path, uid, uid, previousUid, cacheGid, seInfo, targetMode,
Samiul Islam8621e552022-03-30 16:26:45 +0100865 projectIdApp, projectIdCache);
John Wu84e8f242021-10-21 11:50:41 -0700866 if (!status.isOk()) {
867 return status;
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600868 }
John Wu841a8022022-04-05 21:17:54 +0000869 if (previousUid > 0 && previousUid != uid) {
John Wu3b383372022-02-09 02:21:39 -0800870 chown_app_profile_dir(packageName, appId, userId);
871 }
Jeff Sharkey22f6fd52016-09-20 18:21:42 -0600872
Calin Juravled2affb82017-11-28 17:41:43 -0800873 if (!prepare_app_profile_dir(packageName, appId, userId)) {
874 return error("Failed to prepare profiles for " + packageName);
Calin Juravle6a1648e2016-02-01 12:12:16 +0000875 }
Songchun Fancb567f92023-09-11 17:04:47 +0000876
877 if (deDataInode != nullptr) {
878 ino_t result;
879 if (get_path_inode(path, &result) != 0) {
880 return error("Failed to get_path_inode for " + path);
881 }
882 *deDataInode = static_cast<uint64_t>(result);
883 }
Mike Lockwood94afecf2012-10-24 10:45:23 -0700884 }
Samiul Islamc40dff52022-01-14 16:24:48 +0000885
Samiul Islam7d5b1da2022-02-21 15:23:36 +0000886 if (flags & FLAG_STORAGE_SDK) {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700887 ScopedTrace tracer("sdk");
Samiul Islam92f5cf02022-02-03 12:45:51 +0000888 // Safe to ignore status since we can retry creating this by calling reconcileSdkData
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000889 auto ignore = createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000890 if (!ignore.isOk()) {
891 PLOG(WARNING) << "Failed to create sdk data package directory for " << packageName;
Samiul Islamc40dff52022-01-14 16:24:48 +0000892 }
Samiul Islam92f5cf02022-02-03 12:45:51 +0000893 } else {
Alex Buynytskyya203d712023-06-08 12:56:15 -0700894 ScopedTrace tracer("destroy-sdk");
Samiul Islam92f5cf02022-02-03 12:45:51 +0000895 // Package does not need sdk storage. Remove it.
Rishabh Singhe84b0b12022-02-02 20:56:13 +0000896 destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
Samiul Islamc40dff52022-01-14 16:24:48 +0000897 }
898
899 return ok();
900}
901
902/**
Samiul Islam92f5cf02022-02-03 12:45:51 +0000903 * Responsible for creating /data/misc_{ce|de}/user/0/sdksandbox/<package-name> directory and other
Samiul Islamc40dff52022-01-14 16:24:48 +0000904 * app level sub directories, such as ./shared
905 */
Samiul Islam92f5cf02022-02-03 12:45:51 +0000906binder::Status InstalldNativeService::createSdkSandboxDataPackageDirectory(
Samiul Islamc40dff52022-01-14 16:24:48 +0000907 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000908 int32_t appId, int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +0000909 ENFORCE_VALID_USER(userId);
910
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000911 int32_t sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
912 if (sdkSandboxUid == -1) {
913 // There no valid sdk sandbox process for this app. Skip creation of data directory
Samiul Islamc40dff52022-01-14 16:24:48 +0000914 return ok();
915 }
916
Samiul Islamc40dff52022-01-14 16:24:48 +0000917 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
918
919 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +0000920 for (int currentFlag : storageFlags) {
Samiul Islamc40dff52022-01-14 16:24:48 +0000921 if ((flags & currentFlag) == 0) {
922 continue;
923 }
924 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
925
Nikita Ioffe4ee18ae2022-02-21 19:02:05 +0000926 // /data/misc_{ce,de}/<user-id>/sdksandbox directory gets created by vold
Samiul Islamc40dff52022-01-14 16:24:48 +0000927 // during user creation
928
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +0000929 // Prepare the package directory
Samiul Islam92f5cf02022-02-03 12:45:51 +0000930 auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
931 packageName.c_str());
932#if SDK_DEBUG
933 LOG(DEBUG) << "Creating app-level sdk data directory: " << packagePath;
934#endif
935
Shikha Malhotra976ae002022-02-26 15:39:53 +0000936 if (prepare_app_dir(packagePath, 0751, AID_SYSTEM, AID_SYSTEM, 0)) {
Samiul Islam92f5cf02022-02-03 12:45:51 +0000937 return error("Failed to prepare " + packagePath);
Samiul Islamc40dff52022-01-14 16:24:48 +0000938 }
Samiul Islamc40dff52022-01-14 16:24:48 +0000939 }
940
Jeff Sharkey423e7462016-12-09 18:18:43 -0700941 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -0700942}
943
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600944binder::Status InstalldNativeService::createAppData(
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800945 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
946 int32_t flags, int32_t appId, int32_t previousAppId, const std::string& seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000947 int32_t targetSdkVersion, int64_t* ceDataInode, int64_t* deDataInode) {
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800948 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000949 ENFORCE_VALID_USER(userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800950 CHECK_ARGUMENT_UUID(uuid);
951 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
952 LOCK_PACKAGE_USER();
953 return createAppDataLocked(uuid, packageName, userId, flags, appId, previousAppId, seInfo,
Songchun Fancb567f92023-09-11 17:04:47 +0000954 targetSdkVersion, ceDataInode, deDataInode);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800955}
956
957binder::Status InstalldNativeService::createAppData(
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600958 const android::os::CreateAppDataArgs& args,
959 android::os::CreateAppDataResult* _aidl_return) {
960 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000961 ENFORCE_VALID_USER(args.userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800962 // Locking is performed depeer in the callstack.
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600963
964 int64_t ceDataInode = -1;
Songchun Fancb567f92023-09-11 17:04:47 +0000965 int64_t deDataInode = -1;
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600966 auto status = createAppData(args.uuid, args.packageName, args.userId, args.flags, args.appId,
Songchun Fancb567f92023-09-11 17:04:47 +0000967 args.previousAppId, args.seInfo, args.targetSdkVersion,
968 &ceDataInode, &deDataInode);
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600969 _aidl_return->ceDataInode = ceDataInode;
Songchun Fancb567f92023-09-11 17:04:47 +0000970 _aidl_return->deDataInode = deDataInode;
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600971 _aidl_return->exceptionCode = status.exceptionCode();
972 _aidl_return->exceptionMessage = status.exceptionMessage();
973 return ok();
974}
975
976binder::Status InstalldNativeService::createAppDataBatched(
977 const std::vector<android::os::CreateAppDataArgs>& args,
978 std::vector<android::os::CreateAppDataResult>* _aidl_return) {
979 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +0000980 for (const auto& arg : args) {
981 ENFORCE_VALID_USER(arg.userId);
982 }
983
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -0800984 // Locking is performed depeer in the callstack.
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600985
986 std::vector<android::os::CreateAppDataResult> results;
John Wu84e8f242021-10-21 11:50:41 -0700987 for (const auto &arg : args) {
Jeff Sharkey8d3848b2020-08-13 14:16:46 -0600988 android::os::CreateAppDataResult result;
989 createAppData(arg, &result);
990 results.push_back(result);
991 }
992 *_aidl_return = results;
993 return ok();
994}
995
Samiul Islam92f5cf02022-02-03 12:45:51 +0000996binder::Status InstalldNativeService::reconcileSdkData(
997 const android::os::ReconcileSdkDataArgs& args) {
Steven Moreland36945362023-07-05 20:29:10 +0000998 ENFORCE_VALID_USER(args.userId);
Samiul Islam92f5cf02022-02-03 12:45:51 +0000999 // Locking is performed depeer in the callstack.
1000
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001001 return reconcileSdkData(args.uuid, args.packageName, args.subDirNames, args.userId, args.appId,
1002 args.previousAppId, args.seInfo, args.flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001003}
1004
1005/**
1006 * Reconciles per-sdk directory under app-level sdk data directory.
1007
1008 * E.g. `/data/misc_ce/0/sdksandbox/<package-name>/<sdkPackageName>-<randomSuffix>
1009 *
1010 * - If the sdk data package directory is missing, we create it first.
1011 * - If sdkPackageNames is empty, we delete sdk package directory since it's not needed anymore.
1012 * - If a sdk level directory we need to prepare already exist, we skip creating it again. This
1013 * is to avoid having same per-sdk directory with different suffix.
1014 * - If a sdk level directory exist which is absent from sdkPackageNames, we remove it.
1015 */
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001016binder::Status InstalldNativeService::reconcileSdkData(const std::optional<std::string>& uuid,
1017 const std::string& packageName,
1018 const std::vector<std::string>& subDirNames,
1019 int userId, int appId, int previousAppId,
1020 const std::string& seInfo, int flags) {
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001021 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001022 ENFORCE_VALID_USER(userId);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001023 CHECK_ARGUMENT_UUID(uuid);
1024 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001025 LOCK_PACKAGE_USER();
1026
1027#if SDK_DEBUG
1028 LOG(DEBUG) << "Creating per sdk data directory for: " << packageName;
1029#endif
1030
1031 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1032
Samiul Islam92f5cf02022-02-03 12:45:51 +00001033 // Prepare the sdk package directory in case it's missing
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001034 const auto status =
1035 createSdkSandboxDataPackageDirectory(uuid, packageName, userId, appId, flags);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001036 if (!status.isOk()) {
1037 return status;
1038 }
1039
1040 auto res = ok();
1041 // We have to create sdk data for CE and DE storage
1042 const int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1043 for (int currentFlag : storageFlags) {
1044 if ((flags & currentFlag) == 0) {
1045 continue;
1046 }
1047 const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1048
Samiul Islam92f5cf02022-02-03 12:45:51 +00001049 const auto packagePath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId,
1050 packageName.c_str());
Samiul Islam92f5cf02022-02-03 12:45:51 +00001051
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001052 // Remove existing sub-directories not referred in subDirNames
1053 const std::unordered_set<std::string> expectedSubDirNames(subDirNames.begin(),
1054 subDirNames.end());
1055 const auto subDirHandler = [&packagePath, &expectedSubDirNames,
1056 &res](const std::string& subDirName) {
Samiul Islam92f5cf02022-02-03 12:45:51 +00001057 // Remove the per-sdk directory if it is not referred in
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001058 // expectedSubDirNames
1059 if (expectedSubDirNames.find(subDirName) == expectedSubDirNames.end()) {
1060 auto path = packagePath + "/" + subDirName;
1061 if (delete_dir_contents_and_dir(path) != 0) {
1062 res = error("Failed to delete " + path);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001063 return;
1064 }
Samiul Islam92f5cf02022-02-03 12:45:51 +00001065 }
1066 };
1067 const int ec = foreach_subdir(packagePath, subDirHandler);
1068 if (ec != 0) {
1069 res = error("Failed to process subdirs for " + packagePath);
1070 continue;
1071 }
1072
Mohammad Samiul Islam5288b052022-03-09 17:04:38 +00001073 // Now create the subDirNames
1074 for (const auto& subDirName : subDirNames) {
1075 const std::string path =
1076 create_data_misc_sdk_sandbox_sdk_path(uuid_, isCeData, userId,
1077 packageName.c_str(), subDirName.c_str());
Samiul Islam92f5cf02022-02-03 12:45:51 +00001078
1079 // Create the directory along with cache and code_cache
1080 const int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
1081 if (cacheGid == -1) {
1082 return exception(binder::Status::EX_ILLEGAL_STATE,
1083 StringPrintf("cacheGid cannot be -1 for sdk data"));
1084 }
1085 const int32_t sandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
1086 int32_t previousSandboxUid = multiuser_get_sdk_sandbox_uid(userId, previousAppId);
Samiul Islam8621e552022-03-30 16:26:45 +01001087 int32_t appUid = multiuser_get_uid(userId, appId);
1088 long projectIdApp = get_project_id(appUid, PROJECT_ID_APP_START);
1089 long projectIdCache = get_project_id(appUid, PROJECT_ID_APP_CACHE_START);
1090 auto status =
John Wu841a8022022-04-05 21:17:54 +00001091 createAppDataDirs(path, sandboxUid, AID_NOBODY, previousSandboxUid, cacheGid,
Samiul Islam8621e552022-03-30 16:26:45 +01001092 seInfo, 0700 | S_ISGID, projectIdApp, projectIdCache);
Samiul Islam92f5cf02022-02-03 12:45:51 +00001093 if (!status.isOk()) {
1094 res = status;
1095 continue;
1096 }
1097 }
1098 }
1099
1100 return res;
1101}
1102
Jooyung Han149be4a2020-01-23 12:45:10 +09001103binder::Status InstalldNativeService::migrateAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001104 const std::string& packageName, int32_t userId, int32_t flags) {
1105 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001106 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001107 CHECK_ARGUMENT_UUID(uuid);
1108 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001109 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001110
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001111 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1112 const char* pkgname = packageName.c_str();
1113
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001114 // This method only exists to upgrade system apps that have requested
1115 // forceDeviceEncrypted, so their default storage always lives in a
1116 // consistent location. This only works on non-FBE devices, since we
1117 // never want to risk exposing data on a device with real CE/DE storage.
1118
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001119 auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
1120 auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001121
1122 // If neither directory is marked as default, assume CE is default
1123 if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
1124 && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
1125 if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001126 return error("Failed to mark default storage " + ce_path);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001127 }
1128 }
1129
1130 // Migrate default data location if needed
1131 auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
1132 auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
1133
1134 if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
1135 LOG(WARNING) << "Requested default storage " << target
1136 << " is not active; migrating from " << source;
1137 if (delete_dir_contents_and_dir(target) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001138 return error("Failed to delete " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001139 }
1140 if (rename(source.c_str(), target.c_str()) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001141 return error("Failed to rename " + source + " to " + target);
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001142 }
1143 }
1144
Jeff Sharkey423e7462016-12-09 18:18:43 -07001145 return ok();
Jeff Sharkeycc6281c2016-02-06 19:46:09 -07001146}
1147
Calin Juravle6a1648e2016-02-01 12:12:16 +00001148
Calin Juravle562de812018-01-20 23:34:18 -08001149binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName,
1150 const std::string& profileName) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001151 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001152 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyydf2fb612022-08-12 15:42:01 -07001153 CHECK_ARGUMENT_FILE_NAME(profileName);
1154 if (!base::EndsWith(profileName, ".prof")) {
1155 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
1156 StringPrintf("Profile name %s does not end with .prof",
1157 profileName.c_str()));
1158 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001159 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001160
Jeff Sharkey423e7462016-12-09 18:18:43 -07001161 binder::Status res = ok();
Calin Juravle562de812018-01-20 23:34:18 -08001162 if (!clear_primary_reference_profile(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001163 res = error("Failed to clear reference profile for " + packageName);
1164 }
Calin Juravle562de812018-01-20 23:34:18 -08001165 if (!clear_primary_current_profiles(packageName, profileName)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001166 res = error("Failed to clear current profiles for " + packageName);
1167 }
1168 return res;
Calin Juravle6a1648e2016-02-01 12:12:16 +00001169}
1170
Jooyung Han149be4a2020-01-23 12:45:10 +09001171binder::Status InstalldNativeService::clearAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001172 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1173 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001174 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001175 CHECK_ARGUMENT_UUID(uuid);
1176 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001177 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001178
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001179 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1180 const char* pkgname = packageName.c_str();
1181
Jeff Sharkey423e7462016-12-09 18:18:43 -07001182 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001183 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001184 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001185 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1186 path = read_path_inode(path, "cache", kXattrInodeCache);
1187 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1188 path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
1189 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001190 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001191 if (delete_dir_contents(path) != 0) {
1192 res = error("Failed to delete contents of " + path);
Ryuki Nakamurac7342f82017-09-30 11:57:00 +09001193 } else if ((flags & (FLAG_CLEAR_CACHE_ONLY | FLAG_CLEAR_CODE_CACHE_ONLY)) == 0) {
1194 remove_path_xattr(path, kXattrInodeCache);
1195 remove_path_xattr(path, kXattrInodeCodeCache);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001196 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001197 }
1198 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001199 if (flags & FLAG_STORAGE_DE) {
John Wu84e8f242021-10-21 11:50:41 -07001200 std::string suffix;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001201 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1202 suffix = CACHE_DIR_POSTFIX;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001203 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1204 suffix = CODE_CACHE_DIR_POSTFIX;
Jeff Sharkey1f6a7f12016-07-14 18:16:22 -06001205 }
1206
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001207 auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001208 if (access(path.c_str(), F_OK) == 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001209 if (delete_dir_contents(path) != 0) {
1210 res = error("Failed to delete contents of " + path);
1211 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001212 }
1213 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001214 if (flags & FLAG_STORAGE_EXTERNAL) {
1215 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1216 for (const auto& n : mStorageMounts) {
1217 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +00001218
1219 if (android::base::GetBoolProperty(kFuseProp, false)) {
1220 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1221 if (std::regex_match(extPath, re)) {
1222 extPath += "/" + std::to_string(userId);
1223 }
1224 } else {
1225 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1226 extPath += StringPrintf("/%d", userId);
1227 } else if (userId != 0) {
1228 // TODO: support devices mounted under secondary users
1229 continue;
1230 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001231 }
Zim0ce832d2019-12-03 17:03:58 +00001232
Jeff Sharkey6e175692019-05-14 14:55:33 -06001233 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1234 // Clear only cached data from shared storage
1235 auto path = StringPrintf("%s/Android/data/%s/cache", extPath.c_str(), pkgname);
1236 if (delete_dir_contents(path, true) != 0) {
1237 res = error("Failed to delete contents of " + path);
1238 }
1239 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1240 // No code cache on shared storage
1241 } else {
1242 // Clear everything on shared storage
1243 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
1244 if (delete_dir_contents(path, true) != 0) {
1245 res = error("Failed to delete contents of " + path);
1246 }
1247 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
1248 if (delete_dir_contents(path, true) != 0) {
1249 res = error("Failed to delete contents of " + path);
1250 }
Martijn Coenen24a93072020-01-08 10:10:43 +01001251 // Note that we explicitly don't delete OBBs - those are only removed on
1252 // app uninstall.
Jeff Sharkey6e175692019-05-14 14:55:33 -06001253 }
1254 }
1255 }
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001256 auto status = clearSdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1257 if (!status.isOk()) {
1258 res = status;
1259 }
1260 return res;
1261}
1262
1263binder::Status InstalldNativeService::clearSdkSandboxDataPackageDirectory(
1264 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1265 int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00001266 ENFORCE_VALID_USER(userId);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001267 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1268 const char* pkgname = packageName.c_str();
1269
1270 binder::Status res = ok();
1271 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1272 for (int i = 0; i < 2; i++) {
1273 int currentFlag = storageFlags[i];
1274 if ((flags & currentFlag) == 0) {
1275 continue;
1276 }
1277 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1278 std::string suffix;
1279 if (flags & FLAG_CLEAR_CACHE_ONLY) {
1280 suffix = CACHE_DIR_POSTFIX;
1281 } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
1282 suffix = CODE_CACHE_DIR_POSTFIX;
1283 }
1284
1285 auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1286 if (access(appPath.c_str(), F_OK) != 0) continue;
1287 const auto subDirHandler = [&appPath, &res, &suffix](const std::string& filename) {
1288 auto filepath = appPath + "/" + filename + suffix;
1289 if (delete_dir_contents(filepath, true) != 0) {
1290 res = error("Failed to clear contents of " + filepath);
1291 }
1292 };
1293 const int ec = foreach_subdir(appPath, subDirHandler);
1294 if (ec != 0) {
1295 res = error("Failed to process subdirs for " + appPath);
1296 }
1297 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001298 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001299}
1300
Calin Juravle76268c52017-03-09 13:19:42 -08001301static int destroy_app_reference_profile(const std::string& pkgname) {
Calin Juravle7535e8e2016-03-29 16:05:40 +01001302 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -08001303 create_primary_reference_profile_package_dir_path(pkgname),
Calin Juravle7535e8e2016-03-29 16:05:40 +01001304 /*ignore_if_missing*/ true);
1305}
1306
Calin Juravle76268c52017-03-09 13:19:42 -08001307static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
Calin Juravleb06f98a2016-03-28 15:11:01 +01001308 return delete_dir_contents_and_dir(
Calin Juravle114f0812017-03-08 19:05:07 -08001309 create_primary_current_profile_package_dir_path(userid, pkgname),
Calin Juravleb06f98a2016-03-28 15:11:01 +01001310 /*ignore_if_missing*/ true);
Calin Juravleedae6692016-03-23 13:55:31 +00001311}
1312
Jeff Sharkey475c6f92016-12-07 10:37:27 -07001313binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
1314 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001315 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001316 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001317
Jeff Sharkey423e7462016-12-09 18:18:43 -07001318 binder::Status res = ok();
Calin Juravleedae6692016-03-23 13:55:31 +00001319 std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
1320 for (auto user : users) {
Calin Juravle76268c52017-03-09 13:19:42 -08001321 if (destroy_app_current_profiles(packageName, user) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001322 res = error("Failed to destroy current profiles for " + packageName);
1323 }
Calin Juravleedae6692016-03-23 13:55:31 +00001324 }
Calin Juravle76268c52017-03-09 13:19:42 -08001325 if (destroy_app_reference_profile(packageName) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001326 res = error("Failed to destroy reference profile for " + packageName);
1327 }
1328 return res;
Calin Juravlecaa6b802016-03-22 14:15:52 +00001329}
1330
Jiakai Zhangee00e3b2022-03-24 15:03:04 +00001331binder::Status InstalldNativeService::deleteReferenceProfile(const std::string& packageName,
1332 const std::string& profileName) {
1333 ENFORCE_UID(AID_SYSTEM);
1334 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1335 LOCK_PACKAGE();
1336
1337 // This function only supports primary dex'es.
1338 std::string path =
1339 create_reference_profile_path(packageName, profileName, /*is_secondary_dex=*/false);
1340 if (unlink(path.c_str()) != 0) {
1341 if (errno == ENOENT) {
1342 return ok();
1343 } else {
1344 return error("Failed to delete profile " + profileName + " for " + packageName);
1345 }
1346 }
1347 return ok();
1348}
1349
Jooyung Han149be4a2020-01-23 12:45:10 +09001350binder::Status InstalldNativeService::destroyAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001351 const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
1352 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001353 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07001354 CHECK_ARGUMENT_UUID(uuid);
1355 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001356 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07001357
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07001358 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1359 const char* pkgname = packageName.c_str();
1360
Jeff Sharkey423e7462016-12-09 18:18:43 -07001361 binder::Status res = ok();
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001362 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001363 auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08001364 if (rename_delete_dir_contents_and_dir(path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001365 res = error("Failed to delete " + path);
1366 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001367 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07001368 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001369 auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08001370 if (rename_delete_dir_contents_and_dir(path) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001371 res = error("Failed to delete " + path);
1372 }
Alan Stokesd983cc72020-02-14 14:36:58 +00001373 if ((flags & FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES) == 0) {
1374 destroy_app_current_profiles(packageName, userId);
1375 // TODO(calin): If the package is still installed by other users it's probably
1376 // beneficial to keep the reference profile around.
1377 // Verify if it's ok to do that.
1378 destroy_app_reference_profile(packageName);
1379 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07001380 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001381 if (flags & FLAG_STORAGE_EXTERNAL) {
1382 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
1383 for (const auto& n : mStorageMounts) {
1384 auto extPath = n.second;
Zim0ce832d2019-12-03 17:03:58 +00001385
1386 if (android::base::GetBoolProperty(kFuseProp, false)) {
1387 std::regex re("^\\/mnt\\/pass_through\\/[0-9]+\\/emulated");
1388 if (std::regex_match(extPath, re)) {
1389 extPath += "/" + std::to_string(userId);
1390 }
1391 } else {
1392 if (n.first.compare(0, 14, "/mnt/media_rw/") != 0) {
1393 extPath += StringPrintf("/%d", userId);
1394 } else if (userId != 0) {
1395 // TODO: support devices mounted under secondary users
1396 continue;
1397 }
Jeff Sharkey6e175692019-05-14 14:55:33 -06001398 }
Zim0ce832d2019-12-03 17:03:58 +00001399
Jeff Sharkey6e175692019-05-14 14:55:33 -06001400 auto path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001401 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001402 res = error("Failed to delete contents of " + path);
1403 }
1404 path = StringPrintf("%s/Android/media/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001405 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001406 res = error("Failed to delete contents of " + path);
1407 }
1408 path = StringPrintf("%s/Android/obb/%s", extPath.c_str(), pkgname);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08001409 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey6e175692019-05-14 14:55:33 -06001410 res = error("Failed to delete contents of " + path);
1411 }
1412 }
1413 }
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001414 auto status = destroySdkSandboxDataPackageDirectory(uuid, packageName, userId, flags);
1415 if (!status.isOk()) {
1416 res = status;
1417 }
1418 return res;
1419}
1420
1421binder::Status InstalldNativeService::destroySdkSandboxDataPackageDirectory(
1422 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
1423 int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00001424 ENFORCE_VALID_USER(userId);
1425
Rishabh Singhe84b0b12022-02-02 20:56:13 +00001426 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1427 const char* pkgname = packageName.c_str();
1428
1429 binder::Status res = ok();
1430 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1431 for (int i = 0; i < 2; i++) {
1432 int currentFlag = storageFlags[i];
1433 if ((flags & currentFlag) == 0) {
1434 continue;
1435 }
1436 bool isCeData = (currentFlag == FLAG_STORAGE_CE);
1437 auto appPath = create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgname);
1438 if (rename_delete_dir_contents_and_dir(appPath) != 0) {
1439 res = error("Failed to delete " + appPath);
1440 }
1441 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07001442 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07001443}
1444
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001445static gid_t get_cache_gid(uid_t uid) {
1446 int32_t gid = multiuser_get_cache_gid(multiuser_get_user_id(uid), multiuser_get_app_id(uid));
1447 return (gid != -1) ? gid : uid;
1448}
1449
Jooyung Han149be4a2020-01-23 12:45:10 +09001450binder::Status InstalldNativeService::fixupAppData(const std::optional<std::string>& uuid,
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001451 int32_t flags) {
1452 ENFORCE_UID(AID_SYSTEM);
1453 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001454
1455 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001456 for (auto userId : get_known_users(uuid_)) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001457 LOCK_USER();
Zim23457d02022-08-17 12:57:41 +01001458 atrace_pm_begin("fixup user");
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001459 FTS* fts;
1460 FTSENT* p;
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001461 auto ce_path = create_data_user_ce_path(uuid_, userId);
1462 auto de_path = create_data_user_de_path(uuid_, userId);
Jeff Sharkeyd9ff77f2017-04-14 18:54:49 -06001463 char *argv[] = { (char*) ce_path.c_str(), (char*) de_path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07001464 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001465 return error("Failed to fts_open");
1466 }
1467 while ((p = fts_read(fts)) != nullptr) {
1468 if (p->fts_info == FTS_D && p->fts_level == 1) {
1469 // Track down inodes of cache directories
1470 uint64_t raw = 0;
1471 ino_t inode_cache = 0;
1472 ino_t inode_code_cache = 0;
1473 if (getxattr(p->fts_path, kXattrInodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1474 inode_cache = raw;
1475 }
1476 if (getxattr(p->fts_path, kXattrInodeCodeCache, &raw, sizeof(raw)) == sizeof(raw)) {
1477 inode_code_cache = raw;
1478 }
1479
1480 // Figure out expected GID of each child
1481 FTSENT* child = fts_children(fts, 0);
1482 while (child != nullptr) {
1483 if ((child->fts_statp->st_ino == inode_cache)
1484 || (child->fts_statp->st_ino == inode_code_cache)
1485 || !strcmp(child->fts_name, "cache")
1486 || !strcmp(child->fts_name, "code_cache")) {
1487 child->fts_number = get_cache_gid(p->fts_statp->st_uid);
1488 } else {
1489 child->fts_number = p->fts_statp->st_uid;
1490 }
1491 child = child->fts_link;
1492 }
1493 } else if (p->fts_level >= 2) {
1494 if (p->fts_level > 2) {
1495 // Inherit GID from parent once we're deeper into tree
1496 p->fts_number = p->fts_parent->fts_number;
1497 }
1498
1499 uid_t uid = p->fts_parent->fts_statp->st_uid;
1500 gid_t cache_gid = get_cache_gid(uid);
1501 gid_t expected = p->fts_number;
1502 gid_t actual = p->fts_statp->st_gid;
1503 if (actual == expected) {
1504#if FIXUP_DEBUG
1505 LOG(DEBUG) << "Ignoring " << p->fts_path << " with expected GID " << expected;
1506#endif
1507 if (!(flags & FLAG_FORCE)) {
1508 fts_set(fts, p, FTS_SKIP);
1509 }
1510 } else if ((actual == uid) || (actual == cache_gid)) {
1511 // Only consider fixing up when current GID belongs to app
1512 if (p->fts_info != FTS_D) {
1513 LOG(INFO) << "Fixing " << p->fts_path << " with unexpected GID " << actual
1514 << " instead of " << expected;
1515 }
1516 switch (p->fts_info) {
1517 case FTS_DP:
1518 // If we're moving towards cache GID, we need to set S_ISGID
1519 if (expected == cache_gid) {
1520 if (chmod(p->fts_path, 02771) != 0) {
1521 PLOG(WARNING) << "Failed to chmod " << p->fts_path;
1522 }
1523 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07001524 [[fallthrough]]; // also set GID
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001525 case FTS_F:
1526 if (chown(p->fts_path, -1, expected) != 0) {
1527 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1528 }
1529 break;
1530 case FTS_SL:
1531 case FTS_SLNONE:
1532 if (lchown(p->fts_path, -1, expected) != 0) {
1533 PLOG(WARNING) << "Failed to chown " << p->fts_path;
1534 }
1535 break;
1536 }
1537 } else {
1538 // Ignore all other GID transitions, since they're kinda shady
1539 LOG(WARNING) << "Ignoring " << p->fts_path << " with unexpected GID " << actual
1540 << " instead of " << expected;
Jeff Sharkey6b63b912017-09-21 15:41:37 -06001541 if (!(flags & FLAG_FORCE)) {
1542 fts_set(fts, p, FTS_SKIP);
1543 }
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001544 }
1545 }
1546 }
1547 fts_close(fts);
Zim23457d02022-08-17 12:57:41 +01001548 atrace_pm_end();
Jeff Sharkeye12d5962017-04-03 16:41:02 -06001549 }
1550 return ok();
1551}
1552
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001553static int32_t copy_directory_recursive(const char* from, const char* to) {
Dario Freni918beeb2021-12-22 01:00:01 +00001554 char* argv[] =
1555 {(char*)kCpPath,
1556 (char*)"-F", /* delete any existing destination file first (--remove-destination) */
1557 (char*)"--preserve=mode,ownership,timestamps,xattr", /* preserve properties */
1558 (char*)"-R", /* recurse into subdirectories (DEST must be a directory) */
1559 (char*)"-P", /* Do not follow symlinks [default] */
1560 (char*)"-d", /* don't dereference symlinks */
1561 (char*)from,
1562 (char*)to};
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001563
1564 LOG(DEBUG) << "Copying " << from << " to " << to;
Tom Cherrye79cde52019-09-25 16:51:56 -07001565 return logwrap_fork_execvp(ARRAY_SIZE(argv), argv, nullptr, false, LOG_ALOG, false, nullptr);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001566}
1567
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001568binder::Status InstalldNativeService::snapshotAppData(const std::optional<std::string>& volumeUuid,
1569 const std::string& packageName,
1570 int32_t userId, int32_t snapshotId,
1571 int32_t storageFlags, int64_t* _aidl_return) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001572 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001573 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001574 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001575 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001576 LOCK_PACKAGE_USER();
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001577
1578 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1579 const char* package_name = packageName.c_str();
1580
1581 binder::Status res = ok();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001582 // Default result to 0, it will be populated with inode of ce data snapshot
1583 // if FLAG_STORAGE_CE has been passed.
1584 if (_aidl_return != nullptr) *_aidl_return = 0;
1585
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001586 bool clear_ce_on_exit = false;
1587 bool clear_de_on_exit = false;
1588
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001589 auto deleter = [&clear_ce_on_exit, &clear_de_on_exit, &volume_uuid, &userId, &package_name,
1590 &snapshotId] {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001591 if (clear_de_on_exit) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001592 auto to = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1593 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001594 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1595 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1596 }
1597 }
1598
1599 if (clear_ce_on_exit) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001600 auto to = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1601 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001602 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1603 LOG(WARNING) << "Failed to delete app data snapshot: " << to;
1604 }
1605 }
1606 };
1607
1608 auto scope_guard = android::base::make_scope_guard(deleter);
1609
JW Wang1d643c72020-10-06 13:42:41 +08001610 if (storageFlags & FLAG_STORAGE_DE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001611 auto from = create_data_user_de_package_path(volume_uuid, userId, package_name);
1612 auto to = create_data_misc_de_rollback_path(volume_uuid, userId, snapshotId);
1613 auto rollback_package_path =
1614 create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1615 package_name);
JW Wang1d643c72020-10-06 13:42:41 +08001616
1617 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1618 if (rc != 0) {
1619 return error(rc, "Failed to create folder " + to);
1620 }
1621
1622 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1623 if (rc != 0) {
1624 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1625 }
1626
1627 // Check if we have data to copy.
1628 if (access(from.c_str(), F_OK) == 0) {
1629 rc = copy_directory_recursive(from.c_str(), to.c_str());
1630 }
1631 if (rc != 0) {
1632 res = error(rc, "Failed copying " + from + " to " + to);
1633 clear_de_on_exit = true;
1634 return res;
1635 }
1636 }
1637
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001638 // 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 -08001639 auto from_ce = create_data_user_ce_package_path(volume_uuid, userId, package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001640 if (access(from_ce.c_str(), F_OK) != 0) {
1641 LOG(INFO) << "Missing source " << from_ce;
1642 return ok();
1643 }
1644
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001645 // ce_data_inode is not needed when FLAG_CLEAR_CACHE_ONLY is set.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001646 binder::Status clear_cache_result =
1647 clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CACHE_ONLY, 0);
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001648 if (!clear_cache_result.isOk()) {
1649 // It should be fine to continue snapshot if we for some reason failed
1650 // to clear cache.
1651 LOG(WARNING) << "Failed to clear cache of app " << packageName;
1652 }
1653
1654 // ce_data_inode is not needed when FLAG_CLEAR_CODE_CACHE_ONLY is set.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001655 binder::Status clear_code_cache_result =
1656 clearAppData(volumeUuid, packageName, userId, storageFlags | FLAG_CLEAR_CODE_CACHE_ONLY,
1657 0);
Nikita Ioffe900b3c22019-01-23 14:32:48 +00001658 if (!clear_code_cache_result.isOk()) {
1659 // It should be fine to continue snapshot if we for some reason failed
1660 // to clear code_cache.
1661 LOG(WARNING) << "Failed to clear code_cache of app " << packageName;
1662 }
1663
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001664 if (storageFlags & FLAG_STORAGE_CE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001665 auto from = create_data_user_ce_package_path(volume_uuid, userId, package_name);
1666 auto to = create_data_misc_ce_rollback_path(volume_uuid, userId, snapshotId);
1667 auto rollback_package_path =
1668 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1669 package_name);
Nikita Ioffe835ae772019-01-23 16:32:13 +00001670
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001671 int rc = create_dir_if_needed(to.c_str(), kRollbackFolderMode);
1672 if (rc != 0) {
1673 return error(rc, "Failed to create folder " + to);
Nikita Ioffe835ae772019-01-23 16:32:13 +00001674 }
1675
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001676 rc = delete_dir_contents(rollback_package_path, true /* ignore_if_missing */);
1677 if (rc != 0) {
1678 return error(rc, "Failed clearing existing snapshot " + rollback_package_path);
1679 }
1680
1681 rc = copy_directory_recursive(from.c_str(), to.c_str());
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001682 if (rc != 0) {
1683 res = error(rc, "Failed copying " + from + " to " + to);
1684 clear_ce_on_exit = true;
1685 return res;
1686 }
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001687 if (_aidl_return != nullptr) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001688 auto ce_snapshot_path =
1689 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1690 package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001691 rc = get_path_inode(ce_snapshot_path, reinterpret_cast<ino_t*>(_aidl_return));
1692 if (rc != 0) {
1693 res = error(rc, "Failed to get_path_inode for " + ce_snapshot_path);
1694 clear_ce_on_exit = true;
1695 return res;
1696 }
1697 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001698 }
1699
1700 return res;
1701}
1702
1703binder::Status InstalldNativeService::restoreAppDataSnapshot(
Jooyung Han149be4a2020-01-23 12:45:10 +09001704 const std::optional<std::string>& volumeUuid, const std::string& packageName,
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001705 const int32_t appId, const std::string& seInfo, const int32_t userId,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001706 const int32_t snapshotId, int32_t storageFlags) {
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001707 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001708 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001709 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001710 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001711 LOCK_PACKAGE_USER();
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001712
1713 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1714 const char* package_name = packageName.c_str();
1715
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001716 auto from_ce = create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1717 package_name);
1718 auto from_de = create_data_misc_de_rollback_package_path(volume_uuid, userId, snapshotId,
1719 package_name);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001720
1721 const bool needs_ce_rollback = (storageFlags & FLAG_STORAGE_CE) &&
1722 (access(from_ce.c_str(), F_OK) == 0);
1723 const bool needs_de_rollback = (storageFlags & FLAG_STORAGE_DE) &&
1724 (access(from_de.c_str(), F_OK) == 0);
1725
1726 if (!needs_ce_rollback && !needs_de_rollback) {
1727 return ok();
1728 }
1729
1730 // We know we're going to rollback one of the CE or DE data, so we clear
1731 // application data first. Note that it's possible that we're asked to
1732 // restore both CE & DE data but that one of the restores fail. Leaving the
1733 // app with no data in those cases is arguably better than leaving the app
1734 // with mismatched / stale data.
1735 LOG(INFO) << "Clearing app data for " << packageName << " to restore snapshot.";
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001736 // It's fine to pass 0 as ceDataInode here, because restoreAppDataSnapshot
1737 // can only be called when user unlocks the phone, meaning that CE user data
1738 // is decrypted.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001739 binder::Status res =
1740 clearAppData(volumeUuid, packageName, userId, storageFlags, 0 /* ceDataInode */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001741 if (!res.isOk()) {
1742 return res;
1743 }
1744
1745 if (needs_ce_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001746 auto to_ce = create_data_user_ce_path(volume_uuid, userId);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001747 int rc = copy_directory_recursive(from_ce.c_str(), to_ce.c_str());
1748 if (rc != 0) {
1749 res = error(rc, "Failed copying " + from_ce + " to " + to_ce);
1750 return res;
1751 }
JW Wangfda19ec2020-05-18 16:54:08 +08001752 delete_dir_contents_and_dir(from_ce, true /* ignore_if_missing */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001753 }
1754
1755 if (needs_de_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001756 auto to_de = create_data_user_de_path(volume_uuid, userId);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001757 int rc = copy_directory_recursive(from_de.c_str(), to_de.c_str());
1758 if (rc != 0) {
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001759 if (needs_ce_rollback) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001760 auto ce_data = create_data_user_ce_package_path(volume_uuid, userId, package_name);
Nikita Ioffefd2ccd42019-01-25 11:44:36 +00001761 LOG(WARNING) << "de_data rollback failed. Erasing rolled back ce_data " << ce_data;
1762 if (delete_dir_contents(ce_data.c_str(), 1, nullptr) != 0) {
1763 LOG(WARNING) << "Failed to delete rolled back ce_data " << ce_data;
1764 }
1765 }
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001766 res = error(rc, "Failed copying " + from_de + " to " + to_de);
1767 return res;
1768 }
JW Wangfda19ec2020-05-18 16:54:08 +08001769 delete_dir_contents_and_dir(from_de, true /* ignore_if_missing */);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001770 }
1771
1772 // Finally, restore the SELinux label on the app data.
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001773 return restoreconAppData(volumeUuid, packageName, userId, storageFlags, appId, seInfo);
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001774}
1775
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001776binder::Status InstalldNativeService::destroyAppDataSnapshot(
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001777 const std::optional<std::string>& volumeUuid, const std::string& packageName,
1778 const int32_t userId, const int64_t ceSnapshotInode, const int32_t snapshotId,
Nikita Ioffeb68f0d12019-02-04 11:06:37 +00001779 int32_t storageFlags) {
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001780 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001781 ENFORCE_VALID_USER(userId);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001782 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
1783 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001784 LOCK_PACKAGE_USER();
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001785
1786 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1787 const char* package_name = packageName.c_str();
1788
1789 if (storageFlags & FLAG_STORAGE_DE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001790 auto de_snapshot_path = create_data_misc_de_rollback_package_path(volume_uuid, userId,
1791 snapshotId, package_name);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001792
1793 int res = delete_dir_contents_and_dir(de_snapshot_path, true /* ignore_if_missing */);
1794 if (res != 0) {
1795 return error(res, "Failed clearing snapshot " + de_snapshot_path);
1796 }
1797 }
1798
1799 if (storageFlags & FLAG_STORAGE_CE) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001800 auto ce_snapshot_path =
1801 create_data_misc_ce_rollback_package_path(volume_uuid, userId, snapshotId,
1802 package_name, ceSnapshotInode);
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001803 int res = delete_dir_contents_and_dir(ce_snapshot_path, true /* ignore_if_missing */);
1804 if (res != 0) {
1805 return error(res, "Failed clearing snapshot " + ce_snapshot_path);
1806 }
1807 }
1808 return ok();
1809}
1810
Oli Lanc7789572020-03-16 18:18:41 +00001811binder::Status InstalldNativeService::destroyCeSnapshotsNotSpecified(
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001812 const std::optional<std::string>& volumeUuid, const int32_t userId,
Oli Lanc7789572020-03-16 18:18:41 +00001813 const std::vector<int32_t>& retainSnapshotIds) {
1814 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00001815 ENFORCE_VALID_USER(userId);
Oli Lanc7789572020-03-16 18:18:41 +00001816 CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001817 LOCK_USER();
Oli Lanc7789572020-03-16 18:18:41 +00001818
1819 const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
1820
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001821 auto base_path = create_data_misc_ce_rollback_base_path(volume_uuid, userId);
Oli Lanc7789572020-03-16 18:18:41 +00001822
1823 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(base_path.c_str()), closedir);
1824 if (!dir) {
1825 return error(-1, "Failed to open rollback base dir " + base_path);
1826 }
1827
1828 struct dirent* ent;
1829 while ((ent = readdir(dir.get()))) {
1830 if (ent->d_type != DT_DIR) {
1831 continue;
1832 }
1833
1834 uint snapshot_id;
1835 bool parse_ok = ParseUint(ent->d_name, &snapshot_id);
1836 if (parse_ok &&
1837 std::find(retainSnapshotIds.begin(), retainSnapshotIds.end(),
1838 snapshot_id) == retainSnapshotIds.end()) {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001839 auto rollback_path =
1840 create_data_misc_ce_rollback_path(volume_uuid, userId, snapshot_id);
Oli Lanc7789572020-03-16 18:18:41 +00001841 int res = delete_dir_contents_and_dir(rollback_path, true /* ignore_if_missing */);
1842 if (res != 0) {
1843 return error(res, "Failed clearing snapshot " + rollback_path);
1844 }
1845 }
1846 }
1847 return ok();
1848}
Nikita Ioffe77be2ed2019-01-25 13:54:43 +00001849
Jooyung Han149be4a2020-01-23 12:45:10 +09001850binder::Status InstalldNativeService::moveCompleteApp(const std::optional<std::string>& fromUuid,
1851 const std::optional<std::string>& toUuid, const std::string& packageName,
Songchun Fandc2083f2020-02-18 17:45:46 -08001852 int32_t appId, const std::string& seInfo,
Songchun Fanaed33372020-02-05 12:02:22 -08001853 int32_t targetSdkVersion, const std::string& fromCodePath) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001854 ENFORCE_UID(AID_SYSTEM);
1855 CHECK_ARGUMENT_UUID(fromUuid);
1856 CHECK_ARGUMENT_UUID(toUuid);
1857 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001858 LOCK_PACKAGE();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001859
1860 const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
1861 const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
1862 const char* package_name = packageName.c_str();
Jeff Sharkey0274c972016-12-06 09:32:04 -07001863
Jeff Sharkey423e7462016-12-09 18:18:43 -07001864 binder::Status res = ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001865 std::vector<userid_t> users = get_known_users(from_uuid);
1866
Songchun Fandc2083f2020-02-18 17:45:46 -08001867 auto to_app_package_path_parent = create_data_app_path(to_uuid);
1868 auto to_app_package_path = StringPrintf("%s/%s", to_app_package_path_parent.c_str(),
1869 android::base::Basename(fromCodePath).c_str());
1870
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001871 // Copy app
1872 {
Songchun Fandc2083f2020-02-18 17:45:46 -08001873 int rc = copy_directory_recursive(fromCodePath.c_str(), to_app_package_path_parent.c_str());
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001874 if (rc != 0) {
Songchun Fandc2083f2020-02-18 17:45:46 -08001875 res = error(rc, "Failed copying " + fromCodePath + " to " + to_app_package_path);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001876 goto fail;
1877 }
1878
Songchun Fandc2083f2020-02-18 17:45:46 -08001879 if (selinux_android_restorecon(to_app_package_path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
1880 res = error("Failed to restorecon " + to_app_package_path);
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001881 goto fail;
1882 }
1883 }
1884
1885 // Copy private data for all known users
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001886 for (auto userId : users) {
1887 LOCK_USER();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001888
1889 // Data source may not exist for all users; that's okay
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001890 auto from_ce = create_data_user_ce_package_path(from_uuid, userId, package_name);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001891 if (access(from_ce.c_str(), F_OK) != 0) {
1892 LOG(INFO) << "Missing source " << from_ce;
Jeff Sharkeye3637242015-04-08 20:56:42 -07001893 continue;
1894 }
1895
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001896 if (!createAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
Songchun Fancb567f92023-09-11 17:04:47 +00001897 appId, /* previousAppId */ -1, seInfo, targetSdkVersion, nullptr,
1898 nullptr)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001899 .isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001900 res = error("Failed to create package target");
Jeff Sharkeye3637242015-04-08 20:56:42 -07001901 goto fail;
1902 }
Jeff Sharkey51c94492016-05-10 17:46:39 -06001903 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001904 auto from = create_data_user_de_package_path(from_uuid, userId, package_name);
1905 auto to = create_data_user_de_path(to_uuid, userId);
Jeff Sharkeye3637242015-04-08 20:56:42 -07001906
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001907 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001908 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001909 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001910 goto fail;
1911 }
1912 }
1913 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001914 auto from = create_data_user_ce_package_path(from_uuid, userId, package_name);
1915 auto to = create_data_user_ce_path(to_uuid, userId);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001916
Narayan Kamathe63ca7d2019-01-14 15:21:52 +00001917 int rc = copy_directory_recursive(from.c_str(), to.c_str());
Jeff Sharkey51c94492016-05-10 17:46:39 -06001918 if (rc != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001919 res = error(rc, "Failed copying " + from + " to " + to);
Jeff Sharkey51c94492016-05-10 17:46:39 -06001920 goto fail;
1921 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001922 }
1923
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08001924 if (!restoreconAppDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1925 appId, seInfo)
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001926 .isOk()) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07001927 res = error("Failed to restorecon");
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07001928 goto fail;
1929 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001930 }
1931
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001932 // Copy sdk data for all known users
1933 for (auto userId : users) {
1934 LOCK_USER();
1935
1936 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1937 for (int currentFlag : storageFlags) {
1938 const bool isCeData = currentFlag == FLAG_STORAGE_CE;
1939
1940 const auto from = create_data_misc_sdk_sandbox_package_path(from_uuid, isCeData, userId,
1941 package_name);
1942 if (access(from.c_str(), F_OK) != 0) {
1943 LOG(INFO) << "Missing source " << from;
1944 continue;
1945 }
1946 const auto to = create_data_misc_sdk_sandbox_path(to_uuid, isCeData, userId);
1947
1948 const int rc = copy_directory_recursive(from.c_str(), to.c_str());
1949 if (rc != 0) {
1950 res = error(rc, "Failed copying " + from + " to " + to);
1951 goto fail;
1952 }
1953 }
1954
1955 if (!restoreconSdkDataLocked(toUuid, packageName, userId, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
1956 appId, seInfo)
1957 .isOk()) {
1958 res = error("Failed to restorecon");
1959 goto fail;
1960 }
1961 }
Jeff Sharkey31f08982015-07-07 13:31:37 -07001962 // We let the framework scan the new location and persist that before
1963 // deleting the data in the old location; this ordering ensures that
1964 // we can recover from things like battery pulls.
Jeff Sharkey423e7462016-12-09 18:18:43 -07001965 return ok();
Jeff Sharkeye3637242015-04-08 20:56:42 -07001966
1967fail:
1968 // Nuke everything we might have already copied
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001969 {
Songchun Fandc2083f2020-02-18 17:45:46 -08001970 if (delete_dir_contents(to_app_package_path.c_str(), 1, nullptr) != 0) {
1971 LOG(WARNING) << "Failed to rollback " << to_app_package_path;
Jeff Sharkeyd7921182015-04-30 15:58:19 -07001972 }
1973 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001974 for (auto userId : users) {
1975 LOCK_USER();
Jeff Sharkey51c94492016-05-10 17:46:39 -06001976 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001977 auto to = create_data_user_de_package_path(to_uuid, userId, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001978 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001979 LOG(WARNING) << "Failed to rollback " << to;
1980 }
1981 }
1982 {
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08001983 auto to = create_data_user_ce_package_path(to_uuid, userId, package_name);
Yi Konge7bf3772018-07-17 16:16:24 -07001984 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
Jeff Sharkey51c94492016-05-10 17:46:39 -06001985 LOG(WARNING) << "Failed to rollback " << to;
1986 }
Jeff Sharkeye3637242015-04-08 20:56:42 -07001987 }
1988 }
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00001989 for (auto userId : users) {
1990 LOCK_USER();
1991 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
1992 for (int currentFlag : storageFlags) {
1993 const bool isCeData = currentFlag == FLAG_STORAGE_CE;
1994 const auto to = create_data_misc_sdk_sandbox_package_path(to_uuid, isCeData, userId,
1995 package_name);
1996 if (delete_dir_contents(to.c_str(), 1, nullptr) != 0) {
1997 LOG(WARNING) << "Failed to rollback " << to;
1998 }
1999 }
2000 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002001 return res;
Jeff Sharkeye3637242015-04-08 20:56:42 -07002002}
2003
Jooyung Han149be4a2020-01-23 12:45:10 +09002004binder::Status InstalldNativeService::createUserData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002005 int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
2006 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002007 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002008 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002009 LOCK_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07002010
Alex Buynytskyya203d712023-06-08 12:56:15 -07002011 ScopedTrace tracer("create-user-data");
2012
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002013 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey379a12b2016-04-14 20:45:06 -06002014 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002015 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002016 if (ensure_config_user_dirs(userId) != 0) {
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07002017 return error(StringPrintf("Failed to ensure dirs for %d", userId));
Jeff Sharkey423e7462016-12-09 18:18:43 -07002018 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002019 }
2020 }
Jeff Sharkeye59c85c2017-04-02 21:53:14 -06002021
Jeff Sharkey7be5ead2016-12-12 13:18:46 -07002022 return ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002023}
2024
Jooyung Han149be4a2020-01-23 12:45:10 +09002025binder::Status InstalldNativeService::destroyUserData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002026 int32_t userId, int32_t flags) {
2027 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002028 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002029 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002030 LOCK_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07002031
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002032 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey423e7462016-12-09 18:18:43 -07002033 binder::Status res = ok();
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002034 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002035 auto path = create_data_user_de_path(uuid_, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00002036 // Contents only, as vold is responsible for the user_de dir itself.
2037 if (delete_dir_contents(path, true) != 0) {
2038 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002039 }
Rishabh Singh8d784372022-03-09 15:54:46 +00002040 auto sdk_sandbox_de_path =
2041 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
2042 if (delete_dir_contents_and_dir(sdk_sandbox_de_path, true) != 0) {
2043 res = error("Failed to delete " + sdk_sandbox_de_path);
2044 }
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07002045 if (uuid_ == nullptr) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002046 path = create_data_misc_legacy_path(userId);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08002047 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002048 res = error("Failed to delete " + path);
2049 }
Calin Juravle114f0812017-03-08 19:05:07 -08002050 path = create_primary_cur_profile_dir_path(userId);
Alex Buynytskyy5cb25262022-02-15 08:59:36 -08002051 if (delete_dir_contents_and_dir(path, true) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002052 res = error("Failed to delete " + path);
2053 }
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002054 }
Robin Lee095c7632014-04-25 15:05:19 +01002055 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06002056 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002057 auto path = create_data_user_ce_path(uuid_, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00002058 // Contents only, as vold is responsible for the user_ce dir itself.
2059 if (delete_dir_contents(path, true) != 0) {
2060 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002061 }
Rishabh Singh8d784372022-03-09 15:54:46 +00002062 auto sdk_sandbox_ce_path =
2063 create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2064 if (delete_dir_contents_and_dir(sdk_sandbox_ce_path, true) != 0) {
2065 res = error("Failed to delete " + sdk_sandbox_ce_path);
2066 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002067 path = findDataMediaPath(uuid, userId);
Eric Biggersc3d9dce2022-04-28 04:42:45 +00002068 // Contents only, as vold is responsible for the media dir itself.
2069 if (delete_dir_contents(path, true) != 0) {
2070 res = error("Failed to delete contents of " + path);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002071 }
Jeff Sharkey379a12b2016-04-14 20:45:06 -06002072 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07002073 return res;
Robin Lee095c7632014-04-25 15:05:19 +01002074}
2075
Jooyung Han149be4a2020-01-23 12:45:10 +09002076binder::Status InstalldNativeService::freeCache(const std::optional<std::string>& uuid,
Neharika Jali0e542312021-10-25 06:41:24 +00002077 int64_t targetFreeBytes, int32_t flags) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002078 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002079 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002080#ifndef GRANULAR_LOCKS
2081 std::lock_guard lock(mLock);
2082#endif // !GRANULAR_LOCKS
Jeff Sharkey423e7462016-12-09 18:18:43 -07002083
Jooyung Han149be4a2020-01-23 12:45:10 +09002084 auto uuidString = uuid.value_or("");
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002085 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002086 auto data_path = create_data_path(uuid_);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002087 auto noop = (flags & FLAG_FREE_CACHE_NOOP);
Neharika Jali1d667a22021-10-25 19:36:18 +00002088 auto defy_target = (flags & FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07002089
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002090 int64_t free = data_disk_free(data_path);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002091 if (free < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002092 return error("Failed to determine free space for " + data_path);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002093 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002094
Jeff Sharkey60f8a532017-05-30 14:38:42 -06002095 int64_t needed = targetFreeBytes - free;
Neharika Jali1d667a22021-10-25 19:36:18 +00002096 if (!defy_target) {
2097 LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
2098 << targetFreeBytes << "; needed " << needed;
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002099
Neharika Jali1d667a22021-10-25 19:36:18 +00002100 if (free >= targetFreeBytes) {
2101 return ok();
2102 }
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002103 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002104
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002105 if (flags & FLAG_FREE_CACHE_V2) {
2106 // This new cache strategy fairly removes files from UIDs by deleting
2107 // files from the UIDs which are most over their allocated quota
2108
2109 // 1. Create trackers for every known UID
Zim23457d02022-08-17 12:57:41 +01002110 atrace_pm_begin("create");
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002111 const auto users = get_known_users(uuid_);
2112#ifdef GRANULAR_LOCKS
2113 std::vector<UserLock> userLocks;
2114 userLocks.reserve(users.size());
2115 std::vector<UserWriteLockGuard> lockGuards;
2116 lockGuards.reserve(users.size());
2117#endif // GRANULAR_LOCKS
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002118 std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08002119 for (auto userId : users) {
2120#ifdef GRANULAR_LOCKS
2121 userLocks.emplace_back(userId, mUserIdLock, mLock);
2122 lockGuards.emplace_back(userLocks.back());
2123#endif // GRANULAR_LOCKS
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002124 FTS *fts;
2125 FTSENT *p;
Samiul Islama2198092022-05-07 23:22:45 +01002126
2127 // Create a list of data paths whose children have cache directories
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08002128 auto ce_path = create_data_user_ce_path(uuid_, userId);
2129 auto de_path = create_data_user_de_path(uuid_, userId);
2130 auto media_path = findDataMediaPath(uuid, userId) + "/Android/data/";
Samiul Islama2198092022-05-07 23:22:45 +01002131 auto ce_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/true, userId);
2132 auto de_sdk_path = create_data_misc_sdk_sandbox_path(uuid_, /*isCeData=*/false, userId);
2133
2134 std::vector<std::string> dataPaths = {ce_path, de_path, media_path};
2135 foreach_subdir(ce_sdk_path, [&ce_sdk_path, &dataPaths](const std::string subDir) {
2136 const auto fullpath = ce_sdk_path + "/" + subDir;
2137 dataPaths.push_back(fullpath);
2138 });
2139 foreach_subdir(de_sdk_path, [&de_sdk_path, &dataPaths](const std::string subDir) {
2140 const auto fullpath = de_sdk_path + "/" + subDir;
2141 dataPaths.push_back((char*)fullpath.c_str());
2142 });
2143
2144 char* argv[dataPaths.size() + 1];
2145 for (unsigned int i = 0; i < dataPaths.size(); i++) {
2146 argv[i] = (char*)dataPaths[i].c_str();
2147 }
2148 argv[dataPaths.size()] = nullptr;
2149
Yi Konge7bf3772018-07-17 16:16:24 -07002150 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002151 return error("Failed to fts_open");
2152 }
Yi Konge7bf3772018-07-17 16:16:24 -07002153 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002154 if (p->fts_info == FTS_D && p->fts_level == 1) {
2155 uid_t uid = p->fts_statp->st_uid;
Samiul Islama2198092022-05-07 23:22:45 +01002156
2157 // If uid belongs to sdk sandbox, then the cache should be attributed to the
2158 // original client app.
2159 const auto client_uid = multiuser_convert_sdk_sandbox_to_app_uid(uid);
2160 const bool isSandboxUid = (client_uid != (uid_t)-1);
2161 if (isSandboxUid) uid = client_uid;
2162
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002163 if (multiuser_get_app_id(uid) == AID_MEDIA_RW) {
2164 uid = (multiuser_get_app_id(p->fts_statp->st_gid) - AID_EXT_GID_START)
2165 + AID_APP_START;
2166 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002167 auto search = trackers.find(uid);
2168 if (search != trackers.end()) {
2169 search->second->addDataPath(p->fts_path);
2170 } else {
2171 auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
Risan5f308262018-10-26 12:06:58 -06002172 multiuser_get_user_id(uid), multiuser_get_app_id(uid), uuidString));
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002173 tracker->addDataPath(p->fts_path);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002174 {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06002175 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002176 tracker->cacheQuota = mCacheQuotas[uid];
2177 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002178 if (tracker->cacheQuota == 0) {
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002179#if MEASURE_DEBUG
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002180 LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
Jeff Sharkeyed909ae2017-03-22 21:27:40 -06002181#endif
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002182 tracker->cacheQuota = 67108864;
2183 }
2184 trackers[uid] = tracker;
2185 }
2186 fts_set(fts, p, FTS_SKIP);
2187 }
2188 }
2189 fts_close(fts);
2190 }
Zim23457d02022-08-17 12:57:41 +01002191 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002192
2193 // 2. Populate tracker stats and insert into priority queue
Zim23457d02022-08-17 12:57:41 +01002194 atrace_pm_begin("populate");
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002195 auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
2196 return (left->getCacheRatio() < right->getCacheRatio());
2197 };
2198 std::priority_queue<std::shared_ptr<CacheTracker>,
2199 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
2200 for (const auto& it : trackers) {
2201 it.second->loadStats();
2202 queue.push(it.second);
2203 }
Zim23457d02022-08-17 12:57:41 +01002204 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002205
2206 // 3. Bounce across the queue, freeing items from whichever tracker is
2207 // the most over their assigned quota
Zim23457d02022-08-17 12:57:41 +01002208 atrace_pm_begin("bounce");
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002209 std::shared_ptr<CacheTracker> active;
2210 while (active || !queue.empty()) {
Jeff Sharkey871a8f22017-02-21 18:30:28 -07002211 // Only look at apps under quota when explicitly requested
2212 if (active && (active->getCacheRatio() < 10000)
2213 && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
2214 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
2215 << " isn't over quota, and defy not requested";
2216 break;
2217 }
2218
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002219 // Find the best tracker to work with; this might involve swapping
2220 // if the active tracker is no longer the most over quota
2221 bool nextBetter = active && !queue.empty()
2222 && active->getCacheRatio() < queue.top()->getCacheRatio();
2223 if (!active || nextBetter) {
2224 if (active) {
2225 // Current tracker still has items, so we'll consider it
2226 // again later once it bubbles up to surface
2227 queue.push(active);
2228 }
2229 active = queue.top(); queue.pop();
2230 active->ensureItems();
2231 continue;
2232 }
2233
2234 // If no items remain, go find another tracker
2235 if (active->items.empty()) {
2236 active = nullptr;
2237 continue;
2238 } else {
2239 auto item = active->items.back();
2240 active->items.pop_back();
2241
2242 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
2243 if (!noop) {
2244 item->purge();
2245 }
2246 active->cacheUsed -= item->size;
2247 needed -= item->size;
2248 }
2249
Neharika Jali1d667a22021-10-25 19:36:18 +00002250 if (!defy_target) {
2251 // Verify that we're actually done before bailing, since sneaky
2252 // apps might be using hardlinks
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002253 if (needed <= 0) {
Neharika Jali1d667a22021-10-25 19:36:18 +00002254 free = data_disk_free(data_path);
2255 needed = targetFreeBytes - free;
2256 if (needed <= 0) {
2257 break;
2258 } else {
2259 LOG(WARNING) << "Expected to be done but still need " << needed;
2260 }
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002261 }
2262 }
2263 }
Zim23457d02022-08-17 12:57:41 +01002264 atrace_pm_end();
Jeff Sharkey88ddd942017-01-17 18:05:54 -07002265
2266 } else {
Jeff Sharkey1cb4aaf2017-03-27 16:41:06 -06002267 return error("Legacy cache logic no longer supported");
Mike Lockwood94afecf2012-10-24 10:45:23 -07002268 }
2269
Neharika Jali1d667a22021-10-25 19:36:18 +00002270 if (!defy_target) {
2271 free = data_disk_free(data_path);
2272 if (free >= targetFreeBytes) {
2273 return ok();
2274 } else {
2275 return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
2276 targetFreeBytes, data_path.c_str(), free));
2277 }
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002278 } else {
Neharika Jali1d667a22021-10-25 19:36:18 +00002279 return ok();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002280 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002281}
2282
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002283binder::Status InstalldNativeService::rmdex(const std::string& codePath,
2284 const std::string& instructionSet) {
2285 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07002286 CHECK_ARGUMENT_PATH(codePath);
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07002287
Mike Lockwood94afecf2012-10-24 10:45:23 -07002288 char dex_path[PKG_PATH_MAX];
2289
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002290 const char* path = codePath.c_str();
2291 const char* instruction_set = instructionSet.c_str();
2292
Jeff Sharkey770180a2014-09-08 17:14:26 -07002293 if (validate_apk_path(path) && validate_system_app_path(path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002294 return error("Invalid path " + codePath);
Jeff Sharkey770180a2014-09-08 17:14:26 -07002295 }
2296
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002297 if (!create_cache_path(dex_path, path, instruction_set)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07002298 return error("Failed to create cache path for " + codePath);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07002299 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002300
2301 ALOGV("unlink %s\n", dex_path);
2302 if (unlink(dex_path) < 0) {
Calin Juravle249f2d32017-05-03 17:22:27 -07002303 // It's ok if we don't have a dalvik cache path. Report error only when the path exists
2304 // but could not be unlinked.
2305 if (errno != ENOENT) {
2306 return error(StringPrintf("Failed to unlink %s", dex_path));
2307 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002308 }
Calin Juravle249f2d32017-05-03 17:22:27 -07002309 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07002310}
2311
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002312struct stats {
2313 int64_t codeSize;
2314 int64_t dataSize;
2315 int64_t cacheSize;
2316};
2317
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002318#if MEASURE_DEBUG
2319static std::string toString(std::vector<int64_t> values) {
2320 std::stringstream res;
2321 res << "[";
2322 for (size_t i = 0; i < values.size(); i++) {
2323 res << values[i];
2324 if (i < values.size() - 1) {
2325 res << ",";
2326 }
2327 }
2328 res << "]";
2329 return res.str();
2330}
2331#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002332
Shikha Malhotra976ae002022-02-26 15:39:53 +00002333// On devices without sdcardfs, if internal and external are on
2334// the same volume, a uid such as u0_a123 is used for both
2335// internal and external storage; therefore, subtract that
2336// amount from internal to make sure we don't count it double.
2337// This needs to happen for data, cache and OBB
2338static void deductDoubleSpaceIfNeeded(stats* stats, int64_t doubleSpaceToBeDeleted, uid_t uid,
2339 const std::string& uuid) {
2340 if (!supports_sdcardfs()) {
2341 stats->dataSize -= doubleSpaceToBeDeleted;
2342 long obbProjectId = get_project_id(uid, PROJECT_ID_EXT_OBB_START);
2343 int64_t appObbSize = GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2344 stats->dataSize -= appObbSize;
2345 }
2346}
2347
Risan5f308262018-10-26 12:06:58 -06002348static void collectQuotaStats(const std::string& uuid, int32_t userId,
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002349 int32_t appId, struct stats* stats, struct stats* extStats) {
Shikha Malhotra976ae002022-02-26 15:39:53 +00002350 int64_t space, doubleSpaceToBeDeleted = 0;
Martijn Coenen771cc342020-02-19 23:26:56 +01002351 uid_t uid = multiuser_get_uid(userId, appId);
Shikha Malhotra976ae002022-02-26 15:39:53 +00002352 static const bool supportsProjectId = internal_storage_has_project_id();
2353
2354 if (extStats != nullptr) {
2355 space = get_occupied_app_space_external(uuid, userId, appId);
2356
2357 if (space != -1) {
2358 extStats->dataSize += space;
2359 doubleSpaceToBeDeleted += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002360 }
2361
Shikha Malhotra976ae002022-02-26 15:39:53 +00002362 space = get_occupied_app_cache_space_external(uuid, userId, appId);
2363 if (space != -1) {
2364 extStats->dataSize += space; // cache counts for "data"
2365 extStats->cacheSize += space;
2366 doubleSpaceToBeDeleted += space;
2367 }
2368 }
2369
2370 if (stats != nullptr) {
2371 if (!supportsProjectId) {
2372 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002373 stats->dataSize += space;
2374 }
Shikha Malhotra976ae002022-02-26 15:39:53 +00002375 deductDoubleSpaceIfNeeded(stats, doubleSpaceToBeDeleted, uid, uuid);
2376 int sdkSandboxUid = multiuser_get_sdk_sandbox_uid(userId, appId);
2377 if (sdkSandboxUid != -1) {
2378 if ((space = GetOccupiedSpaceForUid(uuid, sdkSandboxUid)) != -1) {
2379 stats->dataSize += space;
2380 }
2381 }
2382 int cacheGid = multiuser_get_cache_gid(userId, appId);
2383 if (cacheGid != -1) {
2384 if ((space = GetOccupiedSpaceForGid(uuid, cacheGid)) != -1) {
2385 stats->cacheSize += space;
2386 }
2387 }
2388 } else {
2389 long projectId = get_project_id(uid, PROJECT_ID_APP_START);
2390 if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
2391 stats->dataSize += space;
2392 }
2393 projectId = get_project_id(uid, PROJECT_ID_APP_CACHE_START);
2394 if ((space = GetOccupiedSpaceForProjectId(uuid, projectId)) != -1) {
Risan5f308262018-10-26 12:06:58 -06002395 stats->cacheSize += space;
Shikha Malhotra976ae002022-02-26 15:39:53 +00002396 stats->dataSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002397 }
2398 }
2399
2400 int sharedGid = multiuser_get_shared_gid(0, appId);
2401 if (sharedGid != -1) {
Risan5f308262018-10-26 12:06:58 -06002402 if ((space = GetOccupiedSpaceForGid(uuid, sharedGid)) != -1) {
2403 stats->codeSize += space;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002404 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002405 }
2406 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002407}
2408
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002409static void collectManualStats(const std::string& path, struct stats* stats) {
Mike Lockwood94afecf2012-10-24 10:45:23 -07002410 DIR *d;
2411 int dfd;
2412 struct dirent *de;
2413 struct stat s;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002414
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002415 d = opendir(path.c_str());
2416 if (d == nullptr) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002417 if (errno != ENOENT) {
2418 PLOG(WARNING) << "Failed to open " << path;
2419 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002420 return;
2421 }
2422 dfd = dirfd(d);
2423 while ((de = readdir(d))) {
2424 const char *name = de->d_name;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002425
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002426 int64_t size = 0;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002427 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002428 size = s.st_blocks * 512;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002429 }
2430
2431 if (de->d_type == DT_DIR) {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002432 if (!strcmp(name, ".")) {
2433 // Don't recurse, but still count node size
2434 } else if (!strcmp(name, "..")) {
2435 // Don't recurse or count node size
2436 continue;
Mike Lockwood94afecf2012-10-24 10:45:23 -07002437 } else {
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002438 // Measure all children nodes
2439 size = 0;
2440 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
Mike Lockwood94afecf2012-10-24 10:45:23 -07002441 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002442
2443 if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
2444 stats->cacheSize += size;
2445 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002446 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002447
2448 // Legacy symlink isn't owned by app
2449 if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
2450 continue;
2451 }
2452
2453 // Everything found inside is considered data
2454 stats->dataSize += size;
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002455 }
2456 closedir(d);
2457}
2458
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002459void collectManualStatsForSubDirectories(const std::string& path, struct stats* stats) {
2460 const auto subDirHandler = [&path, &stats](const std::string& subDir) {
2461 auto fullpath = path + "/" + subDir;
2462 collectManualStats(fullpath, stats);
2463 };
2464 foreach_subdir(path, subDirHandler);
2465}
2466
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002467static void collectManualStatsForUser(const std::string& path, struct stats* stats,
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002468 bool exclude_apps = false,
2469 bool is_sdk_sandbox_storage = false) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002470 DIR *d;
2471 int dfd;
2472 struct dirent *de;
2473 struct stat s;
2474
2475 d = opendir(path.c_str());
2476 if (d == nullptr) {
2477 if (errno != ENOENT) {
2478 PLOG(WARNING) << "Failed to open " << path;
2479 }
2480 return;
2481 }
2482 dfd = dirfd(d);
2483 while ((de = readdir(d))) {
2484 if (de->d_type == DT_DIR) {
2485 const char *name = de->d_name;
2486 if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
2487 continue;
2488 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002489 int32_t user_uid = multiuser_get_app_id(s.st_uid);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002490 if (!strcmp(name, ".") || !strcmp(name, "..")) {
2491 continue;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002492 } else if (exclude_apps && (user_uid >= AID_APP_START && user_uid <= AID_APP_END)) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002493 continue;
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002494 } else if (is_sdk_sandbox_storage) {
2495 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2496 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2497 collectManualStatsForSubDirectories(StringPrintf("%s/%s", path.c_str(), name),
2498 stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002499 } else {
2500 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
2501 }
2502 }
2503 }
2504 closedir(d);
2505}
2506
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002507static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
2508 FTS *fts;
2509 FTSENT *p;
2510 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07002511 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002512 PLOG(ERROR) << "Failed to fts_open " << path;
2513 return;
2514 }
Yi Konge7bf3772018-07-17 16:16:24 -07002515 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002516 p->fts_number = p->fts_parent->fts_number;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002517 switch (p->fts_info) {
2518 case FTS_D:
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002519 if (p->fts_level == 3
2520 && !strcmp(p->fts_parent->fts_name, "obb")
2521 && !strcmp(p->fts_parent->fts_parent->fts_name, "Android")) {
2522 p->fts_number = 1;
2523 } else if (p->fts_level == 4
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002524 && !strcmp(p->fts_name, "cache")
2525 && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
2526 && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002527 p->fts_number = 2;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002528 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07002529 [[fallthrough]]; // to count the directory
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002530 case FTS_DEFAULT:
2531 case FTS_F:
2532 case FTS_SL:
2533 case FTS_SLNONE:
2534 int64_t size = (p->fts_statp->st_blocks * 512);
2535 if (p->fts_number == 1) {
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002536 stats->codeSize += size;
2537 } else {
2538 if (p->fts_number == 2) {
2539 stats->cacheSize += size;
2540 }
2541 stats->dataSize += size;
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002542 }
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002543 break;
2544 }
2545 }
2546 fts_close(fts);
2547}
Shikha Malhotraaae96442021-11-25 10:52:50 +00002548static bool ownsExternalStorage(int32_t appId) {
Shikha Malhotra976ae002022-02-26 15:39:53 +00002549 // if project id calculation is supported then, there is no need to
2550 // calculate in a different way and project_id based calculation can work
2551 if (internal_storage_has_project_id()) {
2552 return false;
2553 }
2554
Shikha Malhotraaae96442021-11-25 10:52:50 +00002555 // Fetch external storage owner appid and check if it is the same as the
2556 // current appId whose size is calculated
2557 struct stat s;
2558 auto _picDir = StringPrintf("%s/Pictures", create_data_media_path(nullptr, 0).c_str());
2559 // check if the stat are present
2560 if (stat(_picDir.c_str(), &s) == 0) {
2561 // fetch the appId from the uid of the media app
2562 return ((int32_t)multiuser_get_app_id(s.st_uid) == appId);
2563 }
2564 return false;
2565}
Jooyung Han149be4a2020-01-23 12:45:10 +09002566binder::Status InstalldNativeService::getAppSize(const std::optional<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002567 const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
2568 int32_t appId, const std::vector<int64_t>& ceDataInodes,
2569 const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002570 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07002571 CHECK_ARGUMENT_UUID(uuid);
Alex Buynytskyya6823ef2022-02-28 14:18:19 -08002572 if (packageNames.size() != ceDataInodes.size()) {
2573 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
2574 "packageNames/ceDataInodes size mismatch.");
2575 }
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002576 for (const auto& packageName : packageNames) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002577 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
2578 }
Jeff Sharkey53594302018-02-24 18:59:39 -07002579 for (const auto& codePath : codePaths) {
2580 CHECK_ARGUMENT_PATH(codePath);
2581 }
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002582 // NOTE: Locking is relaxed on this method, since it's limited to
2583 // read-only measurements without mutation.
Jeff Sharkey423e7462016-12-09 18:18:43 -07002584
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002585 // When modifying this logic, always verify using tests:
2586 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
2587
2588#if MEASURE_DEBUG
2589 LOG(INFO) << "Measuring user " << userId << " app " << appId;
2590#endif
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07002591
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002592 // Here's a summary of the common storage locations across the platform,
2593 // and how they're each tagged:
2594 //
2595 // /data/app/com.example UID system
2596 // /data/app/com.example/oat UID system
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002597 // /data/user/0/com.example UID u0_a10 GID u0_a10
2598 // /data/user/0/com.example/cache UID u0_a10 GID u0_a10_cache
2599 // /data/media/0/foo.txt UID u0_media_rw
2600 // /data/media/0/bar.jpg UID u0_media_rw GID u0_media_image
2601 // /data/media/0/Android/data/com.example UID u0_media_rw GID u0_a10_ext
2602 // /data/media/0/Android/data/com.example/cache UID u0_media_rw GID u0_a10_ext_cache
2603 // /data/media/obb/com.example UID system
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002604
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002605 struct stats stats;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002606 struct stats extStats;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002607 memset(&stats, 0, sizeof(stats));
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002608 memset(&extStats, 0, sizeof(extStats));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002609
Jooyung Han149be4a2020-01-23 12:45:10 +09002610 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002611 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002612
Risan5f308262018-10-26 12:06:58 -06002613 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002614 flags &= ~FLAG_USE_QUOTA;
2615 }
2616
Zim23457d02022-08-17 12:57:41 +01002617 atrace_pm_begin("obb");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002618 for (const auto& packageName : packageNames) {
Jeff Sharkey6d775c52019-03-22 13:46:20 -06002619 auto obbCodePath = create_data_media_package_path(uuid_, userId,
2620 "obb", packageName.c_str());
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002621 calculate_tree_size(obbCodePath, &extStats.codeSize);
2622 }
Zim23457d02022-08-17 12:57:41 +01002623 atrace_pm_end();
Shikha Malhotraaae96442021-11-25 10:52:50 +00002624 // Calculating the app size of the external storage owning app in a manual way, since
2625 // calculating it through quota apis also includes external media storage in the app storage
2626 // numbers
2627 if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START && !ownsExternalStorage(appId)) {
Zim23457d02022-08-17 12:57:41 +01002628 atrace_pm_begin("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002629 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002630 calculate_tree_size(codePath, &stats.codeSize, -1,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002631 multiuser_get_shared_gid(0, appId));
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002632 }
Zim23457d02022-08-17 12:57:41 +01002633 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002634
Zim23457d02022-08-17 12:57:41 +01002635 atrace_pm_begin("quota");
Risan5f308262018-10-26 12:06:58 -06002636 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Zim23457d02022-08-17 12:57:41 +01002637 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002638 } else {
Zim23457d02022-08-17 12:57:41 +01002639 atrace_pm_begin("code");
Chih-Hung Hsiehcb057c22017-08-03 15:48:25 -07002640 for (const auto& codePath : codePaths) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002641 calculate_tree_size(codePath, &stats.codeSize);
2642 }
Zim23457d02022-08-17 12:57:41 +01002643 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002644
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002645 for (size_t i = 0; i < packageNames.size(); i++) {
2646 const char* pkgname = packageNames[i].c_str();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002647
Zim23457d02022-08-17 12:57:41 +01002648 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002649 auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
2650 collectManualStats(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002651 auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
2652 collectManualStats(dePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002653 atrace_pm_end();
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002654
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002655 // In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
2656 // collect individual stats of each subdirectory (shared, storage of each sdk etc.)
2657 if (appId >= AID_APP_START && appId <= AID_APP_END) {
Zim23457d02022-08-17 12:57:41 +01002658 atrace_pm_begin("sdksandbox");
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002659 auto sdkSandboxCePath =
2660 create_data_misc_sdk_sandbox_package_path(uuid_, true, userId, pkgname);
2661 collectManualStatsForSubDirectories(sdkSandboxCePath, &stats);
2662 auto sdkSandboxDePath =
2663 create_data_misc_sdk_sandbox_package_path(uuid_, false, userId, pkgname);
2664 collectManualStatsForSubDirectories(sdkSandboxDePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002665 atrace_pm_end();
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002666 }
2667
Jeff Sharkey06a61842017-04-15 12:03:31 -06002668 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002669 atrace_pm_begin("profiles");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002670 calculate_tree_size(
2671 create_primary_current_profile_package_dir_path(userId, pkgname),
2672 &stats.dataSize);
2673 calculate_tree_size(
2674 create_primary_reference_profile_package_dir_path(pkgname),
2675 &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002676 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002677 }
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002678
Zim23457d02022-08-17 12:57:41 +01002679 atrace_pm_begin("external");
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002680 auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002681 collectManualStats(extPath, &extStats);
Jeff Sharkey76ddaeb2017-01-25 22:15:42 -07002682 auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002683 calculate_tree_size(mediaPath, &extStats.dataSize);
Zim23457d02022-08-17 12:57:41 +01002684 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002685 }
2686
Jeff Sharkey06a61842017-04-15 12:03:31 -06002687 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002688 atrace_pm_begin("dalvik");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002689 int32_t sharedGid = multiuser_get_shared_gid(0, appId);
Jeff Sharkey06a61842017-04-15 12:03:31 -06002690 if (sharedGid != -1) {
2691 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2692 sharedGid, -1);
2693 }
Zim23457d02022-08-17 12:57:41 +01002694 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002695 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07002696 }
Jeff Sharkey2f720f72016-04-10 20:51:40 -06002697
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07002698 std::vector<int64_t> ret;
2699 ret.push_back(stats.codeSize);
2700 ret.push_back(stats.dataSize);
2701 ret.push_back(stats.cacheSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002702 ret.push_back(extStats.codeSize);
2703 ret.push_back(extStats.dataSize);
2704 ret.push_back(extStats.cacheSize);
2705#if MEASURE_DEBUG
2706 LOG(DEBUG) << "Final result " << toString(ret);
2707#endif
2708 *_aidl_return = ret;
2709 return ok();
2710}
2711
Martijn Coenen771cc342020-02-19 23:26:56 +01002712struct external_sizes {
2713 int64_t audioSize;
2714 int64_t videoSize;
2715 int64_t imageSize;
2716 int64_t totalSize; // excludes OBBs (Android/obb), but includes app data + cache
2717 int64_t obbSize;
2718};
2719
2720#define PER_USER_RANGE 100000
2721
2722static long getProjectIdForUser(int userId, long projectId) {
2723 return userId * PER_USER_RANGE + projectId;
2724}
2725
2726static external_sizes getExternalSizesForUserWithQuota(const std::string& uuid, int32_t userId, const std::vector<int32_t>& appIds) {
2727 struct external_sizes sizes = {};
2728 int64_t space;
2729
2730 if (supports_sdcardfs()) {
2731 uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
2732 if ((space = GetOccupiedSpaceForUid(uuid, uid)) != -1) {
2733 sizes.totalSize = space;
2734 }
2735
2736 gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
2737 if ((space = GetOccupiedSpaceForGid(uuid, audioGid)) != -1) {
2738 sizes.audioSize = space;
2739 }
2740
2741 gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
2742 if ((space = GetOccupiedSpaceForGid(uuid, videoGid)) != -1) {
2743 sizes.videoSize = space;
2744 }
2745
2746 gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
2747 if ((space = GetOccupiedSpaceForGid(uuid, imageGid)) != -1) {
2748 sizes.imageSize = space;
2749 }
2750
2751 if ((space = GetOccupiedSpaceForGid(uuid, AID_MEDIA_OBB)) != -1) {
2752 sizes.obbSize = space;
2753 }
2754 } else {
2755 int64_t totalSize = 0;
2756 long defaultProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_DEFAULT);
2757 if ((space = GetOccupiedSpaceForProjectId(uuid, defaultProjectId)) != -1) {
2758 // This is all files that are not audio/video/images, excluding
2759 // OBBs and app-private data
2760 totalSize += space;
2761 }
2762
2763 long audioProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_AUDIO);
2764 if ((space = GetOccupiedSpaceForProjectId(uuid, audioProjectId)) != -1) {
2765 sizes.audioSize = space;
2766 totalSize += space;
2767 }
2768
2769 long videoProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_VIDEO);
2770 if ((space = GetOccupiedSpaceForProjectId(uuid, videoProjectId)) != -1) {
2771 sizes.videoSize = space;
2772 totalSize += space;
2773 }
2774
2775 long imageProjectId = getProjectIdForUser(userId, PROJECT_ID_EXT_MEDIA_IMAGE);
2776 if ((space = GetOccupiedSpaceForProjectId(uuid, imageProjectId)) != -1) {
2777 sizes.imageSize = space;
2778 totalSize += space;
2779 }
2780
2781 int64_t totalAppDataSize = 0;
2782 int64_t totalAppCacheSize = 0;
2783 int64_t totalAppObbSize = 0;
2784 for (auto appId : appIds) {
2785 if (appId >= AID_APP_START) {
2786 // App data
2787 uid_t uid = multiuser_get_uid(userId, appId);
2788 long projectId = uid - AID_APP_START + PROJECT_ID_EXT_DATA_START;
2789 totalAppDataSize += GetOccupiedSpaceForProjectId(uuid, projectId);
2790
2791 // App cache
2792 long cacheProjectId = uid - AID_APP_START + PROJECT_ID_EXT_CACHE_START;
2793 totalAppCacheSize += GetOccupiedSpaceForProjectId(uuid, cacheProjectId);
2794
2795 // App OBBs
2796 long obbProjectId = uid - AID_APP_START + PROJECT_ID_EXT_OBB_START;
2797 totalAppObbSize += GetOccupiedSpaceForProjectId(uuid, obbProjectId);
2798 }
2799 }
2800 // Total size should include app data + cache
2801 totalSize += totalAppDataSize;
2802 totalSize += totalAppCacheSize;
2803 sizes.totalSize = totalSize;
2804
2805 // Only OBB is separate
2806 sizes.obbSize = totalAppObbSize;
2807 }
2808
2809 return sizes;
2810}
2811
Jooyung Han149be4a2020-01-23 12:45:10 +09002812binder::Status InstalldNativeService::getUserSize(const std::optional<std::string>& uuid,
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002813 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2814 std::vector<int64_t>* _aidl_return) {
2815 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002816 ENFORCE_VALID_USER(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002817 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002818 // NOTE: Locking is relaxed on this method, since it's limited to
2819 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002820
2821 // When modifying this logic, always verify using tests:
2822 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
2823
2824#if MEASURE_DEBUG
2825 LOG(INFO) << "Measuring user " << userId;
2826#endif
2827
2828 struct stats stats;
2829 struct stats extStats;
2830 memset(&stats, 0, sizeof(stats));
2831 memset(&extStats, 0, sizeof(extStats));
2832
Jooyung Han149be4a2020-01-23 12:45:10 +09002833 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002834 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2835
Risan5f308262018-10-26 12:06:58 -06002836 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002837 flags &= ~FLAG_USE_QUOTA;
2838 }
2839
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002840 if (flags & FLAG_USE_QUOTA) {
Zim23457d02022-08-17 12:57:41 +01002841 atrace_pm_begin("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002842 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002843 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002844
Zim23457d02022-08-17 12:57:41 +01002845 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002846 auto cePath = create_data_user_ce_path(uuid_, userId);
2847 collectManualStatsForUser(cePath, &stats, true);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002848 auto dePath = create_data_user_de_path(uuid_, userId);
2849 collectManualStatsForUser(dePath, &stats, true);
Zim23457d02022-08-17 12:57:41 +01002850 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002851
Jeff Sharkey06a61842017-04-15 12:03:31 -06002852 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002853 atrace_pm_begin("profile");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002854 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2855 calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
2856 auto refProfilePath = create_primary_ref_profile_dir_path();
2857 calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002858 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002859 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002860
Zim23457d02022-08-17 12:57:41 +01002861 atrace_pm_begin("external");
Martijn Coenen771cc342020-02-19 23:26:56 +01002862 auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2863 extStats.dataSize += sizes.totalSize;
2864 extStats.codeSize += sizes.obbSize;
Zim23457d02022-08-17 12:57:41 +01002865 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002866
Jeff Sharkey06a61842017-04-15 12:03:31 -06002867 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002868 atrace_pm_begin("dalvik");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002869 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
2870 -1, -1, true);
2871 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
2872 -1, -1, true);
Zim23457d02022-08-17 12:57:41 +01002873 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002874 }
Zim23457d02022-08-17 12:57:41 +01002875 atrace_pm_begin("quota");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002876 int64_t dataSize = extStats.dataSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002877 for (auto appId : appIds) {
2878 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06002879 collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002880#if MEASURE_DEBUG
2881 // Sleep to make sure we don't lose logs
2882 usleep(1);
2883#endif
2884 }
2885 }
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002886 extStats.dataSize = dataSize;
Zim23457d02022-08-17 12:57:41 +01002887 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002888 } else {
Zim23457d02022-08-17 12:57:41 +01002889 atrace_pm_begin("code");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002890 calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002891 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002892
Zim23457d02022-08-17 12:57:41 +01002893 atrace_pm_begin("data");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002894 auto cePath = create_data_user_ce_path(uuid_, userId);
2895 collectManualStatsForUser(cePath, &stats);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002896 auto dePath = create_data_user_de_path(uuid_, userId);
2897 collectManualStatsForUser(dePath, &stats);
Zim23457d02022-08-17 12:57:41 +01002898 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002899
Zim23457d02022-08-17 12:57:41 +01002900 atrace_pm_begin("sdksandbox");
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002901 auto sdkSandboxCePath = create_data_misc_sdk_sandbox_path(uuid_, true, userId);
2902 collectManualStatsForUser(sdkSandboxCePath, &stats, false, true);
2903 auto sdkSandboxDePath = create_data_misc_sdk_sandbox_path(uuid_, false, userId);
2904 collectManualStatsForUser(sdkSandboxDePath, &stats, false, true);
Zim23457d02022-08-17 12:57:41 +01002905 atrace_pm_end();
Sanjana Sunil08c0ff32022-03-08 16:16:18 +00002906
Jeff Sharkey06a61842017-04-15 12:03:31 -06002907 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002908 atrace_pm_begin("profile");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002909 auto userProfilePath = create_primary_cur_profile_dir_path(userId);
2910 calculate_tree_size(userProfilePath, &stats.dataSize);
2911 auto refProfilePath = create_primary_ref_profile_dir_path();
2912 calculate_tree_size(refProfilePath, &stats.codeSize);
Zim23457d02022-08-17 12:57:41 +01002913 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002914 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002915
Zim23457d02022-08-17 12:57:41 +01002916 atrace_pm_begin("external");
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002917 auto dataMediaPath = create_data_media_path(uuid_, userId);
2918 collectManualExternalStatsForUser(dataMediaPath, &extStats);
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002919
Jeff Sharkey7bf5b952017-01-19 09:21:36 -07002920#if MEASURE_DEBUG
2921 LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
hyejin.kimae3e9ae2023-06-20 19:42:57 +09002922 << extStats.cacheSize << " code " << extStats.codeSize;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002923#endif
Zim23457d02022-08-17 12:57:41 +01002924 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002925
Jeff Sharkey06a61842017-04-15 12:03:31 -06002926 if (!uuid) {
Zim23457d02022-08-17 12:57:41 +01002927 atrace_pm_begin("dalvik");
Jeff Sharkey06a61842017-04-15 12:03:31 -06002928 calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
2929 calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
Zim23457d02022-08-17 12:57:41 +01002930 atrace_pm_end();
Jeff Sharkey06a61842017-04-15 12:03:31 -06002931 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002932 }
2933
2934 std::vector<int64_t> ret;
2935 ret.push_back(stats.codeSize);
2936 ret.push_back(stats.dataSize);
2937 ret.push_back(stats.cacheSize);
2938 ret.push_back(extStats.codeSize);
2939 ret.push_back(extStats.dataSize);
2940 ret.push_back(extStats.cacheSize);
2941#if MEASURE_DEBUG
2942 LOG(DEBUG) << "Final result " << toString(ret);
2943#endif
2944 *_aidl_return = ret;
2945 return ok();
2946}
2947
Jooyung Han149be4a2020-01-23 12:45:10 +09002948binder::Status InstalldNativeService::getExternalSize(const std::optional<std::string>& uuid,
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002949 int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
2950 std::vector<int64_t>* _aidl_return) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002951 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00002952 ENFORCE_VALID_USER(userId);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002953 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyb26786d2017-03-11 19:40:29 -07002954 // NOTE: Locking is relaxed on this method, since it's limited to
2955 // read-only measurements without mutation.
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002956
2957 // When modifying this logic, always verify using tests:
2958 // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
2959
2960#if MEASURE_DEBUG
2961 LOG(INFO) << "Measuring external " << userId;
2962#endif
2963
Jooyung Han149be4a2020-01-23 12:45:10 +09002964 auto uuidString = uuid.value_or("");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002965 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
2966
2967 int64_t totalSize = 0;
2968 int64_t audioSize = 0;
2969 int64_t videoSize = 0;
2970 int64_t imageSize = 0;
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002971 int64_t appSize = 0;
Jeff Sharkeya0136982017-07-06 11:29:37 -06002972 int64_t obbSize = 0;
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002973
Risan5f308262018-10-26 12:06:58 -06002974 if (!IsQuotaSupported(uuidString)) {
Jeff Sharkey66b1a122017-01-16 20:57:45 -07002975 flags &= ~FLAG_USE_QUOTA;
2976 }
2977
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002978 if (flags & FLAG_USE_QUOTA) {
Zim23457d02022-08-17 12:57:41 +01002979 atrace_pm_begin("quota");
Martijn Coenen771cc342020-02-19 23:26:56 +01002980 auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
2981 totalSize = sizes.totalSize;
2982 audioSize = sizes.audioSize;
2983 videoSize = sizes.videoSize;
2984 imageSize = sizes.imageSize;
2985 obbSize = sizes.obbSize;
Zim23457d02022-08-17 12:57:41 +01002986 atrace_pm_end();
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002987
Zim23457d02022-08-17 12:57:41 +01002988 atrace_pm_begin("apps");
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002989 struct stats extStats;
2990 memset(&extStats, 0, sizeof(extStats));
2991 for (auto appId : appIds) {
2992 if (appId >= AID_APP_START) {
Risan5f308262018-10-26 12:06:58 -06002993 collectQuotaStats(uuidString, userId, appId, nullptr, &extStats);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06002994 }
2995 }
Jeff Sharkey4ca8ff92017-06-07 15:59:03 -06002996 appSize = extStats.dataSize;
Zim23457d02022-08-17 12:57:41 +01002997 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07002998 } else {
Zim23457d02022-08-17 12:57:41 +01002999 atrace_pm_begin("manual");
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003000 FTS *fts;
3001 FTSENT *p;
3002 auto path = create_data_media_path(uuid_, userId);
3003 char *argv[] = { (char*) path.c_str(), nullptr };
Yi Konge7bf3772018-07-17 16:16:24 -07003004 if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003005 return error("Failed to fts_open " + path);
3006 }
Yi Konge7bf3772018-07-17 16:16:24 -07003007 while ((p = fts_read(fts)) != nullptr) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003008 char* ext;
3009 int64_t size = (p->fts_statp->st_blocks * 512);
3010 switch (p->fts_info) {
3011 case FTS_F:
3012 // Only categorize files not belonging to apps
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06003013 if (p->fts_parent->fts_number == 0) {
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003014 ext = strrchr(p->fts_name, '.');
3015 if (ext != nullptr) {
3016 switch (MatchExtension(++ext)) {
3017 case AID_MEDIA_AUDIO: audioSize += size; break;
3018 case AID_MEDIA_VIDEO: videoSize += size; break;
3019 case AID_MEDIA_IMAGE: imageSize += size; break;
3020 }
3021 }
3022 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07003023 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003024 case FTS_D:
Jeff Sharkey444ad1e2017-03-12 16:25:36 -06003025 // Ignore data belonging to specific apps
3026 p->fts_number = p->fts_parent->fts_number;
3027 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
3028 p->fts_number = 1;
3029 }
Chih-Hung Hsiehf1dd98e2018-10-16 14:17:11 -07003030 [[fallthrough]]; // always count against total
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003031 case FTS_DEFAULT:
3032 case FTS_SL:
3033 case FTS_SLNONE:
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06003034 if (p->fts_parent->fts_number == 1) {
3035 appSize += size;
3036 }
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003037 totalSize += size;
3038 break;
3039 }
3040 }
3041 fts_close(fts);
Zim23457d02022-08-17 12:57:41 +01003042 atrace_pm_end();
Jeff Sharkeya0136982017-07-06 11:29:37 -06003043
Zim23457d02022-08-17 12:57:41 +01003044 atrace_pm_begin("obb");
Jeff Sharkey6d775c52019-03-22 13:46:20 -06003045 auto obbPath = StringPrintf("%s/Android/obb",
3046 create_data_media_path(uuid_, userId).c_str());
Jeff Sharkeya0136982017-07-06 11:29:37 -06003047 calculate_tree_size(obbPath, &obbSize);
Chuwei Xu5d64ddf2019-12-04 15:32:18 +08003048 if (!(flags & FLAG_USE_QUOTA)) {
3049 totalSize -= obbSize;
3050 }
Zim23457d02022-08-17 12:57:41 +01003051 atrace_pm_end();
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003052 }
3053
3054 std::vector<int64_t> ret;
3055 ret.push_back(totalSize);
3056 ret.push_back(audioSize);
3057 ret.push_back(videoSize);
3058 ret.push_back(imageSize);
Jeff Sharkeya084fcd2017-04-17 16:44:41 -06003059 ret.push_back(appSize);
Jeff Sharkeya0136982017-07-06 11:29:37 -06003060 ret.push_back(obbSize);
Jeff Sharkeydf2d7542017-01-07 09:19:35 -07003061#if MEASURE_DEBUG
3062 LOG(DEBUG) << "Final result " << toString(ret);
3063#endif
Jeff Sharkey3dfae0c2016-12-12 17:32:56 -07003064 *_aidl_return = ret;
Jeff Sharkey423e7462016-12-09 18:18:43 -07003065 return ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003066}
3067
Felka Chang2a0a2462019-11-20 14:20:40 +08003068binder::Status InstalldNativeService::getAppCrates(
Jooyung Han149be4a2020-01-23 12:45:10 +09003069 const std::optional<std::string>& uuid,
Felka Chang2a0a2462019-11-20 14:20:40 +08003070 const std::vector<std::string>& packageNames, int32_t userId,
Jooyung Han149be4a2020-01-23 12:45:10 +09003071 std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
Felka Chang2a0a2462019-11-20 14:20:40 +08003072 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003073 ENFORCE_VALID_USER(userId);
Felka Chang2a0a2462019-11-20 14:20:40 +08003074 CHECK_ARGUMENT_UUID(uuid);
3075 for (const auto& packageName : packageNames) {
3076 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3077 }
Felka Chang4df87f62020-02-11 19:08:43 +08003078#ifdef ENABLE_STORAGE_CRATES
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003079 LOCK_PACKAGE_USER();
Felka Chang2a0a2462019-11-20 14:20:40 +08003080
Jooyung Han149be4a2020-01-23 12:45:10 +09003081 auto retVector = std::vector<std::optional<CrateMetadata>>();
Felka Chang2a0a2462019-11-20 14:20:40 +08003082 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3083
Jooyung Han149be4a2020-01-23 12:45:10 +09003084 std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3085 [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
Felka Chang2a0a2462019-11-20 14:20:40 +08003086 if (cratedFolder == nullptr) {
3087 return;
3088 }
Jooyung Han149be4a2020-01-23 12:45:10 +09003089 retVector.push_back(std::move(crateMetadata));
Felka Chang2a0a2462019-11-20 14:20:40 +08003090 };
3091
3092 for (const auto& packageName : packageNames) {
3093#if CRATE_DEBUG
3094 LOG(DEBUG) << "packageName = " << packageName;
3095#endif
3096 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageName);
3097 crateManager->traverseAllCrates(onCreateCrate);
3098 }
3099
3100#if CRATE_DEBUG
Jooyung Han149be4a2020-01-23 12:45:10 +09003101 LOG(WARNING) << "retVector.size() =" << retVector.size();
3102 for (auto& item : retVector) {
Jooyung Hand520e802020-03-03 02:56:34 +09003103 CrateManager::dump(*item);
Felka Chang2a0a2462019-11-20 14:20:40 +08003104 }
3105#endif
3106
3107 *_aidl_return = std::move(retVector);
Felka Chang4df87f62020-02-11 19:08:43 +08003108#else // ENABLE_STORAGE_CRATES
Jooyung Han149be4a2020-01-23 12:45:10 +09003109 _aidl_return->reset();
Felka Chang4df87f62020-02-11 19:08:43 +08003110
3111 /* prevent compile warning fail */
3112 if (userId < 0) {
3113 return error();
3114 }
3115#endif // ENABLE_STORAGE_CRATES
Felka Chang2a0a2462019-11-20 14:20:40 +08003116 return ok();
3117}
3118
3119binder::Status InstalldNativeService::getUserCrates(
Jooyung Han149be4a2020-01-23 12:45:10 +09003120 const std::optional<std::string>& uuid, int32_t userId,
3121 std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
Felka Chang2a0a2462019-11-20 14:20:40 +08003122 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003123 ENFORCE_VALID_USER(userId);
Felka Chang2a0a2462019-11-20 14:20:40 +08003124 CHECK_ARGUMENT_UUID(uuid);
Felka Chang4df87f62020-02-11 19:08:43 +08003125#ifdef ENABLE_STORAGE_CRATES
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003126 LOCK_USER();
Felka Chang2a0a2462019-11-20 14:20:40 +08003127
3128 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
Jooyung Han149be4a2020-01-23 12:45:10 +09003129 auto retVector = std::vector<std::optional<CrateMetadata>>();
Felka Chang2a0a2462019-11-20 14:20:40 +08003130
Jooyung Han149be4a2020-01-23 12:45:10 +09003131 std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
3132 [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
Felka Chang2a0a2462019-11-20 14:20:40 +08003133 if (cratedFolder == nullptr) {
3134 return;
3135 }
Jooyung Hand520e802020-03-03 02:56:34 +09003136 retVector.push_back(std::move(crateMetadata));
Felka Chang2a0a2462019-11-20 14:20:40 +08003137 };
3138
3139 std::function<void(FTSENT*)> onHandingPackage = [&](FTSENT* packageDir) -> void {
3140 auto crateManager = std::make_unique<CrateManager>(uuid_, userId, packageDir->fts_name);
3141 crateManager->traverseAllCrates(onCreateCrate);
3142 };
3143 CrateManager::traverseAllPackagesForUser(uuid, userId, onHandingPackage);
3144
3145#if CRATE_DEBUG
Jooyung Han149be4a2020-01-23 12:45:10 +09003146 LOG(DEBUG) << "retVector.size() =" << retVector.size();
3147 for (auto& item : retVector) {
Jooyung Hand520e802020-03-03 02:56:34 +09003148 CrateManager::dump(*item);
Felka Chang2a0a2462019-11-20 14:20:40 +08003149 }
3150#endif
3151
3152 *_aidl_return = std::move(retVector);
Felka Chang4df87f62020-02-11 19:08:43 +08003153#else // ENABLE_STORAGE_CRATES
Jooyung Han149be4a2020-01-23 12:45:10 +09003154 _aidl_return->reset();
Felka Chang4df87f62020-02-11 19:08:43 +08003155
3156 /* prevent compile warning fail */
3157 if (userId < 0) {
3158 return error();
3159 }
3160#endif // ENABLE_STORAGE_CRATES
Felka Chang2a0a2462019-11-20 14:20:40 +08003161 return ok();
3162}
3163
Jooyung Han149be4a2020-01-23 12:45:10 +09003164binder::Status InstalldNativeService::setAppQuota(const std::optional<std::string>& uuid,
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003165 int32_t userId, int32_t appId, int64_t cacheQuota) {
3166 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003167 ENFORCE_VALID_USER(userId);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003168 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003169 std::lock_guard<std::recursive_mutex> lock(mQuotasLock);
Jeff Sharkey88ddd942017-01-17 18:05:54 -07003170
3171 int32_t uid = multiuser_get_uid(userId, appId);
3172 mCacheQuotas[uid] = cacheQuota;
3173
3174 return ok();
3175}
3176
David Sehr6727c2d2016-05-17 16:06:22 -07003177// Dumps the contents of a profile file, using pkgname's dex files for pretty
3178// printing the result.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003179binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
Martin Stjernholmfd000402022-04-11 18:04:59 +01003180 const std::string& profileName,
3181 const std::string& codePath,
3182 bool dumpClassesAndMethods, bool* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003183 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003184 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003185 CHECK_ARGUMENT_PATH(codePath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003186 LOCK_PACKAGE();
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003187
Martin Stjernholmfd000402022-04-11 18:04:59 +01003188 *_aidl_return = dump_profiles(uid, packageName, profileName, codePath, dumpClassesAndMethods);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003189 return ok();
David Sehr6727c2d2016-05-17 16:06:22 -07003190}
3191
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003192// Copy the contents of a system profile over the data profile.
3193binder::Status InstalldNativeService::copySystemProfile(const std::string& systemProfile,
Calin Juravle562de812018-01-20 23:34:18 -08003194 int32_t packageUid, const std::string& packageName, const std::string& profileName,
3195 bool* _aidl_return) {
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003196 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyyd04631f2022-08-12 15:14:41 -07003197 CHECK_ARGUMENT_PATH(systemProfile);
3198 if (!base::EndsWith(systemProfile, ".prof")) {
3199 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3200 StringPrintf("System profile path %s does not end with .prof",
3201 systemProfile.c_str()));
3202 }
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003203 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyyd04631f2022-08-12 15:14:41 -07003204 CHECK_ARGUMENT_FILE_NAME(profileName);
3205 if (!base::EndsWith(profileName, ".prof")) {
3206 return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
3207 StringPrintf("Profile name %s does not end with .prof",
3208 profileName.c_str()));
3209 }
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003210 LOCK_PACKAGE();
Calin Juravle562de812018-01-20 23:34:18 -08003211 *_aidl_return = copy_system_profile(systemProfile, packageUid, packageName, profileName);
Mathieu Chartierf966f2a2017-05-10 12:48:37 -07003212 return ok();
3213}
3214
Andreas Gampe4d0f8252016-03-20 11:30:28 -07003215// TODO: Consider returning error codes.
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003216binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
Calin Juravle3b758282021-06-08 08:04:52 -07003217 const std::string& profileName, int* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003218 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003219 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003220 LOCK_PACKAGE();
Jeff Sharkey423e7462016-12-09 18:18:43 -07003221
Calin Juravle562de812018-01-20 23:34:18 -08003222 *_aidl_return = analyze_primary_profiles(uid, packageName, profileName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003223 return ok();
Andreas Gampe4d0f8252016-03-20 11:30:28 -07003224}
3225
Calin Juravlec41dac22017-12-05 12:29:15 -08003226binder::Status InstalldNativeService::createProfileSnapshot(int32_t appId,
Calin Juravlee61189e2018-01-23 19:54:11 -08003227 const std::string& packageName, const std::string& profileName,
3228 const std::string& classpath, bool* _aidl_return) {
Calin Juravle29591732017-11-20 17:46:19 -08003229 ENFORCE_UID(AID_SYSTEM);
3230 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003231 LOCK_PACKAGE();
Calin Juravle29591732017-11-20 17:46:19 -08003232
Calin Juravlee61189e2018-01-23 19:54:11 -08003233 *_aidl_return = create_profile_snapshot(appId, packageName, profileName, classpath);
Calin Juravle29591732017-11-20 17:46:19 -08003234 return ok();
3235}
3236
3237binder::Status InstalldNativeService::destroyProfileSnapshot(const std::string& packageName,
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003238 const std::string& profileName) {
Calin Juravle29591732017-11-20 17:46:19 -08003239 ENFORCE_UID(AID_SYSTEM);
3240 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003241 LOCK_PACKAGE();
Calin Juravle29591732017-11-20 17:46:19 -08003242
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003243 std::string snapshot = create_snapshot_profile_path(packageName, profileName);
Calin Juravle29591732017-11-20 17:46:19 -08003244 if ((unlink(snapshot.c_str()) != 0) && (errno != ENOENT)) {
Calin Juravlecfcd6aa2018-01-18 20:23:17 -08003245 return error("Failed to destroy profile snapshot for " + packageName + ":" + profileName);
Calin Juravle29591732017-11-20 17:46:19 -08003246 }
3247 return ok();
3248}
3249
Jooyung Han149be4a2020-01-23 12:45:10 +09003250static const char* getCStr(const std::optional<std::string>& data,
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003251 const char* default_value = nullptr) {
Jooyung Han149be4a2020-01-23 12:45:10 +09003252 return data ? data->c_str() : default_value;
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003253}
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003254binder::Status InstalldNativeService::dexopt(
3255 const std::string& apkPath, int32_t uid, const std::string& packageName,
3256 const std::string& instructionSet, int32_t dexoptNeeded,
3257 const std::optional<std::string>& outputPath, int32_t dexFlags,
Jooyung Han149be4a2020-01-23 12:45:10 +09003258 const std::string& compilerFilter, const std::optional<std::string>& uuid,
3259 const std::optional<std::string>& classLoaderContext,
3260 const std::optional<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
3261 const std::optional<std::string>& profileName,
3262 const std::optional<std::string>& dexMetadataPath,
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003263 const std::optional<std::string>& compilationReason, bool* aidl_return) {
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003264 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003265 CHECK_ARGUMENT_UUID(uuid);
Jeff Sharkey53594302018-02-24 18:59:39 -07003266 CHECK_ARGUMENT_PATH(apkPath);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003267 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003268 CHECK_ARGUMENT_PATH(outputPath);
3269 CHECK_ARGUMENT_PATH(dexMetadataPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003270 const auto userId = multiuser_get_user_id(uid);
3271 LOCK_PACKAGE_USER();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003272
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07003273 const char* oat_dir = getCStr(outputPath);
3274 const char* instruction_set = instructionSet.c_str();
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003275 if (oat_dir != nullptr && !createOatDir(packageName, oat_dir, instruction_set).isOk()) {
Alex Buynytskyy17d8f822019-06-20 16:29:57 -07003276 // Can't create oat dir - let dexopt use cache dir.
3277 oat_dir = nullptr;
3278 }
3279
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003280 const char* apk_path = apkPath.c_str();
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003281 const char* pkgname = packageName.c_str();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003282 const char* compiler_filter = compilerFilter.c_str();
Calin Juravlecc3b8ae2018-02-01 17:03:23 +00003283 const char* volume_uuid = getCStr(uuid);
3284 const char* class_loader_context = getCStr(classLoaderContext);
3285 const char* se_info = getCStr(seInfo);
3286 const char* profile_name = getCStr(profileName);
3287 const char* dm_path = getCStr(dexMetadataPath);
Calin Juravledcccd832018-02-13 18:31:32 -08003288 const char* compilation_reason = getCStr(compilationReason);
Andreas Gampe023b2242018-02-28 16:03:25 -08003289 std::string error_msg;
Keun young Park65578d62021-06-28 17:52:05 -07003290 bool completed = false; // not necessary but for compiler
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003291 int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
Calin Juravle1d667612017-07-13 22:50:21 -07003292 oat_dir, dexFlags, compiler_filter, volume_uuid, class_loader_context, se_info,
Keun young Park65578d62021-06-28 17:52:05 -07003293 downgrade, targetSdkVersion, profile_name, dm_path, compilation_reason, &error_msg,
3294 &completed);
3295 *aidl_return = completed;
Andreas Gampe023b2242018-02-28 16:03:25 -08003296 return res ? error(res, error_msg) : ok();
Jeff Sharkey6c2c0562016-12-07 12:12:00 -07003297}
3298
Keun young Park65578d62021-06-28 17:52:05 -07003299binder::Status InstalldNativeService::controlDexOptBlocking(bool block) {
3300 android::installd::control_dexopt_blocking(block);
3301 return ok();
3302}
3303
Eric Holk0ebbe0f2019-01-09 18:17:27 -08003304binder::Status InstalldNativeService::compileLayouts(const std::string& apkPath,
3305 const std::string& packageName,
3306 const std ::string& outDexFile, int uid,
3307 bool* _aidl_return) {
3308 const char* apk_path = apkPath.c_str();
3309 const char* package_name = packageName.c_str();
3310 const char* out_dex_file = outDexFile.c_str();
3311 *_aidl_return = android::installd::view_compiler(apk_path, package_name, out_dex_file, uid);
3312 return *_aidl_return ? ok() : error("viewcompiler failed");
3313}
3314
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003315binder::Status InstalldNativeService::linkNativeLibraryDirectory(
Jooyung Han149be4a2020-01-23 12:45:10 +09003316 const std::optional<std::string>& uuid, const std::string& packageName,
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003317 const std::string& nativeLibPath32, int32_t userId) {
3318 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003319 CHECK_ARGUMENT_UUID(uuid);
3320 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003321 CHECK_ARGUMENT_PATH(nativeLibPath32);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003322 LOCK_PACKAGE_USER();
Jeff Sharkey423e7462016-12-09 18:18:43 -07003323
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003324 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3325 const char* pkgname = packageName.c_str();
3326 const char* asecLibDir = nativeLibPath32.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003327 struct stat s, libStat;
Jeff Sharkey423e7462016-12-09 18:18:43 -07003328 binder::Status res = ok();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003329
Jeff Sharkey423e7462016-12-09 18:18:43 -07003330 auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
3331 auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
Jeff Sharkeyc03de092015-04-07 18:14:05 -07003332
3333 const char* pkgdir = _pkgdir.c_str();
3334 const char* libsymlink = _libsymlink.c_str();
Mike Lockwood94afecf2012-10-24 10:45:23 -07003335
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003336 if (stat(pkgdir, &s) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003337 return error("Failed to stat " + _pkgdir);
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003338 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003339
Nick Kralevich85958b62019-01-30 12:32:21 -08003340 char *con = nullptr;
Alex Buynytskyyc668d562023-11-10 22:53:46 +00003341 if (::lgetfilecon(pkgdir, &con) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08003342 return error("Failed to lgetfilecon " + _pkgdir);
3343 }
3344
Mike Lockwood94afecf2012-10-24 10:45:23 -07003345 if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
Nick Kralevich85958b62019-01-30 12:32:21 -08003346 res = error("Failed to chown " + _pkgdir);
3347 goto out;
Mike Lockwood94afecf2012-10-24 10:45:23 -07003348 }
3349
3350 if (chmod(pkgdir, 0700) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003351 res = error("Failed to chmod " + _pkgdir);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003352 goto out;
3353 }
3354
3355 if (lstat(libsymlink, &libStat) < 0) {
3356 if (errno != ENOENT) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003357 res = error("Failed to stat " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003358 goto out;
3359 }
3360 } else {
3361 if (S_ISDIR(libStat.st_mode)) {
Yi Konge7bf3772018-07-17 16:16:24 -07003362 if (delete_dir_contents(libsymlink, 1, nullptr) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003363 res = error("Failed to delete " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003364 goto out;
3365 }
3366 } else if (S_ISLNK(libStat.st_mode)) {
3367 if (unlink(libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003368 res = error("Failed to unlink " + _libsymlink);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003369 goto out;
3370 }
3371 }
3372 }
3373
3374 if (symlink(asecLibDir, libsymlink) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003375 res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003376 goto out;
3377 }
3378
Nick Kralevich85958b62019-01-30 12:32:21 -08003379 if (lsetfilecon(libsymlink, con) < 0) {
3380 res = error("Failed to lsetfilecon " + _libsymlink);
3381 goto out;
3382 }
3383
Mike Lockwood94afecf2012-10-24 10:45:23 -07003384out:
Nick Kralevich85958b62019-01-30 12:32:21 -08003385 free(con);
Mike Lockwood94afecf2012-10-24 10:45:23 -07003386 if (chmod(pkgdir, s.st_mode) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003387 auto msg = "Failed to cleanup chmod " + _pkgdir;
3388 if (res.isOk()) {
3389 res = error(msg);
3390 } else {
3391 PLOG(ERROR) << msg;
3392 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003393 }
3394
3395 if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003396 auto msg = "Failed to cleanup chown " + _pkgdir;
3397 if (res.isOk()) {
3398 res = error(msg);
3399 } else {
3400 PLOG(ERROR) << msg;
3401 }
Mike Lockwood94afecf2012-10-24 10:45:23 -07003402 }
3403
Jeff Sharkey423e7462016-12-09 18:18:43 -07003404 return res;
Mike Lockwood94afecf2012-10-24 10:45:23 -07003405}
MÃ¥rten Kongstad63568b12014-01-31 14:42:59 +01003406
Jooyung Han149be4a2020-01-23 12:45:10 +09003407binder::Status InstalldNativeService::restoreconAppData(const std::optional<std::string>& uuid,
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003408 const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
3409 const std::string& seInfo) {
3410 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003411 ENFORCE_VALID_USER(userId);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003412 CHECK_ARGUMENT_UUID(uuid);
3413 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003414 LOCK_PACKAGE_USER();
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08003415 return restoreconAppDataLocked(uuid, packageName, userId, flags, appId, seInfo);
3416}
3417
3418binder::Status InstalldNativeService::restoreconAppDataLocked(
3419 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3420 int32_t flags, int32_t appId, const std::string& seInfo) {
3421 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003422 ENFORCE_VALID_USER(userId);
Alex Buynytskyyfcd5bf32021-11-23 11:31:34 -08003423 CHECK_ARGUMENT_UUID(uuid);
3424 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003425
3426 binder::Status res = ok();
Robert Craige9887e42014-02-20 10:25:56 -05003427
Robert Craigda30dc72014-03-27 10:21:12 -04003428 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003429 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003430 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3431 const char* pkgName = packageName.c_str();
3432 const char* seinfo = seInfo.c_str();
Robert Craigda30dc72014-03-27 10:21:12 -04003433
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003434 uid_t uid = multiuser_get_uid(userId, appId);
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07003435 if (flags & FLAG_STORAGE_CE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003436 auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003437 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003438 res = error("restorecon failed for " + path);
Jeff Sharkeyebf728f2015-11-18 14:15:17 -07003439 }
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003440 }
Jeff Sharkeyaa7ddfd2016-02-03 14:03:16 -07003441 if (flags & FLAG_STORAGE_DE) {
Jeff Sharkeyc1e93e72016-12-05 23:39:32 -07003442 auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
Jeff Sharkeyc7d1b222016-01-11 13:07:09 -07003443 if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003444 res = error("restorecon failed for " + path);
Jeff Sharkey41ea4242015-04-09 11:34:03 -07003445 }
Robert Craige9887e42014-02-20 10:25:56 -05003446 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07003447 return res;
Robert Craige9887e42014-02-20 10:25:56 -05003448}
Narayan Kamath3aee2c52014-06-10 13:16:47 +01003449
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00003450binder::Status InstalldNativeService::restoreconSdkDataLocked(
3451 const std::optional<std::string>& uuid, const std::string& packageName, int32_t userId,
3452 int32_t flags, int32_t appId, const std::string& seInfo) {
3453 ENFORCE_UID(AID_SYSTEM);
Steven Moreland36945362023-07-05 20:29:10 +00003454 ENFORCE_VALID_USER(userId);
Mohammad Samiul Islame7634ba2022-03-07 20:27:30 +00003455 CHECK_ARGUMENT_UUID(uuid);
3456 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3457
3458 binder::Status res = ok();
3459
3460 // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
3461 unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
3462 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3463 const char* pkgName = packageName.c_str();
3464 const char* seinfo = seInfo.c_str();
3465
3466 uid_t uid = multiuser_get_sdk_sandbox_uid(userId, appId);
3467 constexpr int storageFlags[2] = {FLAG_STORAGE_CE, FLAG_STORAGE_DE};
3468 for (int currentFlag : storageFlags) {
3469 if ((flags & currentFlag) == 0) {
3470 continue;
3471 }
3472 const bool isCeData = (currentFlag == FLAG_STORAGE_CE);
3473 const auto packagePath =
3474 create_data_misc_sdk_sandbox_package_path(uuid_, isCeData, userId, pkgName);
3475 if (access(packagePath.c_str(), F_OK) != 0) {
3476 LOG(INFO) << "Missing source " << packagePath;
3477 continue;
3478 }
3479 const auto subDirHandler = [&packagePath, &seinfo, &uid, &seflags,
3480 &res](const std::string& subDir) {
3481 const auto& fullpath = packagePath + "/" + subDir;
3482 if (selinux_android_restorecon_pkgdir(fullpath.c_str(), seinfo, uid, seflags) < 0) {
3483 res = error("restorecon failed for " + fullpath);
3484 }
3485 };
3486 const auto ec = foreach_subdir(packagePath, subDirHandler);
3487 if (ec != 0) {
3488 res = error("Failed to restorecon for subdirs of " + packagePath);
3489 }
3490 }
3491 return res;
3492}
3493
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003494binder::Status InstalldNativeService::createOatDir(const std::string& packageName,
3495 const std::string& oatDir,
3496 const std::string& instructionSet) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003497 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003498 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003499 CHECK_ARGUMENT_PATH(oatDir);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003500 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003501
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003502 const char* oat_dir = oatDir.c_str();
3503 const char* instruction_set = instructionSet.c_str();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003504 char oat_instr_dir[PKG_PATH_MAX];
3505
3506 if (validate_apk_path(oat_dir)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003507 return error("Invalid path " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003508 }
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07003509 if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003510 return error("Failed to prepare " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003511 }
3512 if (selinux_android_restorecon(oat_dir, 0)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003513 return error("Failed to restorecon " + oatDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003514 }
3515 snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
Fyodor Kupolov8eed7e62015-04-06 19:09:02 -07003516 if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003517 return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003518 }
Jeff Sharkey423e7462016-12-09 18:18:43 -07003519 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003520}
3521
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003522binder::Status InstalldNativeService::rmPackageDir(const std::string& packageName,
3523 const std::string& packageDir) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003524 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey53594302018-02-24 18:59:39 -07003525 CHECK_ARGUMENT_PATH(packageDir);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003526 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003527
Jeff Sharkey423e7462016-12-09 18:18:43 -07003528 if (validate_apk_path(packageDir.c_str())) {
3529 return error("Invalid path " + packageDir);
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003530 }
Oleksandr Peletskyid2be6322019-01-24 17:59:45 +01003531 if (rm_package_dir(packageDir) != 0) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003532 return error("Failed to delete " + packageDir);
3533 }
3534 return ok();
Fyodor Kupolov88ce4ff2015-03-03 12:25:29 -08003535}
3536
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003537binder::Status InstalldNativeService::linkFile(const std::string& packageName,
3538 const std::string& relativePath,
3539 const std::string& fromBase,
3540 const std::string& toBase) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003541 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003542 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003543 CHECK_ARGUMENT_PATH(fromBase);
3544 CHECK_ARGUMENT_PATH(toBase);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003545 LOCK_PACKAGE();
Jeff Sharkey7a9059e2017-01-16 19:07:18 -07003546
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003547 const char* relative_path = relativePath.c_str();
3548 const char* from_base = fromBase.c_str();
3549 const char* to_base = toBase.c_str();
Narayan Kamathd845c962015-06-04 13:20:27 +01003550 char from_path[PKG_PATH_MAX];
3551 char to_path[PKG_PATH_MAX];
3552 snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
3553 snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
3554
3555 if (validate_apk_path_subdirs(from_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003556 return error(StringPrintf("Invalid from path %s", from_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003557 }
3558
3559 if (validate_apk_path_subdirs(to_path)) {
Jeff Sharkey423e7462016-12-09 18:18:43 -07003560 return error(StringPrintf("Invalid to path %s", to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003561 }
3562
Jeff Sharkey423e7462016-12-09 18:18:43 -07003563 if (link(from_path, to_path) < 0) {
3564 return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
Narayan Kamathd845c962015-06-04 13:20:27 +01003565 }
3566
Jeff Sharkey423e7462016-12-09 18:18:43 -07003567 return ok();
Narayan Kamathd845c962015-06-04 13:20:27 +01003568}
3569
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003570binder::Status InstalldNativeService::moveAb(const std::string& packageName,
3571 const std::string& apkPath,
3572 const std::string& instructionSet,
3573 const std::string& outputPath) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003574 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003575 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003576 CHECK_ARGUMENT_PATH(apkPath);
3577 CHECK_ARGUMENT_PATH(outputPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003578 LOCK_PACKAGE();
Jeff Sharkey90aff262016-12-12 14:28:24 -07003579
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003580 const char* apk_path = apkPath.c_str();
3581 const char* instruction_set = instructionSet.c_str();
3582 const char* oat_dir = outputPath.c_str();
Andreas Gampe0354bd02016-06-27 14:25:30 -07003583
Jeff Sharkey90aff262016-12-12 14:28:24 -07003584 bool success = move_ab(apk_path, instruction_set, oat_dir);
Jeff Sharkey423e7462016-12-09 18:18:43 -07003585 return success ? ok() : error();
Andreas Gampee65b4fa2016-03-01 11:46:45 -08003586}
3587
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003588binder::Status InstalldNativeService::deleteOdex(const std::string& packageName,
3589 const std::string& apkPath,
3590 const std::string& instructionSet,
3591 const std::optional<std::string>& outputPath,
3592 int64_t* _aidl_return) {
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003593 ENFORCE_UID(AID_SYSTEM);
Alex Buynytskyy44036e22021-11-19 08:58:23 -08003594 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003595 CHECK_ARGUMENT_PATH(apkPath);
3596 CHECK_ARGUMENT_PATH(outputPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003597 LOCK_PACKAGE();
Jeff Sharkey90aff262016-12-12 14:28:24 -07003598
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003599 const char* apk_path = apkPath.c_str();
3600 const char* instruction_set = instructionSet.c_str();
Andreas Gampec5234092017-05-31 16:39:58 -07003601 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
Jeff Sharkey475c6f92016-12-07 10:37:27 -07003602
Calin Juravleea214ad2021-06-11 09:17:20 -07003603 *_aidl_return = delete_odex(apk_path, instruction_set, oat_dir);
3604 return *_aidl_return == -1 ? error() : ok();
Andreas Gampe3964da02016-09-09 17:07:04 -07003605}
3606
Calin Juravlebd968362017-01-25 01:17:17 -08003607binder::Status InstalldNativeService::reconcileSecondaryDexFile(
3608 const std::string& dexPath, const std::string& packageName, int32_t uid,
Jooyung Han149be4a2020-01-23 12:45:10 +09003609 const std::vector<std::string>& isas, const std::optional<std::string>& volumeUuid,
Calin Juravlebd968362017-01-25 01:17:17 -08003610 int32_t storage_flag, bool* _aidl_return) {
3611 ENFORCE_UID(AID_SYSTEM);
3612 CHECK_ARGUMENT_UUID(volumeUuid);
3613 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003614 CHECK_ARGUMENT_PATH(dexPath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003615 const auto userId = multiuser_get_user_id(uid);
3616 LOCK_PACKAGE_USER();
Jeff Sharkey53594302018-02-24 18:59:39 -07003617
Calin Juravlebd968362017-01-25 01:17:17 -08003618 bool result = android::installd::reconcile_secondary_dex_file(
3619 dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
3620 return result ? ok() : error();
3621}
3622
Alan Stokes753dc712017-10-16 10:56:00 +01003623binder::Status InstalldNativeService::hashSecondaryDexFile(
3624 const std::string& dexPath, const std::string& packageName, int32_t uid,
Jooyung Han149be4a2020-01-23 12:45:10 +09003625 const std::optional<std::string>& volumeUuid, int32_t storageFlag,
Alan Stokes753dc712017-10-16 10:56:00 +01003626 std::vector<uint8_t>* _aidl_return) {
3627 ENFORCE_UID(AID_SYSTEM);
3628 CHECK_ARGUMENT_UUID(volumeUuid);
3629 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003630 CHECK_ARGUMENT_PATH(dexPath);
Alan Stokes753dc712017-10-16 10:56:00 +01003631
3632 // mLock is not taken here since we will never modify the file system.
3633 // If a file is modified just as we are reading it this may result in an
3634 // anomalous hash, but that's ok.
3635 bool result = android::installd::hash_secondary_dex_file(
3636 dexPath, packageName, uid, volumeUuid, storageFlag, _aidl_return);
3637 return result ? ok() : error();
3638}
Shikha Malhotra976ae002022-02-26 15:39:53 +00003639/**
3640 * Returns true if ioctl feature (F2FS_IOC_FS{GET,SET}XATTR) is supported as
3641 * these were introduced in Linux 4.14, so kernel versions before that will fail
3642 * while setting project id attributes. Only when these features are enabled,
3643 * storage calculation using project_id is enabled
3644 */
3645bool check_if_ioctl_feature_is_supported() {
3646 bool result = false;
3647 auto temp_path = StringPrintf("%smisc/installd/ioctl_check", android_data_dir.c_str());
3648 if (access(temp_path.c_str(), F_OK) != 0) {
3649 int fd = open(temp_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644);
Shikha Malhotrac18afa82022-04-01 22:13:39 +00003650 result = set_quota_project_id(temp_path, 0, false) == 0;
Shikha Malhotra976ae002022-02-26 15:39:53 +00003651 close(fd);
3652 // delete the temp file
3653 remove(temp_path.c_str());
3654 }
3655 return result;
3656}
3657
3658binder::Status InstalldNativeService::setFirstBoot() {
3659 ENFORCE_UID(AID_SYSTEM);
3660 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3661 std::string uuid;
3662 if (GetOccupiedSpaceForProjectId(uuid, 0) != -1 && check_if_ioctl_feature_is_supported()) {
3663 auto first_boot_path =
3664 StringPrintf("%smisc/installd/using_project_ids", android_data_dir.c_str());
3665 if (access(first_boot_path.c_str(), F_OK) != 0) {
3666 close(open(first_boot_path.c_str(), O_CREAT | O_TRUNC | O_RDWR | O_CLOEXEC, 0644));
3667 }
3668 }
3669 return ok();
3670}
Alan Stokes753dc712017-10-16 10:56:00 +01003671
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003672binder::Status InstalldNativeService::invalidateMounts() {
3673 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003674 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003675
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003676 mStorageMounts.clear();
Risan5f308262018-10-26 12:06:58 -06003677
3678#if !BYPASS_QUOTA
3679 if (!InvalidateQuotaMounts()) {
3680 return error("Failed to read mounts");
3681 }
3682#endif
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003683
3684 std::ifstream in("/proc/mounts");
3685 if (!in.is_open()) {
3686 return error("Failed to read mounts");
3687 }
3688
3689 std::string source;
3690 std::string target;
3691 std::string ignored;
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003692 while (!in.eof()) {
3693 std::getline(in, source, ' ');
3694 std::getline(in, target, ' ');
3695 std::getline(in, ignored);
3696
Zim0ce832d2019-12-03 17:03:58 +00003697 if (android::base::GetBoolProperty(kFuseProp, false)) {
Zim1edb92a2020-01-09 08:48:00 +00003698 if (target.find(kMntFuse) == 0) {
Zim0ce832d2019-12-03 17:03:58 +00003699 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3700 mStorageMounts[source] = target;
3701 }
3702 } else {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003703#if !BYPASS_SDCARDFS
Zim1edb92a2020-01-09 08:48:00 +00003704 if (target.find(kMntSdcardfs) == 0) {
Zim0ce832d2019-12-03 17:03:58 +00003705 LOG(DEBUG) << "Found storage mount " << source << " at " << target;
3706 mStorageMounts[source] = target;
3707 }
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003708#endif
Zim0ce832d2019-12-03 17:03:58 +00003709 }
Jeff Sharkey66b1a122017-01-16 20:57:45 -07003710 }
3711 return ok();
3712}
3713
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003714// Mount volume's CE and DE storage to mirror
Ricky Wai2a4983f2020-02-07 14:25:45 +00003715binder::Status InstalldNativeService::tryMountDataMirror(
Jooyung Han149be4a2020-01-23 12:45:10 +09003716 const std::optional<std::string>& uuid) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003717 ENFORCE_UID(AID_SYSTEM);
3718 CHECK_ARGUMENT_UUID(uuid);
3719 if (!sAppDataIsolationEnabled) {
3720 return ok();
3721 }
3722 if (!uuid) {
3723 return error("Should not happen, mounting uuid == null");
3724 }
3725
3726 const char* uuid_ = uuid->c_str();
Ricky Wai2a4983f2020-02-07 14:25:45 +00003727
Alex Buynytskyy40c45ba2021-11-18 15:16:27 -08003728 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3729
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003730 std::string mirrorVolCePath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003731 if (fs_prepare_dir(mirrorVolCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003732 return error("Failed to create CE data mirror");
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003733 }
Ricky Wai2a4983f2020-02-07 14:25:45 +00003734
3735 std::string mirrorVolDePath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003736 if (fs_prepare_dir(mirrorVolDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003737 return error("Failed to create DE data mirror");
3738 }
3739
3740 std::string mirrorVolMiscCePath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003741 if (fs_prepare_dir(mirrorVolMiscCePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003742 return error("Failed to create CE misc mirror");
3743 }
3744
3745 std::string mirrorVolMiscDePath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
Eric Biggers5818c652023-06-14 00:53:20 +00003746 if (fs_prepare_dir(mirrorVolMiscDePath.c_str(), 0511, AID_SYSTEM, AID_SYSTEM) != 0) {
Sanjana Sunil691163d2022-03-28 19:15:54 +00003747 return error("Failed to create DE misc mirror");
Ricky Wai2a4983f2020-02-07 14:25:45 +00003748 }
3749
3750 auto cePath = StringPrintf("%s/user", create_data_path(uuid_).c_str());
3751 auto dePath = StringPrintf("%s/user_de", create_data_path(uuid_).c_str());
Sanjana Sunil691163d2022-03-28 19:15:54 +00003752 auto miscCePath = StringPrintf("%s/misc_ce", create_data_path(uuid_).c_str());
3753 auto miscDePath = StringPrintf("%s/misc_de", create_data_path(uuid_).c_str());
Ricky Wai2a4983f2020-02-07 14:25:45 +00003754
3755 if (access(cePath.c_str(), F_OK) != 0) {
3756 return error("Cannot access CE path: " + cePath);
3757 }
3758 if (access(dePath.c_str(), F_OK) != 0) {
3759 return error("Cannot access DE path: " + dePath);
3760 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003761 if (access(miscCePath.c_str(), F_OK) != 0) {
3762 return error("Cannot access misc CE path: " + cePath);
3763 }
3764 if (access(miscDePath.c_str(), F_OK) != 0) {
3765 return error("Cannot access misc DE path: " + dePath);
3766 }
Ricky Wai2a4983f2020-02-07 14:25:45 +00003767
3768 struct stat ceStat, mirrorCeStat;
3769 if (stat(cePath.c_str(), &ceStat) != 0) {
3770 return error("Failed to stat " + cePath);
3771 }
3772 if (stat(mirrorVolCePath.c_str(), &mirrorCeStat) != 0) {
3773 return error("Failed to stat " + mirrorVolCePath);
3774 }
3775
Eric Biggersab9ea462022-05-26 00:28:09 +00003776 if (mirrorCeStat.st_ino == ceStat.st_ino && mirrorCeStat.st_dev == ceStat.st_dev) {
Ricky Wai2a4983f2020-02-07 14:25:45 +00003777 // As it's being called by prepareUserStorage, it can be called multiple times.
3778 // Hence, we if we mount it already, we should skip it.
Eric Biggersab9ea462022-05-26 00:28:09 +00003779 LOG(INFO) << "CE dir is mounted already: " + cePath;
Ricky Wai2a4983f2020-02-07 14:25:45 +00003780 return ok();
3781 }
3782
3783 // Mount CE mirror
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003784 if (TEMP_FAILURE_RETRY(mount(cePath.c_str(), mirrorVolCePath.c_str(), NULL,
3785 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3786 return error("Failed to mount " + mirrorVolCePath);
3787 }
3788
3789 // Mount DE mirror
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003790 if (TEMP_FAILURE_RETRY(mount(dePath.c_str(), mirrorVolDePath.c_str(), NULL,
3791 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
3792 return error("Failed to mount " + mirrorVolDePath);
3793 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003794
3795 // Mount misc CE mirror
3796 if (TEMP_FAILURE_RETRY(mount(miscCePath.c_str(), mirrorVolMiscCePath.c_str(), NULL,
3797 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3798 nullptr)) == -1) {
3799 return error("Failed to mount " + mirrorVolMiscCePath);
3800 }
3801
3802 // Mount misc DE mirror
3803 if (TEMP_FAILURE_RETRY(mount(miscDePath.c_str(), mirrorVolMiscDePath.c_str(), NULL,
3804 MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
3805 nullptr)) == -1) {
3806 return error("Failed to mount " + mirrorVolMiscDePath);
3807 }
3808
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003809 return ok();
3810}
3811
3812// Unmount volume's CE and DE storage from mirror
3813binder::Status InstalldNativeService::onPrivateVolumeRemoved(
Jooyung Han149be4a2020-01-23 12:45:10 +09003814 const std::optional<std::string>& uuid) {
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003815 ENFORCE_UID(AID_SYSTEM);
3816 CHECK_ARGUMENT_UUID(uuid);
3817 if (!sAppDataIsolationEnabled) {
3818 return ok();
3819 }
3820 if (!uuid) {
3821 // It happens when private volume failed to mount.
3822 LOG(INFO) << "Ignore unmount uuid=null";
3823 return ok();
3824 }
3825 const char* uuid_ = uuid->c_str();
3826
3827 binder::Status res = ok();
3828
3829 std::string mirrorCeVolPath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
3830 std::string mirrorDeVolPath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
Sanjana Sunil691163d2022-03-28 19:15:54 +00003831 std::string mirrorMiscCeVolPath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
3832 std::string mirrorMiscDeVolPath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003833
Alex Buynytskyy40c45ba2021-11-18 15:16:27 -08003834 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3835
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003836 // Unmount CE storage
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003837 if (TEMP_FAILURE_RETRY(umount(mirrorCeVolPath.c_str())) != 0) {
3838 if (errno != ENOENT) {
3839 res = error(StringPrintf("Failed to umount %s %s", mirrorCeVolPath.c_str(),
3840 strerror(errno)));
3841 }
3842 }
3843 if (delete_dir_contents_and_dir(mirrorCeVolPath, true) != 0) {
3844 res = error("Failed to delete " + mirrorCeVolPath);
3845 }
3846
3847 // Unmount DE storage
3848 if (TEMP_FAILURE_RETRY(umount(mirrorDeVolPath.c_str())) != 0) {
3849 if (errno != ENOENT) {
3850 res = error(StringPrintf("Failed to umount %s %s", mirrorDeVolPath.c_str(),
3851 strerror(errno)));
3852 }
3853 }
3854 if (delete_dir_contents_and_dir(mirrorDeVolPath, true) != 0) {
3855 res = error("Failed to delete " + mirrorDeVolPath);
3856 }
Sanjana Sunil691163d2022-03-28 19:15:54 +00003857
3858 // Unmount misc CE storage
3859 if (TEMP_FAILURE_RETRY(umount(mirrorMiscCeVolPath.c_str())) != 0) {
3860 if (errno != ENOENT) {
3861 res = error(StringPrintf("Failed to umount %s %s", mirrorMiscCeVolPath.c_str(),
3862 strerror(errno)));
3863 }
3864 }
3865 if (delete_dir_contents_and_dir(mirrorMiscCeVolPath, true) != 0) {
3866 res = error("Failed to delete " + mirrorMiscCeVolPath);
3867 }
3868
3869 // Unmount misc DE storage
3870 if (TEMP_FAILURE_RETRY(umount(mirrorMiscDeVolPath.c_str())) != 0) {
3871 if (errno != ENOENT) {
3872 res = error(StringPrintf("Failed to umount %s %s", mirrorMiscDeVolPath.c_str(),
3873 strerror(errno)));
3874 }
3875 }
3876 if (delete_dir_contents_and_dir(mirrorMiscDeVolPath, true) != 0) {
3877 res = error("Failed to delete " + mirrorMiscDeVolPath);
3878 }
3879
Ricky Waiff9d3ea2019-11-18 18:18:24 +00003880 return res;
3881}
3882
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003883std::string InstalldNativeService::findDataMediaPath(
Jooyung Han149be4a2020-01-23 12:45:10 +09003884 const std::optional<std::string>& uuid, userid_t userid) {
Jeff Sharkeyd712f0c2017-05-03 11:36:42 -06003885 std::lock_guard<std::recursive_mutex> lock(mMountsLock);
3886 const char* uuid_ = uuid ? uuid->c_str() : nullptr;
3887 auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
3888 auto resolved = mStorageMounts[path];
3889 if (resolved.empty()) {
3890 LOG(WARNING) << "Failed to find storage mount for " << path;
3891 resolved = path;
3892 }
3893 return StringPrintf("%s/%u", resolved.c_str(), userid);
3894}
3895
Jeff Sharkey325b8c92017-02-21 10:00:53 -07003896binder::Status InstalldNativeService::isQuotaSupported(
Jooyung Han149be4a2020-01-23 12:45:10 +09003897 const std::optional<std::string>& uuid, bool* _aidl_return) {
3898 *_aidl_return = IsQuotaSupported(uuid.value_or(""));
Jeff Sharkey325b8c92017-02-21 10:00:53 -07003899 return ok();
3900}
3901
Calin Juravlebc5ab872018-01-18 22:32:58 -08003902binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
3903 int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
Jooyung Han149be4a2020-01-23 12:45:10 +09003904 const std::optional<std::string>& dexMetadata, bool* _aidl_return) {
Calin Juravlebc5ab872018-01-18 22:32:58 -08003905 ENFORCE_UID(AID_SYSTEM);
Steven Moreland3e543b92023-09-07 20:08:15 +00003906 ENFORCE_VALID_USER_OR_NULL(userId);
Calin Juravlebc5ab872018-01-18 22:32:58 -08003907 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
Jeff Sharkey53594302018-02-24 18:59:39 -07003908 CHECK_ARGUMENT_PATH(codePath);
Alex Buynytskyy4fef8862021-11-21 16:09:33 -08003909 LOCK_PACKAGE_USER();
Calin Juravlebc5ab872018-01-18 22:32:58 -08003910
3911 *_aidl_return = prepare_app_profile(packageName, userId, appId, profileName, codePath,
3912 dexMetadata);
3913 return ok();
3914}
3915
Narayan Kamath28ab93b2019-05-15 18:29:44 +01003916binder::Status InstalldNativeService::migrateLegacyObbData() {
3917 ENFORCE_UID(AID_SYSTEM);
3918 // NOTE: The lint warning doesn't apply to the use of system(3) with
3919 // absolute parse and no command line arguments.
Cole Faustf6cd58a2022-09-01 17:34:36 -07003920 if (system("/system/bin/migrate_legacy_obb_data") != 0) { // NOLINT(cert-env33-c)
Narayan Kamath28ab93b2019-05-15 18:29:44 +01003921 LOG(ERROR) << "Unable to migrate legacy obb data";
3922 }
3923
3924 return ok();
3925}
3926
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003927binder::Status InstalldNativeService::cleanupInvalidPackageDirs(
3928 const std::optional<std::string>& uuid, int32_t userId, int32_t flags) {
Steven Moreland36945362023-07-05 20:29:10 +00003929 ENFORCE_VALID_USER(userId);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003930 const char* uuid_cstr = uuid ? uuid->c_str() : nullptr;
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003931
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003932 if (flags & FLAG_STORAGE_CE) {
3933 auto ce_path = create_data_user_ce_path(uuid_cstr, userId);
3934 cleanup_invalid_package_dirs_under_path(ce_path);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00003935 auto sdksandbox_ce_path =
3936 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/true, userId);
3937 cleanup_invalid_package_dirs_under_path(sdksandbox_ce_path);
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003938 }
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003939
3940 if (flags & FLAG_STORAGE_DE) {
3941 auto de_path = create_data_user_de_path(uuid_cstr, userId);
3942 cleanup_invalid_package_dirs_under_path(de_path);
Rishabh Singhe84b0b12022-02-02 20:56:13 +00003943 auto sdksandbox_de_path =
3944 create_data_misc_sdk_sandbox_path(uuid_cstr, /*isCeData=*/false, userId);
3945 cleanup_invalid_package_dirs_under_path(sdksandbox_de_path);
Alex Buynytskyy58a73092022-02-14 13:15:53 -08003946 }
3947
Alex Buynytskyy038a19b2022-02-09 19:51:52 -08003948 return ok();
3949}
3950
Jiakai Zhangf515a1b2022-02-23 18:33:26 +00003951binder::Status InstalldNativeService::getOdexVisibility(
3952 const std::string& packageName, const std::string& apkPath,
3953 const std::string& instructionSet, const std::optional<std::string>& outputPath,
3954 int32_t* _aidl_return) {
3955 ENFORCE_UID(AID_SYSTEM);
3956 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
3957 CHECK_ARGUMENT_PATH(apkPath);
3958 CHECK_ARGUMENT_PATH(outputPath);
3959 LOCK_PACKAGE();
3960
3961 const char* apk_path = apkPath.c_str();
3962 const char* instruction_set = instructionSet.c_str();
3963 const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
3964
3965 *_aidl_return = get_odex_visibility(apk_path, instruction_set, oat_dir);
3966 return *_aidl_return == -1 ? error() : ok();
3967}
3968
Victor Hsiehc7ab5642023-07-28 15:07:55 -07003969// Creates an auth token to be used in enableFsverity. This token is really to store a proof that
3970// the caller can write to a file, represented by the authFd. Effectively, system_server as the
3971// attacker-in-the-middle cannot enable fs-verity on arbitrary app files. If the FD is not writable,
3972// return null.
3973//
3974// appUid and userId are passed for additional ownership check, such that one app can not be
3975// authenticated for another app's file. These parameters are assumed trusted for this purpose of
3976// consistency check.
3977//
3978// Notably, creating the token allows us to manage the writable FD easily during enableFsverity.
3979// Since enabling fs-verity to a file requires no outstanding writable FD, passing the authFd to the
3980// server allows the server to hold the only reference (as long as the client app doesn't).
3981binder::Status InstalldNativeService::createFsveritySetupAuthToken(
3982 const ParcelFileDescriptor& authFd, int32_t appUid, int32_t userId,
3983 sp<IFsveritySetupAuthToken>* _aidl_return) {
3984 CHECK_ARGUMENT_UID_IN_APP_RANGE(appUid);
3985 ENFORCE_VALID_USER(userId);
3986
3987 auto token = sp<FsveritySetupAuthToken>::make();
3988 binder::Status status = token->authenticate(authFd, appUid, userId);
3989 if (!status.isOk()) {
3990 return status;
3991 }
3992 *_aidl_return = token;
3993 return ok();
3994}
3995
3996// Enables fs-verity for filePath, which must be an absolute path and the same inode as in the auth
3997// token previously returned from createFsveritySetupAuthToken, and owned by the app uid. As
3998// installd is more privileged than its client / system server, we attempt to limit what a
3999// (compromised) client can do.
4000//
4001// The reason for this app request to go through installd is to avoid exposing a risky area (PKCS#7
4002// signature verification) in the kernel to the app as an attack surface (it can't be system server
4003// because it can't override DAC and manipulate app files). Note that we should be able to drop
4004// these hops and simply the app calls the ioctl, once all upgrading devices run with a kernel
4005// without fs-verity built-in signature (https://r.android.com/2650402).
4006binder::Status InstalldNativeService::enableFsverity(const sp<IFsveritySetupAuthToken>& authToken,
4007 const std::string& filePath,
4008 const std::string& packageName,
4009 int32_t* _aidl_return) {
4010 ENFORCE_UID(AID_SYSTEM);
4011 CHECK_ARGUMENT_PATH(filePath);
4012 CHECK_ARGUMENT_PACKAGE_NAME(packageName);
4013 LOCK_PACKAGE();
4014 if (authToken == nullptr) {
4015 return exception(binder::Status::EX_ILLEGAL_ARGUMENT, "Received a null auth token");
4016 }
4017
4018 // Authenticate to check the targeting file is the same inode as the authFd.
4019 sp<IBinder> authTokenBinder = IInterface::asBinder(authToken)->localBinder();
4020 if (authTokenBinder == nullptr) {
4021 return exception(binder::Status::EX_SECURITY, "Received a non-local auth token");
4022 }
4023 auto authTokenInstance = sp<FsveritySetupAuthToken>::cast(authTokenBinder);
4024 unique_fd rfd(open(filePath.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
4025 struct stat stFromPath;
4026 if (fstat(rfd.get(), &stFromPath) < 0) {
4027 *_aidl_return = errno;
4028 return ok();
4029 }
4030 if (!authTokenInstance->isSameStat(stFromPath)) {
4031 LOG(DEBUG) << "FD authentication failed";
4032 *_aidl_return = EPERM;
4033 return ok();
4034 }
4035
4036 fsverity_enable_arg arg = {};
4037 arg.version = 1;
4038 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
4039 arg.block_size = 4096;
4040 if (ioctl(rfd.get(), FS_IOC_ENABLE_VERITY, &arg) < 0) {
4041 *_aidl_return = errno;
4042 } else {
4043 *_aidl_return = 0;
4044 }
4045 return ok();
4046}
4047
Andreas Gampe02d0de52015-11-11 20:43:16 -08004048} // namespace installd
4049} // namespace android