OSDN Git Service

Merge "Support profile guided compilation for secondary dex files" am: cb2e477f14...
[android-x86/frameworks-native.git] / cmds / installd / InstalldNativeService.cpp
1 /*
2 ** Copyright 2008, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 **     http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16
17 #include "InstalldNativeService.h"
18
19 #define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
20
21 #include <errno.h>
22 #include <inttypes.h>
23 #include <fstream>
24 #include <fts.h>
25 #include <regex>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/capability.h>
29 #include <sys/file.h>
30 #include <sys/resource.h>
31 #include <sys/quota.h>
32 #include <sys/stat.h>
33 #include <sys/statvfs.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <sys/xattr.h>
37 #include <unistd.h>
38
39 #include <android-base/logging.h>
40 #include <android-base/stringprintf.h>
41 #include <android-base/strings.h>
42 #include <android-base/unique_fd.h>
43 #include <cutils/fs.h>
44 #include <cutils/properties.h>
45 #include <cutils/sched_policy.h>
46 #include <log/log.h>               // TODO: Move everything to base/logging.
47 #include <logwrap/logwrap.h>
48 #include <private/android_filesystem_config.h>
49 #include <selinux/android.h>
50 #include <system/thread_defs.h>
51 #include <utils/Trace.h>
52
53 #include "dexopt.h"
54 #include "globals.h"
55 #include "installd_deps.h"
56 #include "otapreopt_utils.h"
57 #include "utils.h"
58
59 #include "CacheTracker.h"
60 #include "MatchExtensionGen.h"
61
62 #ifndef LOG_TAG
63 #define LOG_TAG "installd"
64 #endif
65
66 using android::base::StringPrintf;
67 using std::endl;
68
69 namespace android {
70 namespace installd {
71
72 static constexpr const char* kCpPath = "/system/bin/cp";
73 static constexpr const char* kXattrDefault = "user.default";
74
75 static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
76
77 static constexpr const char* PKG_LIB_POSTFIX = "/lib";
78 static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
79 static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
80
81 static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
82 static constexpr const char* IDMAP_SUFFIX = "@idmap";
83
84 // NOTE: keep in sync with Installer
85 static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
86 static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
87 static constexpr int FLAG_USE_QUOTA = 1 << 12;
88 static constexpr int FLAG_FREE_CACHE_V2 = 1 << 13;
89 static constexpr int FLAG_FREE_CACHE_V2_DEFY_QUOTA = 1 << 14;
90 static constexpr int FLAG_FREE_CACHE_NOOP = 1 << 15;
91
92 namespace {
93
94 constexpr const char* kDump = "android.permission.DUMP";
95
96 static binder::Status ok() {
97     return binder::Status::ok();
98 }
99
100 static binder::Status exception(uint32_t code, const std::string& msg) {
101     return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
102 }
103
104 static binder::Status error() {
105     return binder::Status::fromServiceSpecificError(errno);
106 }
107
108 static binder::Status error(const std::string& msg) {
109     PLOG(ERROR) << msg;
110     return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
111 }
112
113 static binder::Status error(uint32_t code, const std::string& msg) {
114     LOG(ERROR) << msg << " (" << code << ")";
115     return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
116 }
117
118 binder::Status checkPermission(const char* permission) {
119     pid_t pid;
120     uid_t uid;
121
122     if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
123             reinterpret_cast<int32_t*>(&uid))) {
124         return ok();
125     } else {
126         return exception(binder::Status::EX_SECURITY,
127                 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
128     }
129 }
130
131 binder::Status checkUid(uid_t expectedUid) {
132     uid_t uid = IPCThreadState::self()->getCallingUid();
133     if (uid == expectedUid || uid == AID_ROOT) {
134         return ok();
135     } else {
136         return exception(binder::Status::EX_SECURITY,
137                 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
138     }
139 }
140
141 binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
142     if (!uuid || is_valid_filename(*uuid)) {
143         return ok();
144     } else {
145         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
146                 StringPrintf("UUID %s is malformed", uuid->c_str()));
147     }
148 }
149
150 binder::Status checkArgumentPackageName(const std::string& packageName) {
151     if (is_valid_package_name(packageName.c_str())) {
152         return ok();
153     } else {
154         return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
155                 StringPrintf("Package name %s is malformed", packageName.c_str()));
156     }
157 }
158
159 #define ENFORCE_UID(uid) {                                  \
160     binder::Status status = checkUid((uid));                \
161     if (!status.isOk()) {                                   \
162         return status;                                      \
163     }                                                       \
164 }
165
166 #define CHECK_ARGUMENT_UUID(uuid) {                         \
167     binder::Status status = checkArgumentUuid((uuid));      \
168     if (!status.isOk()) {                                   \
169         return status;                                      \
170     }                                                       \
171 }
172
173 #define CHECK_ARGUMENT_PACKAGE_NAME(packageName) {          \
174     binder::Status status =                                 \
175             checkArgumentPackageName((packageName));        \
176     if (!status.isOk()) {                                   \
177         return status;                                      \
178     }                                                       \
179 }
180
181 }  // namespace
182
183 status_t InstalldNativeService::start() {
184     IPCThreadState::self()->disableBackgroundScheduling(true);
185     status_t ret = BinderService<InstalldNativeService>::publish();
186     if (ret != android::OK) {
187         return ret;
188     }
189     sp<ProcessState> ps(ProcessState::self());
190     ps->startThreadPool();
191     ps->giveThreadPoolName();
192     return android::OK;
193 }
194
195 status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
196     auto out = std::fstream(StringPrintf("/proc/self/fd/%d", fd));
197     const binder::Status dump_permission = checkPermission(kDump);
198     if (!dump_permission.isOk()) {
199         out << dump_permission.toString8() << endl;
200         return PERMISSION_DENIED;
201     }
202     std::lock_guard<std::recursive_mutex> lock(mLock);
203
204     out << "installd is happy!" << endl;
205
206     {
207         std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
208         out << endl << "Devices with quota support:" << endl;
209         for (const auto& n : mQuotaDevices) {
210             out << "    " << n.first << " = " << n.second << endl;
211         }
212     }
213
214     {
215         std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
216         out << endl << "Per-UID cache quotas:" << endl;
217         for (const auto& n : mCacheQuotas) {
218             out << "    " << n.first << " = " << n.second << endl;
219         }
220     }
221
222     out << endl;
223     out.flush();
224
225     return NO_ERROR;
226 }
227
228 /**
229  * Perform restorecon of the given path, but only perform recursive restorecon
230  * if the label of that top-level file actually changed.  This can save us
231  * significant time by avoiding no-op traversals of large filesystem trees.
232  */
233 static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
234         bool existing) {
235     int res = 0;
236     char* before = nullptr;
237     char* after = nullptr;
238
239     // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
240     // libselinux. Not needed here.
241
242     if (lgetfilecon(path.c_str(), &before) < 0) {
243         PLOG(ERROR) << "Failed before getfilecon for " << path;
244         goto fail;
245     }
246     if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
247         PLOG(ERROR) << "Failed top-level restorecon for " << path;
248         goto fail;
249     }
250     if (lgetfilecon(path.c_str(), &after) < 0) {
251         PLOG(ERROR) << "Failed after getfilecon for " << path;
252         goto fail;
253     }
254
255     // If the initial top-level restorecon above changed the label, then go
256     // back and restorecon everything recursively
257     if (strcmp(before, after)) {
258         if (existing) {
259             LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
260                     << path << "; running recursive restorecon";
261         }
262         if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
263                 SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
264             PLOG(ERROR) << "Failed recursive restorecon for " << path;
265             goto fail;
266         }
267     }
268
269     goto done;
270 fail:
271     res = -1;
272 done:
273     free(before);
274     free(after);
275     return res;
276 }
277
278 static int restorecon_app_data_lazy(const std::string& parent, const char* name,
279         const std::string& seInfo, uid_t uid, bool existing) {
280     return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
281             existing);
282 }
283
284 static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
285     if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
286         PLOG(ERROR) << "Failed to prepare " << path;
287         return -1;
288     }
289     return 0;
290 }
291
292 binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
293         const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
294         const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
295     ENFORCE_UID(AID_SYSTEM);
296     CHECK_ARGUMENT_UUID(uuid);
297     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
298     std::lock_guard<std::recursive_mutex> lock(mLock);
299
300     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
301     const char* pkgname = packageName.c_str();
302
303     // Assume invalid inode unless filled in below
304     if (_aidl_return != nullptr) *_aidl_return = -1;
305
306     int32_t uid = multiuser_get_uid(userId, appId);
307     int32_t cacheGid = multiuser_get_cache_gid(userId, appId);
308     mode_t targetMode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
309
310     // If UID doesn't have a specific cache GID, use UID value
311     if (cacheGid == -1) {
312         cacheGid = uid;
313     }
314
315     if (flags & FLAG_STORAGE_CE) {
316         auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
317         bool existing = (access(path.c_str(), F_OK) == 0);
318
319         if (prepare_app_dir(path, targetMode, uid) ||
320                 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
321                 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
322             return error("Failed to prepare " + path);
323         }
324
325         // Consider restorecon over contents if label changed
326         if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
327                 restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
328                 restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
329             return error("Failed to restorecon " + path);
330         }
331
332         // Remember inode numbers of cache directories so that we can clear
333         // contents while CE storage is locked
334         if (write_path_inode(path, "cache", kXattrInodeCache) ||
335                 write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
336             return error("Failed to write_path_inode for " + path);
337         }
338
339         // And return the CE inode of the top-level data directory so we can
340         // clear contents while CE storage is locked
341         if ((_aidl_return != nullptr)
342                 && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
343             return error("Failed to get_path_inode for " + path);
344         }
345     }
346     if (flags & FLAG_STORAGE_DE) {
347         auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
348         bool existing = (access(path.c_str(), F_OK) == 0);
349
350         if (prepare_app_dir(path, targetMode, uid) ||
351                 prepare_app_cache_dir(path, "cache", 02771, uid, cacheGid) ||
352                 prepare_app_cache_dir(path, "code_cache", 02771, uid, cacheGid)) {
353             return error("Failed to prepare " + path);
354         }
355
356         // Consider restorecon over contents if label changed
357         if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
358             return error("Failed to restorecon " + path);
359         }
360
361         if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
362             const std::string profile_dir =
363                     create_primary_current_profile_package_dir_path(userId, pkgname);
364             // read-write-execute only for the app user.
365             if (fs_prepare_dir_strict(profile_dir.c_str(), 0700, uid, uid) != 0) {
366                 return error("Failed to prepare " + profile_dir);
367             }
368             const std::string profile_file = create_current_profile_path(userId, pkgname,
369                     /*is_secondary_dex*/false);
370             // read-write only for the app user.
371             if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
372                 return error("Failed to prepare " + profile_file);
373             }
374             const std::string ref_profile_path =
375                     create_primary_reference_profile_package_dir_path(pkgname);
376             // dex2oat/profman runs under the shared app gid and it needs to read/write reference
377             // profiles.
378             int shared_app_gid = multiuser_get_shared_gid(0, appId);
379             if ((shared_app_gid != -1) && fs_prepare_dir_strict(
380                     ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
381                 return error("Failed to prepare " + ref_profile_path);
382             }
383         }
384     }
385     return ok();
386 }
387
388 binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
389         const std::string& packageName, int32_t userId, int32_t flags) {
390     ENFORCE_UID(AID_SYSTEM);
391     CHECK_ARGUMENT_UUID(uuid);
392     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
393     std::lock_guard<std::recursive_mutex> lock(mLock);
394
395     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
396     const char* pkgname = packageName.c_str();
397
398     // This method only exists to upgrade system apps that have requested
399     // forceDeviceEncrypted, so their default storage always lives in a
400     // consistent location.  This only works on non-FBE devices, since we
401     // never want to risk exposing data on a device with real CE/DE storage.
402
403     auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
404     auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
405
406     // If neither directory is marked as default, assume CE is default
407     if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
408             && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
409         if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
410             return error("Failed to mark default storage " + ce_path);
411         }
412     }
413
414     // Migrate default data location if needed
415     auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
416     auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
417
418     if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
419         LOG(WARNING) << "Requested default storage " << target
420                 << " is not active; migrating from " << source;
421         if (delete_dir_contents_and_dir(target) != 0) {
422             return error("Failed to delete " + target);
423         }
424         if (rename(source.c_str(), target.c_str()) != 0) {
425             return error("Failed to rename " + source + " to " + target);
426         }
427     }
428
429     return ok();
430 }
431
432
433 binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
434     ENFORCE_UID(AID_SYSTEM);
435     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
436     std::lock_guard<std::recursive_mutex> lock(mLock);
437
438     binder::Status res = ok();
439     if (!clear_primary_reference_profile(packageName)) {
440         res = error("Failed to clear reference profile for " + packageName);
441     }
442     if (!clear_primary_current_profiles(packageName)) {
443         res = error("Failed to clear current profiles for " + packageName);
444     }
445     return res;
446 }
447
448 binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
449         const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
450     ENFORCE_UID(AID_SYSTEM);
451     CHECK_ARGUMENT_UUID(uuid);
452     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
453     std::lock_guard<std::recursive_mutex> lock(mLock);
454
455     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
456     const char* pkgname = packageName.c_str();
457
458     binder::Status res = ok();
459     if (flags & FLAG_STORAGE_CE) {
460         auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
461         if (flags & FLAG_CLEAR_CACHE_ONLY) {
462             path = read_path_inode(path, "cache", kXattrInodeCache);
463         } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
464             path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
465         }
466         if (access(path.c_str(), F_OK) == 0) {
467             if (delete_dir_contents(path) != 0) {
468                 res = error("Failed to delete contents of " + path);
469             }
470         }
471     }
472     if (flags & FLAG_STORAGE_DE) {
473         std::string suffix = "";
474         bool only_cache = false;
475         if (flags & FLAG_CLEAR_CACHE_ONLY) {
476             suffix = CACHE_DIR_POSTFIX;
477             only_cache = true;
478         } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
479             suffix = CODE_CACHE_DIR_POSTFIX;
480             only_cache = true;
481         }
482
483         auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
484         if (access(path.c_str(), F_OK) == 0) {
485             if (delete_dir_contents(path) != 0) {
486                 res = error("Failed to delete contents of " + path);
487             }
488         }
489         if (!only_cache) {
490             if (!clear_primary_current_profile(packageName, userId)) {
491                 res = error("Failed to clear current profile for " + packageName);
492             }
493         }
494     }
495     return res;
496 }
497
498 static int destroy_app_reference_profile(const std::string& pkgname) {
499     return delete_dir_contents_and_dir(
500         create_primary_reference_profile_package_dir_path(pkgname),
501         /*ignore_if_missing*/ true);
502 }
503
504 static int destroy_app_current_profiles(const std::string& pkgname, userid_t userid) {
505     return delete_dir_contents_and_dir(
506         create_primary_current_profile_package_dir_path(userid, pkgname),
507         /*ignore_if_missing*/ true);
508 }
509
510 binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
511     ENFORCE_UID(AID_SYSTEM);
512     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
513     std::lock_guard<std::recursive_mutex> lock(mLock);
514
515     binder::Status res = ok();
516     std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
517     for (auto user : users) {
518         if (destroy_app_current_profiles(packageName, user) != 0) {
519             res = error("Failed to destroy current profiles for " + packageName);
520         }
521     }
522     if (destroy_app_reference_profile(packageName) != 0) {
523         res = error("Failed to destroy reference profile for " + packageName);
524     }
525     return res;
526 }
527
528 binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
529         const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
530     ENFORCE_UID(AID_SYSTEM);
531     CHECK_ARGUMENT_UUID(uuid);
532     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
533     std::lock_guard<std::recursive_mutex> lock(mLock);
534
535     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
536     const char* pkgname = packageName.c_str();
537
538     binder::Status res = ok();
539     if (flags & FLAG_STORAGE_CE) {
540         auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
541         if (delete_dir_contents_and_dir(path) != 0) {
542             res = error("Failed to delete " + path);
543         }
544     }
545     if (flags & FLAG_STORAGE_DE) {
546         auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
547         if (delete_dir_contents_and_dir(path) != 0) {
548             res = error("Failed to delete " + path);
549         }
550         destroy_app_current_profiles(packageName, userId);
551         // TODO(calin): If the package is still installed by other users it's probably
552         // beneficial to keep the reference profile around.
553         // Verify if it's ok to do that.
554         destroy_app_reference_profile(packageName);
555     }
556     return res;
557 }
558
559 binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
560         const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
561         const std::string& dataAppName, int32_t appId, const std::string& seInfo,
562         int32_t targetSdkVersion) {
563     ENFORCE_UID(AID_SYSTEM);
564     CHECK_ARGUMENT_UUID(fromUuid);
565     CHECK_ARGUMENT_UUID(toUuid);
566     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
567     std::lock_guard<std::recursive_mutex> lock(mLock);
568
569     const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
570     const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
571     const char* package_name = packageName.c_str();
572     const char* data_app_name = dataAppName.c_str();
573
574     binder::Status res = ok();
575     std::vector<userid_t> users = get_known_users(from_uuid);
576
577     // Copy app
578     {
579         auto from = create_data_app_package_path(from_uuid, data_app_name);
580         auto to = create_data_app_package_path(to_uuid, data_app_name);
581         auto to_parent = create_data_app_path(to_uuid);
582
583         char *argv[] = {
584             (char*) kCpPath,
585             (char*) "-F", /* delete any existing destination file first (--remove-destination) */
586             (char*) "-p", /* preserve timestamps, ownership, and permissions */
587             (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
588             (char*) "-P", /* Do not follow symlinks [default] */
589             (char*) "-d", /* don't dereference symlinks */
590             (char*) from.c_str(),
591             (char*) to_parent.c_str()
592         };
593
594         LOG(DEBUG) << "Copying " << from << " to " << to;
595         int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
596         if (rc != 0) {
597             res = error(rc, "Failed copying " + from + " to " + to);
598             goto fail;
599         }
600
601         if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
602             res = error("Failed to restorecon " + to);
603             goto fail;
604         }
605     }
606
607     // Copy private data for all known users
608     for (auto user : users) {
609
610         // Data source may not exist for all users; that's okay
611         auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
612         if (access(from_ce.c_str(), F_OK) != 0) {
613             LOG(INFO) << "Missing source " << from_ce;
614             continue;
615         }
616
617         if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
618                 seInfo, targetSdkVersion, nullptr).isOk()) {
619             res = error("Failed to create package target");
620             goto fail;
621         }
622
623         char *argv[] = {
624             (char*) kCpPath,
625             (char*) "-F", /* delete any existing destination file first (--remove-destination) */
626             (char*) "-p", /* preserve timestamps, ownership, and permissions */
627             (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
628             (char*) "-P", /* Do not follow symlinks [default] */
629             (char*) "-d", /* don't dereference symlinks */
630             nullptr,
631             nullptr
632         };
633
634         {
635             auto from = create_data_user_de_package_path(from_uuid, user, package_name);
636             auto to = create_data_user_de_path(to_uuid, user);
637             argv[6] = (char*) from.c_str();
638             argv[7] = (char*) to.c_str();
639
640             LOG(DEBUG) << "Copying " << from << " to " << to;
641             int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
642             if (rc != 0) {
643                 res = error(rc, "Failed copying " + from + " to " + to);
644                 goto fail;
645             }
646         }
647         {
648             auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
649             auto to = create_data_user_ce_path(to_uuid, user);
650             argv[6] = (char*) from.c_str();
651             argv[7] = (char*) to.c_str();
652
653             LOG(DEBUG) << "Copying " << from << " to " << to;
654             int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
655             if (rc != 0) {
656                 res = error(rc, "Failed copying " + from + " to " + to);
657                 goto fail;
658             }
659         }
660
661         if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
662                 appId, seInfo).isOk()) {
663             res = error("Failed to restorecon");
664             goto fail;
665         }
666     }
667
668     // We let the framework scan the new location and persist that before
669     // deleting the data in the old location; this ordering ensures that
670     // we can recover from things like battery pulls.
671     return ok();
672
673 fail:
674     // Nuke everything we might have already copied
675     {
676         auto to = create_data_app_package_path(to_uuid, data_app_name);
677         if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
678             LOG(WARNING) << "Failed to rollback " << to;
679         }
680     }
681     for (auto user : users) {
682         {
683             auto to = create_data_user_de_package_path(to_uuid, user, package_name);
684             if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
685                 LOG(WARNING) << "Failed to rollback " << to;
686             }
687         }
688         {
689             auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
690             if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
691                 LOG(WARNING) << "Failed to rollback " << to;
692             }
693         }
694     }
695     return res;
696 }
697
698 binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
699         int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
700     ENFORCE_UID(AID_SYSTEM);
701     CHECK_ARGUMENT_UUID(uuid);
702     std::lock_guard<std::recursive_mutex> lock(mLock);
703
704     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
705     if (flags & FLAG_STORAGE_DE) {
706         if (uuid_ == nullptr) {
707             if (ensure_config_user_dirs(userId) != 0) {
708                 return error(StringPrintf("Failed to ensure dirs for %d", userId));
709             }
710         }
711     }
712     return ok();
713 }
714
715 binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
716         int32_t userId, int32_t flags) {
717     ENFORCE_UID(AID_SYSTEM);
718     CHECK_ARGUMENT_UUID(uuid);
719     std::lock_guard<std::recursive_mutex> lock(mLock);
720
721     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
722     binder::Status res = ok();
723     if (flags & FLAG_STORAGE_DE) {
724         auto path = create_data_user_de_path(uuid_, userId);
725         if (delete_dir_contents_and_dir(path, true) != 0) {
726             res = error("Failed to delete " + path);
727         }
728         if (uuid_ == nullptr) {
729             path = create_data_misc_legacy_path(userId);
730             if (delete_dir_contents_and_dir(path, true) != 0) {
731                 res = error("Failed to delete " + path);
732             }
733             path = create_primary_cur_profile_dir_path(userId);
734             if (delete_dir_contents_and_dir(path, true) != 0) {
735                 res = error("Failed to delete " + path);
736             }
737         }
738     }
739     if (flags & FLAG_STORAGE_CE) {
740         auto path = create_data_user_ce_path(uuid_, userId);
741         if (delete_dir_contents_and_dir(path, true) != 0) {
742             res = error("Failed to delete " + path);
743         }
744         path = create_data_media_path(uuid_, userId);
745         if (delete_dir_contents_and_dir(path, true) != 0) {
746             res = error("Failed to delete " + path);
747         }
748     }
749     return res;
750 }
751
752 /* Try to ensure free_size bytes of storage are available.
753  * Returns 0 on success.
754  * This is rather simple-minded because doing a full LRU would
755  * be potentially memory-intensive, and without atime it would
756  * also require that apps constantly modify file metadata even
757  * when just reading from the cache, which is pretty awful.
758  */
759 binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
760         int64_t freeStorageSize, int32_t flags) {
761     ENFORCE_UID(AID_SYSTEM);
762     CHECK_ARGUMENT_UUID(uuid);
763     std::lock_guard<std::recursive_mutex> lock(mLock);
764
765     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
766     auto data_path = create_data_path(uuid_);
767     auto device = findQuotaDeviceForUuid(uuid);
768     auto noop = (flags & FLAG_FREE_CACHE_NOOP);
769
770     int64_t free = data_disk_free(data_path);
771     int64_t needed = freeStorageSize - free;
772     if (free < 0) {
773         return error("Failed to determine free space for " + data_path);
774     } else if (free >= freeStorageSize) {
775         return ok();
776     }
777
778     LOG(DEBUG) << "Found " << data_path << " with " << free << " free; caller requested "
779             << freeStorageSize;
780
781     if (flags & FLAG_FREE_CACHE_V2) {
782         // This new cache strategy fairly removes files from UIDs by deleting
783         // files from the UIDs which are most over their allocated quota
784
785         // 1. Create trackers for every known UID
786         ATRACE_BEGIN("create");
787         std::unordered_map<uid_t, std::shared_ptr<CacheTracker>> trackers;
788         for (auto user : get_known_users(uuid_)) {
789             FTS *fts;
790             FTSENT *p;
791             char *argv[] = {
792                     (char*) create_data_user_ce_path(uuid_, user).c_str(),
793                     (char*) create_data_user_de_path(uuid_, user).c_str(),
794                     nullptr
795             };
796             if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
797                 return error("Failed to fts_open");
798             }
799             while ((p = fts_read(fts)) != NULL) {
800                 if (p->fts_info == FTS_D && p->fts_level == 1) {
801                     uid_t uid = p->fts_statp->st_uid;
802                     auto search = trackers.find(uid);
803                     if (search != trackers.end()) {
804                         search->second->addDataPath(p->fts_path);
805                     } else {
806                         auto tracker = std::shared_ptr<CacheTracker>(new CacheTracker(
807                                 multiuser_get_user_id(uid), multiuser_get_app_id(uid), device));
808                         tracker->addDataPath(p->fts_path);
809                         {
810                             std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
811                             tracker->cacheQuota = mCacheQuotas[uid];
812                         }
813                         if (tracker->cacheQuota == 0) {
814                             LOG(WARNING) << "UID " << uid << " has no cache quota; assuming 64MB";
815                             tracker->cacheQuota = 67108864;
816                         }
817                         trackers[uid] = tracker;
818                     }
819                     fts_set(fts, p, FTS_SKIP);
820                 }
821             }
822             fts_close(fts);
823         }
824         ATRACE_END();
825
826         // 2. Populate tracker stats and insert into priority queue
827         ATRACE_BEGIN("populate");
828         auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
829             return (left->getCacheRatio() < right->getCacheRatio());
830         };
831         std::priority_queue<std::shared_ptr<CacheTracker>,
832                 std::vector<std::shared_ptr<CacheTracker>>, decltype(cmp)> queue(cmp);
833         for (const auto& it : trackers) {
834             it.second->loadStats();
835             queue.push(it.second);
836         }
837         ATRACE_END();
838
839         // 3. Bounce across the queue, freeing items from whichever tracker is
840         // the most over their assigned quota
841         ATRACE_BEGIN("bounce");
842         std::shared_ptr<CacheTracker> active;
843         while (active || !queue.empty()) {
844             // Only look at apps under quota when explicitly requested
845             if (active && (active->getCacheRatio() < 10000)
846                     && !(flags & FLAG_FREE_CACHE_V2_DEFY_QUOTA)) {
847                 LOG(DEBUG) << "Active ratio " << active->getCacheRatio()
848                         << " isn't over quota, and defy not requested";
849                 break;
850             }
851
852             // Find the best tracker to work with; this might involve swapping
853             // if the active tracker is no longer the most over quota
854             bool nextBetter = active && !queue.empty()
855                     && active->getCacheRatio() < queue.top()->getCacheRatio();
856             if (!active || nextBetter) {
857                 if (active) {
858                     // Current tracker still has items, so we'll consider it
859                     // again later once it bubbles up to surface
860                     queue.push(active);
861                 }
862                 active = queue.top(); queue.pop();
863                 active->ensureItems();
864                 continue;
865             }
866
867             // If no items remain, go find another tracker
868             if (active->items.empty()) {
869                 active = nullptr;
870                 continue;
871             } else {
872                 auto item = active->items.back();
873                 active->items.pop_back();
874
875                 LOG(DEBUG) << "Purging " << item->toString() << " from " << active->toString();
876                 if (!noop) {
877                     item->purge();
878                 }
879                 active->cacheUsed -= item->size;
880                 needed -= item->size;
881             }
882
883             // Verify that we're actually done before bailing, since sneaky
884             // apps might be using hardlinks
885             if (needed <= 0) {
886                 free = data_disk_free(data_path);
887                 needed = freeStorageSize - free;
888                 if (needed <= 0) {
889                     break;
890                 } else {
891                     LOG(WARNING) << "Expected to be done but still need " << needed;
892                 }
893             }
894         }
895         ATRACE_END();
896
897     } else {
898         ATRACE_BEGIN("start");
899         cache_t* cache = start_cache_collection();
900         ATRACE_END();
901
902         ATRACE_BEGIN("add");
903         for (auto user : get_known_users(uuid_)) {
904             add_cache_files(cache, create_data_user_ce_path(uuid_, user));
905             add_cache_files(cache, create_data_user_de_path(uuid_, user));
906             add_cache_files(cache,
907                     StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
908         }
909         // Add files from /data/preloads/file_cache
910         if (uuid == nullptr) {
911             add_preloads_file_cache(cache, uuid_);
912         }
913         ATRACE_END();
914
915         ATRACE_BEGIN("clear");
916         clear_cache_files(data_path, cache, freeStorageSize);
917         ATRACE_END();
918
919         ATRACE_BEGIN("finish");
920         finish_cache_collection(cache);
921         ATRACE_END();
922     }
923
924     free = data_disk_free(data_path);
925     if (free >= freeStorageSize) {
926         return ok();
927     } else {
928         return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
929                 freeStorageSize, data_path.c_str(), free));
930     }
931 }
932
933 binder::Status InstalldNativeService::rmdex(const std::string& codePath,
934         const std::string& instructionSet) {
935     ENFORCE_UID(AID_SYSTEM);
936     std::lock_guard<std::recursive_mutex> lock(mLock);
937
938     char dex_path[PKG_PATH_MAX];
939
940     const char* path = codePath.c_str();
941     const char* instruction_set = instructionSet.c_str();
942
943     if (validate_apk_path(path) && validate_system_app_path(path)) {
944         return error("Invalid path " + codePath);
945     }
946
947     if (!create_cache_path(dex_path, path, instruction_set)) {
948         return error("Failed to create cache path for " + codePath);
949     }
950
951     ALOGV("unlink %s\n", dex_path);
952     if (unlink(dex_path) < 0) {
953         return error(StringPrintf("Failed to unlink %s", dex_path));
954     } else {
955         return ok();
956     }
957 }
958
959 struct stats {
960     int64_t codeSize;
961     int64_t dataSize;
962     int64_t cacheSize;
963 };
964
965 #if MEASURE_DEBUG
966 static std::string toString(std::vector<int64_t> values) {
967     std::stringstream res;
968     res << "[";
969     for (size_t i = 0; i < values.size(); i++) {
970         res << values[i];
971         if (i < values.size() - 1) {
972             res << ",";
973         }
974     }
975     res << "]";
976     return res.str();
977 }
978 #endif
979
980 static void collectQuotaStats(const std::string& device, int32_t userId,
981         int32_t appId, struct stats* stats, struct stats* extStats) {
982     if (device.empty()) return;
983
984     struct dqblk dq;
985
986     uid_t uid = multiuser_get_uid(userId, appId);
987     if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
988             reinterpret_cast<char*>(&dq)) != 0) {
989         if (errno != ESRCH) {
990             PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
991         }
992     } else {
993 #if MEASURE_DEBUG
994         LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
995 #endif
996         stats->dataSize += dq.dqb_curspace;
997     }
998
999     int cacheGid = multiuser_get_cache_gid(userId, appId);
1000     if (cacheGid != -1) {
1001         if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), cacheGid,
1002                 reinterpret_cast<char*>(&dq)) != 0) {
1003             if (errno != ESRCH) {
1004                 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << cacheGid;
1005             }
1006         } else {
1007 #if MEASURE_DEBUG
1008             LOG(DEBUG) << "quotactl() for GID " << cacheGid << " " << dq.dqb_curspace;
1009 #endif
1010             stats->cacheSize += dq.dqb_curspace;
1011         }
1012     }
1013
1014     int extGid = multiuser_get_ext_gid(userId, appId);
1015     if (extGid != -1) {
1016         if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), extGid,
1017                 reinterpret_cast<char*>(&dq)) != 0) {
1018             if (errno != ESRCH) {
1019                 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << extGid;
1020             }
1021         } else {
1022 #if MEASURE_DEBUG
1023             LOG(DEBUG) << "quotactl() for GID " << extGid << " " << dq.dqb_curspace;
1024 #endif
1025             extStats->dataSize += dq.dqb_curspace;
1026         }
1027     }
1028
1029     int sharedGid = multiuser_get_shared_gid(userId, appId);
1030     if (sharedGid != -1) {
1031         if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), sharedGid,
1032                 reinterpret_cast<char*>(&dq)) != 0) {
1033             if (errno != ESRCH) {
1034                 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << sharedGid;
1035             }
1036         } else {
1037 #if MEASURE_DEBUG
1038             LOG(DEBUG) << "quotactl() for GID " << sharedGid << " " << dq.dqb_curspace;
1039 #endif
1040             stats->codeSize += dq.dqb_curspace;
1041         }
1042     }
1043 }
1044
1045 static void collectManualStats(const std::string& path, struct stats* stats) {
1046     DIR *d;
1047     int dfd;
1048     struct dirent *de;
1049     struct stat s;
1050
1051     d = opendir(path.c_str());
1052     if (d == nullptr) {
1053         if (errno != ENOENT) {
1054             PLOG(WARNING) << "Failed to open " << path;
1055         }
1056         return;
1057     }
1058     dfd = dirfd(d);
1059     while ((de = readdir(d))) {
1060         const char *name = de->d_name;
1061
1062         int64_t size = 0;
1063         if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
1064             size = s.st_blocks * 512;
1065         }
1066
1067         if (de->d_type == DT_DIR) {
1068             if (!strcmp(name, ".")) {
1069                 // Don't recurse, but still count node size
1070             } else if (!strcmp(name, "..")) {
1071                 // Don't recurse or count node size
1072                 continue;
1073             } else {
1074                 // Measure all children nodes
1075                 size = 0;
1076                 calculate_tree_size(StringPrintf("%s/%s", path.c_str(), name), &size);
1077             }
1078
1079             if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
1080                 stats->cacheSize += size;
1081             }
1082         }
1083
1084         // Legacy symlink isn't owned by app
1085         if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
1086             continue;
1087         }
1088
1089         // Everything found inside is considered data
1090         stats->dataSize += size;
1091     }
1092     closedir(d);
1093 }
1094
1095 static void collectManualStatsForUser(const std::string& path, struct stats* stats,
1096         bool exclude_apps = false) {
1097     DIR *d;
1098     int dfd;
1099     struct dirent *de;
1100     struct stat s;
1101
1102     d = opendir(path.c_str());
1103     if (d == nullptr) {
1104         if (errno != ENOENT) {
1105             PLOG(WARNING) << "Failed to open " << path;
1106         }
1107         return;
1108     }
1109     dfd = dirfd(d);
1110     while ((de = readdir(d))) {
1111         if (de->d_type == DT_DIR) {
1112             const char *name = de->d_name;
1113             if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) != 0) {
1114                 continue;
1115             }
1116             if (!strcmp(name, ".") || !strcmp(name, "..")) {
1117                 continue;
1118             } else if (exclude_apps && (s.st_uid >= AID_APP_START && s.st_uid <= AID_APP_END)) {
1119                 continue;
1120             } else {
1121                 collectManualStats(StringPrintf("%s/%s", path.c_str(), name), stats);
1122             }
1123         }
1124     }
1125     closedir(d);
1126 }
1127
1128 static void collectManualExternalStatsForUser(const std::string& path, struct stats* stats) {
1129     FTS *fts;
1130     FTSENT *p;
1131     char *argv[] = { (char*) path.c_str(), nullptr };
1132     if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
1133         PLOG(ERROR) << "Failed to fts_open " << path;
1134         return;
1135     }
1136     while ((p = fts_read(fts)) != NULL) {
1137         p->fts_number = p->fts_parent->fts_number;
1138         switch (p->fts_info) {
1139         case FTS_D:
1140             if (p->fts_level == 4
1141                     && !strcmp(p->fts_name, "cache")
1142                     && !strcmp(p->fts_parent->fts_parent->fts_name, "data")
1143                     && !strcmp(p->fts_parent->fts_parent->fts_parent->fts_name, "Android")) {
1144                 p->fts_number = 1;
1145             }
1146             // Fall through to count the directory
1147         case FTS_DEFAULT:
1148         case FTS_F:
1149         case FTS_SL:
1150         case FTS_SLNONE:
1151             int64_t size = (p->fts_statp->st_blocks * 512);
1152             if (p->fts_number == 1) {
1153                 stats->cacheSize += size;
1154             }
1155             stats->dataSize += size;
1156             break;
1157         }
1158     }
1159     fts_close(fts);
1160 }
1161
1162 binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
1163         const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
1164         int32_t appId, const std::vector<int64_t>& ceDataInodes,
1165         const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
1166     ENFORCE_UID(AID_SYSTEM);
1167     CHECK_ARGUMENT_UUID(uuid);
1168     for (auto packageName : packageNames) {
1169         CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1170     }
1171     // NOTE: Locking is relaxed on this method, since it's limited to
1172     // read-only measurements without mutation.
1173
1174     // When modifying this logic, always verify using tests:
1175     // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetAppSize
1176
1177 #if MEASURE_DEBUG
1178     LOG(INFO) << "Measuring user " << userId << " app " << appId;
1179 #endif
1180
1181     // Here's a summary of the common storage locations across the platform,
1182     // and how they're each tagged:
1183     //
1184     // /data/app/com.example                           UID system
1185     // /data/app/com.example/oat                       UID system
1186     // /data/user/0/com.example                        UID u0_a10      GID u0_a10
1187     // /data/user/0/com.example/cache                  UID u0_a10      GID u0_a10_cache
1188     // /data/media/0/foo.txt                           UID u0_media_rw
1189     // /data/media/0/bar.jpg                           UID u0_media_rw GID u0_media_image
1190     // /data/media/0/Android/data/com.example          UID u0_media_rw GID u0_a10_ext
1191     // /data/media/0/Android/data/com.example/cache    UID u0_media_rw GID u0_a10_ext_cache
1192     // /data/media/obb/com.example                     UID system
1193
1194     struct stats stats;
1195     struct stats extStats;
1196     memset(&stats, 0, sizeof(stats));
1197     memset(&extStats, 0, sizeof(extStats));
1198
1199     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1200
1201     auto device = findQuotaDeviceForUuid(uuid);
1202     if (device.empty()) {
1203         flags &= ~FLAG_USE_QUOTA;
1204     }
1205
1206     ATRACE_BEGIN("obb");
1207     for (auto packageName : packageNames) {
1208         auto obbCodePath = create_data_media_obb_path(uuid_, packageName.c_str());
1209         calculate_tree_size(obbCodePath, &extStats.codeSize);
1210     }
1211     ATRACE_END();
1212
1213     if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START) {
1214         ATRACE_BEGIN("code");
1215         for (auto codePath : codePaths) {
1216             calculate_tree_size(codePath, &stats.codeSize, -1,
1217                     multiuser_get_shared_gid(userId, appId));
1218         }
1219         ATRACE_END();
1220
1221         ATRACE_BEGIN("quota");
1222         collectQuotaStats(device, userId, appId, &stats, &extStats);
1223         ATRACE_END();
1224
1225     } else {
1226         ATRACE_BEGIN("code");
1227         for (auto codePath : codePaths) {
1228             calculate_tree_size(codePath, &stats.codeSize);
1229         }
1230         ATRACE_END();
1231
1232         for (size_t i = 0; i < packageNames.size(); i++) {
1233             const char* pkgname = packageNames[i].c_str();
1234
1235             ATRACE_BEGIN("data");
1236             auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
1237             collectManualStats(cePath, &stats);
1238             auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
1239             collectManualStats(dePath, &stats);
1240             ATRACE_END();
1241
1242             ATRACE_BEGIN("profiles");
1243             auto userProfilePath = create_primary_current_profile_package_dir_path(userId, pkgname);
1244             calculate_tree_size(userProfilePath, &stats.dataSize);
1245             auto refProfilePath = create_primary_reference_profile_package_dir_path(pkgname);
1246             calculate_tree_size(refProfilePath, &stats.codeSize);
1247             ATRACE_END();
1248
1249             ATRACE_BEGIN("external");
1250             auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
1251             collectManualStats(extPath, &extStats);
1252             auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
1253             calculate_tree_size(mediaPath, &extStats.dataSize);
1254             ATRACE_END();
1255         }
1256
1257         ATRACE_BEGIN("dalvik");
1258         int32_t sharedGid = multiuser_get_shared_gid(userId, appId);
1259         if (sharedGid != -1) {
1260             calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1261                     sharedGid, -1);
1262         }
1263         calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1264                 multiuser_get_uid(userId, appId), -1);
1265         ATRACE_END();
1266     }
1267
1268     std::vector<int64_t> ret;
1269     ret.push_back(stats.codeSize);
1270     ret.push_back(stats.dataSize);
1271     ret.push_back(stats.cacheSize);
1272     ret.push_back(extStats.codeSize);
1273     ret.push_back(extStats.dataSize);
1274     ret.push_back(extStats.cacheSize);
1275 #if MEASURE_DEBUG
1276     LOG(DEBUG) << "Final result " << toString(ret);
1277 #endif
1278     *_aidl_return = ret;
1279     return ok();
1280 }
1281
1282 binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
1283         int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
1284         std::vector<int64_t>* _aidl_return) {
1285     ENFORCE_UID(AID_SYSTEM);
1286     CHECK_ARGUMENT_UUID(uuid);
1287     // NOTE: Locking is relaxed on this method, since it's limited to
1288     // read-only measurements without mutation.
1289
1290     // When modifying this logic, always verify using tests:
1291     // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetUserSize
1292
1293 #if MEASURE_DEBUG
1294     LOG(INFO) << "Measuring user " << userId;
1295 #endif
1296
1297     struct stats stats;
1298     struct stats extStats;
1299     memset(&stats, 0, sizeof(stats));
1300     memset(&extStats, 0, sizeof(extStats));
1301
1302     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1303
1304     auto device = findQuotaDeviceForUuid(uuid);
1305     if (device.empty()) {
1306         flags &= ~FLAG_USE_QUOTA;
1307     }
1308
1309     if (flags & FLAG_USE_QUOTA) {
1310         struct dqblk dq;
1311
1312         ATRACE_BEGIN("obb");
1313         if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), AID_MEDIA_OBB,
1314                 reinterpret_cast<char*>(&dq)) != 0) {
1315             if (errno != ESRCH) {
1316                 PLOG(ERROR) << "Failed to quotactl " << device << " for GID " << AID_MEDIA_OBB;
1317             }
1318         } else {
1319 #if MEASURE_DEBUG
1320             LOG(DEBUG) << "quotactl() for GID " << AID_MEDIA_OBB << " " << dq.dqb_curspace;
1321 #endif
1322             extStats.codeSize += dq.dqb_curspace;
1323         }
1324         ATRACE_END();
1325
1326         ATRACE_BEGIN("code");
1327         calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
1328         ATRACE_END();
1329
1330         ATRACE_BEGIN("data");
1331         auto cePath = create_data_user_ce_path(uuid_, userId);
1332         collectManualStatsForUser(cePath, &stats, true);
1333         auto dePath = create_data_user_de_path(uuid_, userId);
1334         collectManualStatsForUser(dePath, &stats, true);
1335         ATRACE_END();
1336
1337         ATRACE_BEGIN("profile");
1338         auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1339         calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
1340         auto refProfilePath = create_primary_ref_profile_dir_path();
1341         calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
1342         ATRACE_END();
1343
1344         ATRACE_BEGIN("external");
1345         uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1346         if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1347                 reinterpret_cast<char*>(&dq)) != 0) {
1348             if (errno != ESRCH) {
1349                 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1350             }
1351         } else {
1352 #if MEASURE_DEBUG
1353             LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1354 #endif
1355             extStats.dataSize += dq.dqb_curspace;
1356         }
1357         ATRACE_END();
1358
1359         ATRACE_BEGIN("dalvik");
1360         calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
1361                 -1, -1, true);
1362         calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
1363                 -1, -1, true);
1364         ATRACE_END();
1365
1366         ATRACE_BEGIN("quota");
1367         for (auto appId : appIds) {
1368             if (appId >= AID_APP_START) {
1369                 collectQuotaStats(device, userId, appId, &stats, &extStats);
1370 #if MEASURE_DEBUG
1371                 // Sleep to make sure we don't lose logs
1372                 usleep(1);
1373 #endif
1374             }
1375         }
1376         ATRACE_END();
1377     } else {
1378         ATRACE_BEGIN("obb");
1379         auto obbPath = create_data_path(uuid_) + "/media/obb";
1380         calculate_tree_size(obbPath, &extStats.codeSize);
1381         ATRACE_END();
1382
1383         ATRACE_BEGIN("code");
1384         calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
1385         ATRACE_END();
1386
1387         ATRACE_BEGIN("data");
1388         auto cePath = create_data_user_ce_path(uuid_, userId);
1389         collectManualStatsForUser(cePath, &stats);
1390         auto dePath = create_data_user_de_path(uuid_, userId);
1391         collectManualStatsForUser(dePath, &stats);
1392         ATRACE_END();
1393
1394         ATRACE_BEGIN("profile");
1395         auto userProfilePath = create_primary_cur_profile_dir_path(userId);
1396         calculate_tree_size(userProfilePath, &stats.dataSize);
1397         auto refProfilePath = create_primary_ref_profile_dir_path();
1398         calculate_tree_size(refProfilePath, &stats.codeSize);
1399         ATRACE_END();
1400
1401         ATRACE_BEGIN("external");
1402         auto dataMediaPath = create_data_media_path(uuid_, userId);
1403         collectManualExternalStatsForUser(dataMediaPath, &extStats);
1404 #if MEASURE_DEBUG
1405         LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
1406                 << extStats.cacheSize;
1407 #endif
1408         ATRACE_END();
1409
1410         ATRACE_BEGIN("dalvik");
1411         calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
1412         calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
1413         ATRACE_END();
1414     }
1415
1416     std::vector<int64_t> ret;
1417     ret.push_back(stats.codeSize);
1418     ret.push_back(stats.dataSize);
1419     ret.push_back(stats.cacheSize);
1420     ret.push_back(extStats.codeSize);
1421     ret.push_back(extStats.dataSize);
1422     ret.push_back(extStats.cacheSize);
1423 #if MEASURE_DEBUG
1424     LOG(DEBUG) << "Final result " << toString(ret);
1425 #endif
1426     *_aidl_return = ret;
1427     return ok();
1428 }
1429
1430 binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
1431         int32_t userId, int32_t flags, std::vector<int64_t>* _aidl_return) {
1432     ENFORCE_UID(AID_SYSTEM);
1433     CHECK_ARGUMENT_UUID(uuid);
1434     // NOTE: Locking is relaxed on this method, since it's limited to
1435     // read-only measurements without mutation.
1436
1437     // When modifying this logic, always verify using tests:
1438     // runtest -x frameworks/base/services/tests/servicestests/src/com/android/server/pm/InstallerTest.java -m testGetExternalSize
1439
1440 #if MEASURE_DEBUG
1441     LOG(INFO) << "Measuring external " << userId;
1442 #endif
1443
1444     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1445
1446     int64_t totalSize = 0;
1447     int64_t audioSize = 0;
1448     int64_t videoSize = 0;
1449     int64_t imageSize = 0;
1450
1451     auto device = findQuotaDeviceForUuid(uuid);
1452     if (device.empty()) {
1453         flags &= ~FLAG_USE_QUOTA;
1454     }
1455
1456     if (flags & FLAG_USE_QUOTA) {
1457         struct dqblk dq;
1458
1459         uid_t uid = multiuser_get_uid(userId, AID_MEDIA_RW);
1460         if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
1461                 reinterpret_cast<char*>(&dq)) != 0) {
1462             if (errno != ESRCH) {
1463                 PLOG(ERROR) << "Failed to quotactl " << device << " for UID " << uid;
1464             }
1465         } else {
1466 #if MEASURE_DEBUG
1467         LOG(DEBUG) << "quotactl() for UID " << uid << " " << dq.dqb_curspace;
1468 #endif
1469             totalSize = dq.dqb_curspace;
1470         }
1471
1472         gid_t audioGid = multiuser_get_uid(userId, AID_MEDIA_AUDIO);
1473         if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), audioGid,
1474                 reinterpret_cast<char*>(&dq)) == 0) {
1475 #if MEASURE_DEBUG
1476         LOG(DEBUG) << "quotactl() for GID " << audioGid << " " << dq.dqb_curspace;
1477 #endif
1478             audioSize = dq.dqb_curspace;
1479         }
1480         gid_t videoGid = multiuser_get_uid(userId, AID_MEDIA_VIDEO);
1481         if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), videoGid,
1482                 reinterpret_cast<char*>(&dq)) == 0) {
1483 #if MEASURE_DEBUG
1484         LOG(DEBUG) << "quotactl() for GID " << videoGid << " " << dq.dqb_curspace;
1485 #endif
1486             videoSize = dq.dqb_curspace;
1487         }
1488         gid_t imageGid = multiuser_get_uid(userId, AID_MEDIA_IMAGE);
1489         if (quotactl(QCMD(Q_GETQUOTA, GRPQUOTA), device.c_str(), imageGid,
1490                 reinterpret_cast<char*>(&dq)) == 0) {
1491 #if MEASURE_DEBUG
1492         LOG(DEBUG) << "quotactl() for GID " << imageGid << " " << dq.dqb_curspace;
1493 #endif
1494             imageSize = dq.dqb_curspace;
1495         }
1496     } else {
1497         FTS *fts;
1498         FTSENT *p;
1499         auto path = create_data_media_path(uuid_, userId);
1500         char *argv[] = { (char*) path.c_str(), nullptr };
1501         if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, NULL))) {
1502             return error("Failed to fts_open " + path);
1503         }
1504         while ((p = fts_read(fts)) != NULL) {
1505             char* ext;
1506             int64_t size = (p->fts_statp->st_blocks * 512);
1507             switch (p->fts_info) {
1508             case FTS_F:
1509                 // Only categorize files not belonging to apps
1510                 if (p->fts_parent->fts_number == 0) {
1511                     ext = strrchr(p->fts_name, '.');
1512                     if (ext != nullptr) {
1513                         switch (MatchExtension(++ext)) {
1514                         case AID_MEDIA_AUDIO: audioSize += size; break;
1515                         case AID_MEDIA_VIDEO: videoSize += size; break;
1516                         case AID_MEDIA_IMAGE: imageSize += size; break;
1517                         }
1518                     }
1519                 }
1520                 // Fall through to always count against total
1521             case FTS_D:
1522                 // Ignore data belonging to specific apps
1523                 p->fts_number = p->fts_parent->fts_number;
1524                 if (p->fts_level == 1 && !strcmp(p->fts_name, "Android")) {
1525                     p->fts_number = 1;
1526                 }
1527             case FTS_DEFAULT:
1528             case FTS_SL:
1529             case FTS_SLNONE:
1530                 totalSize += size;
1531                 break;
1532             }
1533         }
1534         fts_close(fts);
1535     }
1536
1537     std::vector<int64_t> ret;
1538     ret.push_back(totalSize);
1539     ret.push_back(audioSize);
1540     ret.push_back(videoSize);
1541     ret.push_back(imageSize);
1542 #if MEASURE_DEBUG
1543     LOG(DEBUG) << "Final result " << toString(ret);
1544 #endif
1545     *_aidl_return = ret;
1546     return ok();
1547 }
1548
1549 binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
1550         int32_t userId, int32_t appId, int64_t cacheQuota) {
1551     ENFORCE_UID(AID_SYSTEM);
1552     CHECK_ARGUMENT_UUID(uuid);
1553     std::lock_guard<std::recursive_mutex> lock(mCacheQuotasLock);
1554
1555     int32_t uid = multiuser_get_uid(userId, appId);
1556     mCacheQuotas[uid] = cacheQuota;
1557
1558     return ok();
1559 }
1560
1561 // Dumps the contents of a profile file, using pkgname's dex files for pretty
1562 // printing the result.
1563 binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
1564         const std::string& codePaths, bool* _aidl_return) {
1565     ENFORCE_UID(AID_SYSTEM);
1566     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1567     std::lock_guard<std::recursive_mutex> lock(mLock);
1568
1569     const char* pkgname = packageName.c_str();
1570     const char* code_paths = codePaths.c_str();
1571
1572     *_aidl_return = dump_profiles(uid, pkgname, code_paths);
1573     return ok();
1574 }
1575
1576 // TODO: Consider returning error codes.
1577 binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
1578         bool* _aidl_return) {
1579     ENFORCE_UID(AID_SYSTEM);
1580     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1581     std::lock_guard<std::recursive_mutex> lock(mLock);
1582
1583     *_aidl_return = analyze_primary_profiles(uid, packageName);
1584     return ok();
1585 }
1586
1587 binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
1588         const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
1589         int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
1590         const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
1591         const std::unique_ptr<std::string>& sharedLibraries) {
1592     ENFORCE_UID(AID_SYSTEM);
1593     CHECK_ARGUMENT_UUID(uuid);
1594     if (packageName && *packageName != "*") {
1595         CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
1596     }
1597     std::lock_guard<std::recursive_mutex> lock(mLock);
1598
1599     const char* apk_path = apkPath.c_str();
1600     const char* pkgname = packageName ? packageName->c_str() : "*";
1601     const char* instruction_set = instructionSet.c_str();
1602     const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
1603     const char* compiler_filter = compilerFilter.c_str();
1604     const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
1605     const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
1606
1607     int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
1608             oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
1609     return res ? error(res, "Failed to dexopt") : ok();
1610 }
1611
1612 binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
1613     ENFORCE_UID(AID_SYSTEM);
1614     std::lock_guard<std::recursive_mutex> lock(mLock);
1615
1616     const char* instruction_set = instructionSet.c_str();
1617
1618     char boot_marker_path[PKG_PATH_MAX];
1619     sprintf(boot_marker_path,
1620           "%s/%s/%s/.booting",
1621           android_data_dir.path,
1622           DALVIK_CACHE,
1623           instruction_set);
1624
1625     ALOGV("mark_boot_complete : %s", boot_marker_path);
1626     if (unlink(boot_marker_path) != 0) {
1627         return error(StringPrintf("Failed to unlink %s", boot_marker_path));
1628     }
1629     return ok();
1630 }
1631
1632 void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
1633         struct stat* statbuf)
1634 {
1635     while (path[basepos] != 0) {
1636         if (path[basepos] == '/') {
1637             path[basepos] = 0;
1638             if (lstat(path, statbuf) < 0) {
1639                 ALOGV("Making directory: %s\n", path);
1640                 if (mkdir(path, mode) == 0) {
1641                     chown(path, uid, gid);
1642                 } else {
1643                     ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
1644                 }
1645             }
1646             path[basepos] = '/';
1647             basepos++;
1648         }
1649         basepos++;
1650     }
1651 }
1652
1653 binder::Status InstalldNativeService::linkNativeLibraryDirectory(
1654         const std::unique_ptr<std::string>& uuid, const std::string& packageName,
1655         const std::string& nativeLibPath32, int32_t userId) {
1656     ENFORCE_UID(AID_SYSTEM);
1657     CHECK_ARGUMENT_UUID(uuid);
1658     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1659     std::lock_guard<std::recursive_mutex> lock(mLock);
1660
1661     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1662     const char* pkgname = packageName.c_str();
1663     const char* asecLibDir = nativeLibPath32.c_str();
1664     struct stat s, libStat;
1665     binder::Status res = ok();
1666
1667     auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
1668     auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
1669
1670     const char* pkgdir = _pkgdir.c_str();
1671     const char* libsymlink = _libsymlink.c_str();
1672
1673     if (stat(pkgdir, &s) < 0) {
1674         return error("Failed to stat " + _pkgdir);
1675     }
1676
1677     if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
1678         return error("Failed to chown " + _pkgdir);
1679     }
1680
1681     if (chmod(pkgdir, 0700) < 0) {
1682         res = error("Failed to chmod " + _pkgdir);
1683         goto out;
1684     }
1685
1686     if (lstat(libsymlink, &libStat) < 0) {
1687         if (errno != ENOENT) {
1688             res = error("Failed to stat " + _libsymlink);
1689             goto out;
1690         }
1691     } else {
1692         if (S_ISDIR(libStat.st_mode)) {
1693             if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
1694                 res = error("Failed to delete " + _libsymlink);
1695                 goto out;
1696             }
1697         } else if (S_ISLNK(libStat.st_mode)) {
1698             if (unlink(libsymlink) < 0) {
1699                 res = error("Failed to unlink " + _libsymlink);
1700                 goto out;
1701             }
1702         }
1703     }
1704
1705     if (symlink(asecLibDir, libsymlink) < 0) {
1706         res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
1707         goto out;
1708     }
1709
1710 out:
1711     if (chmod(pkgdir, s.st_mode) < 0) {
1712         auto msg = "Failed to cleanup chmod " + _pkgdir;
1713         if (res.isOk()) {
1714             res = error(msg);
1715         } else {
1716             PLOG(ERROR) << msg;
1717         }
1718     }
1719
1720     if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1721         auto msg = "Failed to cleanup chown " + _pkgdir;
1722         if (res.isOk()) {
1723             res = error(msg);
1724         } else {
1725             PLOG(ERROR) << msg;
1726         }
1727     }
1728
1729     return res;
1730 }
1731
1732 static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1733 {
1734     static const char *IDMAP_BIN = "/system/bin/idmap";
1735     static const size_t MAX_INT_LEN = 32;
1736     char idmap_str[MAX_INT_LEN];
1737
1738     snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1739
1740     execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1741     ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1742 }
1743
1744 // Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1745 // eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1746 static int flatten_path(const char *prefix, const char *suffix,
1747         const char *overlay_path, char *idmap_path, size_t N)
1748 {
1749     if (overlay_path == NULL || idmap_path == NULL) {
1750         return -1;
1751     }
1752     const size_t len_overlay_path = strlen(overlay_path);
1753     // will access overlay_path + 1 further below; requires absolute path
1754     if (len_overlay_path < 2 || *overlay_path != '/') {
1755         return -1;
1756     }
1757     const size_t len_idmap_root = strlen(prefix);
1758     const size_t len_suffix = strlen(suffix);
1759     if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1760             SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1761         // additions below would cause overflow
1762         return -1;
1763     }
1764     if (N < len_idmap_root + len_overlay_path + len_suffix) {
1765         return -1;
1766     }
1767     memset(idmap_path, 0, N);
1768     snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1769     char *ch = idmap_path + len_idmap_root;
1770     while (*ch != '\0') {
1771         if (*ch == '/') {
1772             *ch = '@';
1773         }
1774         ++ch;
1775     }
1776     return 0;
1777 }
1778
1779 binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1780         const std::string& overlayApkPath, int32_t uid) {
1781     ENFORCE_UID(AID_SYSTEM);
1782     std::lock_guard<std::recursive_mutex> lock(mLock);
1783
1784     const char* target_apk = targetApkPath.c_str();
1785     const char* overlay_apk = overlayApkPath.c_str();
1786     ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1787
1788     int idmap_fd = -1;
1789     char idmap_path[PATH_MAX];
1790
1791     if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1792                 idmap_path, sizeof(idmap_path)) == -1) {
1793         ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1794         goto fail;
1795     }
1796
1797     unlink(idmap_path);
1798     idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1799     if (idmap_fd < 0) {
1800         ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1801         goto fail;
1802     }
1803     if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1804         ALOGE("idmap cannot chown '%s'\n", idmap_path);
1805         goto fail;
1806     }
1807     if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1808         ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1809         goto fail;
1810     }
1811
1812     pid_t pid;
1813     pid = fork();
1814     if (pid == 0) {
1815         /* child -- drop privileges before continuing */
1816         if (setgid(uid) != 0) {
1817             ALOGE("setgid(%d) failed during idmap\n", uid);
1818             exit(1);
1819         }
1820         if (setuid(uid) != 0) {
1821             ALOGE("setuid(%d) failed during idmap\n", uid);
1822             exit(1);
1823         }
1824         if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1825             ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1826             exit(1);
1827         }
1828
1829         run_idmap(target_apk, overlay_apk, idmap_fd);
1830         exit(1); /* only if exec call to idmap failed */
1831     } else {
1832         int status = wait_child(pid);
1833         if (status != 0) {
1834             ALOGE("idmap failed, status=0x%04x\n", status);
1835             goto fail;
1836         }
1837     }
1838
1839     close(idmap_fd);
1840     return ok();
1841 fail:
1842     if (idmap_fd >= 0) {
1843         close(idmap_fd);
1844         unlink(idmap_path);
1845     }
1846     return error();
1847 }
1848
1849 binder::Status InstalldNativeService::removeIdmap(const std::string& overlayApkPath) {
1850     const char* overlay_apk = overlayApkPath.c_str();
1851     char idmap_path[PATH_MAX];
1852
1853     if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1854                 idmap_path, sizeof(idmap_path)) == -1) {
1855         ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1856         return error();
1857     }
1858     if (unlink(idmap_path) < 0) {
1859         ALOGE("couldn't unlink idmap file %s\n", idmap_path);
1860         return error();
1861     }
1862     return ok();
1863 }
1864
1865 binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1866         const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1867         const std::string& seInfo) {
1868     ENFORCE_UID(AID_SYSTEM);
1869     CHECK_ARGUMENT_UUID(uuid);
1870     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1871     std::lock_guard<std::recursive_mutex> lock(mLock);
1872
1873     binder::Status res = ok();
1874
1875     // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
1876     unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
1877     const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1878     const char* pkgName = packageName.c_str();
1879     const char* seinfo = seInfo.c_str();
1880
1881     uid_t uid = multiuser_get_uid(userId, appId);
1882     if (flags & FLAG_STORAGE_CE) {
1883         auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
1884         if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1885             res = error("restorecon failed for " + path);
1886         }
1887     }
1888     if (flags & FLAG_STORAGE_DE) {
1889         auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
1890         if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1891             res = error("restorecon failed for " + path);
1892         }
1893     }
1894     return res;
1895 }
1896
1897 binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1898         const std::string& instructionSet) {
1899     ENFORCE_UID(AID_SYSTEM);
1900     std::lock_guard<std::recursive_mutex> lock(mLock);
1901
1902     const char* oat_dir = oatDir.c_str();
1903     const char* instruction_set = instructionSet.c_str();
1904     char oat_instr_dir[PKG_PATH_MAX];
1905
1906     if (validate_apk_path(oat_dir)) {
1907         return error("Invalid path " + oatDir);
1908     }
1909     if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1910         return error("Failed to prepare " + oatDir);
1911     }
1912     if (selinux_android_restorecon(oat_dir, 0)) {
1913         return error("Failed to restorecon " + oatDir);
1914     }
1915     snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
1916     if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1917         return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
1918     }
1919     return ok();
1920 }
1921
1922 binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1923     ENFORCE_UID(AID_SYSTEM);
1924     std::lock_guard<std::recursive_mutex> lock(mLock);
1925
1926     if (validate_apk_path(packageDir.c_str())) {
1927         return error("Invalid path " + packageDir);
1928     }
1929     if (delete_dir_contents_and_dir(packageDir) != 0) {
1930         return error("Failed to delete " + packageDir);
1931     }
1932     return ok();
1933 }
1934
1935 binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1936         const std::string& fromBase, const std::string& toBase) {
1937     ENFORCE_UID(AID_SYSTEM);
1938     std::lock_guard<std::recursive_mutex> lock(mLock);
1939
1940     const char* relative_path = relativePath.c_str();
1941     const char* from_base = fromBase.c_str();
1942     const char* to_base = toBase.c_str();
1943     char from_path[PKG_PATH_MAX];
1944     char to_path[PKG_PATH_MAX];
1945     snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1946     snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1947
1948     if (validate_apk_path_subdirs(from_path)) {
1949         return error(StringPrintf("Invalid from path %s", from_path));
1950     }
1951
1952     if (validate_apk_path_subdirs(to_path)) {
1953         return error(StringPrintf("Invalid to path %s", to_path));
1954     }
1955
1956     if (link(from_path, to_path) < 0) {
1957         return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
1958     }
1959
1960     return ok();
1961 }
1962
1963 binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1964         const std::string& instructionSet, const std::string& outputPath) {
1965     ENFORCE_UID(AID_SYSTEM);
1966     std::lock_guard<std::recursive_mutex> lock(mLock);
1967
1968     const char* apk_path = apkPath.c_str();
1969     const char* instruction_set = instructionSet.c_str();
1970     const char* oat_dir = outputPath.c_str();
1971
1972     bool success = move_ab(apk_path, instruction_set, oat_dir);
1973     return success ? ok() : error();
1974 }
1975
1976 binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
1977         const std::string& instructionSet, const std::string& outputPath) {
1978     ENFORCE_UID(AID_SYSTEM);
1979     std::lock_guard<std::recursive_mutex> lock(mLock);
1980
1981     const char* apk_path = apkPath.c_str();
1982     const char* instruction_set = instructionSet.c_str();
1983     const char* oat_dir = outputPath.c_str();
1984
1985     bool res = delete_odex(apk_path, instruction_set, oat_dir);
1986     return res ? ok() : error();
1987 }
1988
1989 binder::Status InstalldNativeService::reconcileSecondaryDexFile(
1990         const std::string& dexPath, const std::string& packageName, int32_t uid,
1991         const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
1992         int32_t storage_flag, bool* _aidl_return) {
1993     ENFORCE_UID(AID_SYSTEM);
1994     CHECK_ARGUMENT_UUID(volumeUuid);
1995     CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1996
1997     std::lock_guard<std::recursive_mutex> lock(mLock);
1998     bool result = android::installd::reconcile_secondary_dex_file(
1999             dexPath, packageName, uid, isas, volumeUuid, storage_flag, _aidl_return);
2000     return result ? ok() : error();
2001 }
2002
2003 binder::Status InstalldNativeService::invalidateMounts() {
2004     ENFORCE_UID(AID_SYSTEM);
2005     std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
2006
2007     mQuotaDevices.clear();
2008
2009     std::ifstream in("/proc/mounts");
2010     if (!in.is_open()) {
2011         return error("Failed to read mounts");
2012     }
2013
2014     std::string source;
2015     std::string target;
2016     std::string ignored;
2017     struct dqblk dq;
2018     while (!in.eof()) {
2019         std::getline(in, source, ' ');
2020         std::getline(in, target, ' ');
2021         std::getline(in, ignored);
2022
2023         if (source.compare(0, 11, "/dev/block/") == 0) {
2024             if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), source.c_str(), 0,
2025                     reinterpret_cast<char*>(&dq)) == 0) {
2026                 LOG(DEBUG) << "Found " << source << " with quota";
2027                 mQuotaDevices[target] = source;
2028             }
2029         }
2030     }
2031     return ok();
2032 }
2033
2034 std::string InstalldNativeService::findQuotaDeviceForUuid(
2035         const std::unique_ptr<std::string>& uuid) {
2036     std::lock_guard<std::recursive_mutex> lock(mQuotaDevicesLock);
2037     auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
2038     return mQuotaDevices[path];
2039 }
2040
2041 binder::Status InstalldNativeService::isQuotaSupported(
2042         const std::unique_ptr<std::string>& volumeUuid, bool* _aidl_return) {
2043     *_aidl_return = !findQuotaDeviceForUuid(volumeUuid).empty();
2044     return ok();
2045 }
2046
2047 }  // namespace installd
2048 }  // namespace android