InstalldNativeService.cpp revision 74b37b98cd39e6592953da8a3aad2700e23a872f
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#include <errno.h>
20#include <inttypes.h>
21#include <regex>
22#include <stdlib.h>
23#include <sys/capability.h>
24#include <sys/file.h>
25#include <sys/resource.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <sys/wait.h>
29#include <sys/xattr.h>
30#include <unistd.h>
31
32#include <android-base/logging.h>
33#include <android-base/stringprintf.h>
34#include <android-base/strings.h>
35#include <android-base/unique_fd.h>
36#include <cutils/fs.h>
37#include <cutils/log.h>               // TODO: Move everything to base/logging.
38#include <cutils/properties.h>
39#include <cutils/sched_policy.h>
40#include <diskusage/dirsize.h>
41#include <logwrap/logwrap.h>
42#include <private/android_filesystem_config.h>
43#include <selinux/android.h>
44#include <system/thread_defs.h>
45
46#include "dexopt.h"
47#include "globals.h"
48#include "installd_deps.h"
49#include "otapreopt_utils.h"
50#include "utils.h"
51
52#ifndef LOG_TAG
53#define LOG_TAG "installd"
54#endif
55
56using android::base::StringPrintf;
57
58namespace android {
59namespace installd {
60
61static constexpr const char* kCpPath = "/system/bin/cp";
62static constexpr const char* kXattrDefault = "user.default";
63
64static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
65
66static constexpr const char* PKG_LIB_POSTFIX = "/lib";
67static constexpr const char* CACHE_DIR_POSTFIX = "/cache";
68static constexpr const char* CODE_CACHE_DIR_POSTFIX = "/code_cache";
69
70static constexpr const char* IDMAP_PREFIX = "/data/resource-cache/";
71static constexpr const char* IDMAP_SUFFIX = "@idmap";
72
73// NOTE: keep in sync with StorageManager
74static constexpr int FLAG_STORAGE_DE = 1 << 0;
75static constexpr int FLAG_STORAGE_CE = 1 << 1;
76
77// NOTE: keep in sync with Installer
78static constexpr int FLAG_CLEAR_CACHE_ONLY = 1 << 8;
79static constexpr int FLAG_CLEAR_CODE_CACHE_ONLY = 1 << 9;
80
81
82namespace {
83
84constexpr const char* kDump = "android.permission.DUMP";
85
86static binder::Status ok() {
87    return binder::Status::ok();
88}
89
90static binder::Status exception(uint32_t code, const std::string& msg) {
91    return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
92}
93
94static binder::Status error() {
95    return binder::Status::fromServiceSpecificError(errno);
96}
97
98static binder::Status error(const std::string& msg) {
99    PLOG(ERROR) << msg;
100    return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str()));
101}
102
103static binder::Status error(uint32_t code, const std::string& msg) {
104    LOG(ERROR) << msg << " (" << code << ")";
105    return binder::Status::fromServiceSpecificError(code, String8(msg.c_str()));
106}
107
108binder::Status checkPermission(const char* permission) {
109    pid_t pid;
110    uid_t uid;
111
112    if (checkCallingPermission(String16(permission), reinterpret_cast<int32_t*>(&pid),
113            reinterpret_cast<int32_t*>(&uid))) {
114        return ok();
115    } else {
116        return exception(binder::Status::EX_SECURITY,
117                StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
118    }
119}
120
121binder::Status checkUid(uid_t expectedUid) {
122    uid_t uid = IPCThreadState::self()->getCallingUid();
123    if (uid == expectedUid || uid == AID_ROOT) {
124        return ok();
125    } else {
126        return exception(binder::Status::EX_SECURITY,
127                StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
128    }
129}
130
131binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
132    if (!uuid || is_valid_filename(*uuid)) {
133        return ok();
134    } else {
135        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
136                StringPrintf("UUID %s is malformed", uuid->c_str()));
137    }
138}
139
140binder::Status checkArgumentPackageName(const std::string& packageName) {
141    if (is_valid_package_name(packageName.c_str())) {
142        return ok();
143    } else {
144        return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
145                StringPrintf("Package name %s is malformed", packageName.c_str()));
146    }
147}
148
149#define ENFORCE_UID(uid) {                                  \
150    binder::Status status = checkUid((uid));                \
151    if (!status.isOk()) {                                   \
152        return status;                                      \
153    }                                                       \
154}
155
156#define CHECK_ARGUMENT_UUID(uuid) {                         \
157    binder::Status status = checkArgumentUuid((uuid));      \
158    if (!status.isOk()) {                                   \
159        return status;                                      \
160    }                                                       \
161}
162
163#define CHECK_ARGUMENT_PACKAGE_NAME(packageName) {          \
164    binder::Status status =                                 \
165            checkArgumentPackageName((packageName));        \
166    if (!status.isOk()) {                                   \
167        return status;                                      \
168    }                                                       \
169}
170
171}  // namespace
172
173status_t InstalldNativeService::start() {
174    IPCThreadState::self()->disableBackgroundScheduling(true);
175    status_t ret = BinderService<InstalldNativeService>::publish();
176    if (ret != android::OK) {
177        return ret;
178    }
179    sp<ProcessState> ps(ProcessState::self());
180    ps->startThreadPool();
181    ps->giveThreadPoolName();
182    return android::OK;
183}
184
185status_t InstalldNativeService::dump(int fd, const Vector<String16> & /* args */) {
186    const binder::Status dump_permission = checkPermission(kDump);
187    if (!dump_permission.isOk()) {
188        const String8 msg(dump_permission.toString8());
189        write(fd, msg.string(), msg.size());
190        return PERMISSION_DENIED;
191    }
192
193    std::string msg = "installd is happy\n";
194    write(fd, msg.c_str(), strlen(msg.c_str()));
195    return NO_ERROR;
196}
197
198/**
199 * Perform restorecon of the given path, but only perform recursive restorecon
200 * if the label of that top-level file actually changed.  This can save us
201 * significant time by avoiding no-op traversals of large filesystem trees.
202 */
203static int restorecon_app_data_lazy(const std::string& path, const std::string& seInfo, uid_t uid,
204        bool existing) {
205    int res = 0;
206    char* before = nullptr;
207    char* after = nullptr;
208
209    // Note that SELINUX_ANDROID_RESTORECON_DATADATA flag is set by
210    // libselinux. Not needed here.
211
212    if (lgetfilecon(path.c_str(), &before) < 0) {
213        PLOG(ERROR) << "Failed before getfilecon for " << path;
214        goto fail;
215    }
216    if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid, 0) < 0) {
217        PLOG(ERROR) << "Failed top-level restorecon for " << path;
218        goto fail;
219    }
220    if (lgetfilecon(path.c_str(), &after) < 0) {
221        PLOG(ERROR) << "Failed after getfilecon for " << path;
222        goto fail;
223    }
224
225    // If the initial top-level restorecon above changed the label, then go
226    // back and restorecon everything recursively
227    if (strcmp(before, after)) {
228        if (existing) {
229            LOG(DEBUG) << "Detected label change from " << before << " to " << after << " at "
230                    << path << "; running recursive restorecon";
231        }
232        if (selinux_android_restorecon_pkgdir(path.c_str(), seInfo.c_str(), uid,
233                SELINUX_ANDROID_RESTORECON_RECURSE) < 0) {
234            PLOG(ERROR) << "Failed recursive restorecon for " << path;
235            goto fail;
236        }
237    }
238
239    goto done;
240fail:
241    res = -1;
242done:
243    free(before);
244    free(after);
245    return res;
246}
247
248static int restorecon_app_data_lazy(const std::string& parent, const char* name,
249        const std::string& seInfo, uid_t uid, bool existing) {
250    return restorecon_app_data_lazy(StringPrintf("%s/%s", parent.c_str(), name), seInfo, uid,
251            existing);
252}
253
254static int prepare_app_dir(const std::string& path, mode_t target_mode, uid_t uid) {
255    if (fs_prepare_dir_strict(path.c_str(), target_mode, uid, uid) != 0) {
256        PLOG(ERROR) << "Failed to prepare " << path;
257        return -1;
258    }
259    return 0;
260}
261
262static int prepare_app_dir(const std::string& parent, const char* name, mode_t target_mode,
263        uid_t uid) {
264    return prepare_app_dir(StringPrintf("%s/%s", parent.c_str(), name), target_mode, uid);
265}
266
267binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
268        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
269        const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
270    ENFORCE_UID(AID_SYSTEM);
271    CHECK_ARGUMENT_UUID(uuid);
272    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
273
274    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
275    const char* pkgname = packageName.c_str();
276
277    // Assume invalid inode unless filled in below
278    if (_aidl_return != nullptr) *_aidl_return = -1;
279
280    uid_t uid = multiuser_get_uid(userId, appId);
281    mode_t target_mode = targetSdkVersion >= MIN_RESTRICTED_HOME_SDK_VERSION ? 0700 : 0751;
282    if (flags & FLAG_STORAGE_CE) {
283        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname);
284        bool existing = (access(path.c_str(), F_OK) == 0);
285
286        if (prepare_app_dir(path, target_mode, uid) ||
287                prepare_app_dir(path, "cache", 0771, uid) ||
288                prepare_app_dir(path, "code_cache", 0771, uid)) {
289            return error("Failed to prepare " + path);
290        }
291
292        // Consider restorecon over contents if label changed
293        if (restorecon_app_data_lazy(path, seInfo, uid, existing) ||
294                restorecon_app_data_lazy(path, "cache", seInfo, uid, existing) ||
295                restorecon_app_data_lazy(path, "code_cache", seInfo, uid, existing)) {
296            return error("Failed to restorecon " + path);
297        }
298
299        // Remember inode numbers of cache directories so that we can clear
300        // contents while CE storage is locked
301        if (write_path_inode(path, "cache", kXattrInodeCache) ||
302                write_path_inode(path, "code_cache", kXattrInodeCodeCache)) {
303            return error("Failed to write_path_inode for " + path);
304        }
305
306        // And return the CE inode of the top-level data directory so we can
307        // clear contents while CE storage is locked
308        if ((_aidl_return != nullptr)
309                && get_path_inode(path, reinterpret_cast<ino_t*>(_aidl_return)) != 0) {
310            return error("Failed to get_path_inode for " + path);
311        }
312    }
313    if (flags & FLAG_STORAGE_DE) {
314        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
315        bool existing = (access(path.c_str(), F_OK) == 0);
316
317        if (prepare_app_dir(path, target_mode, uid)) {
318            return error("Failed to prepare " + path);
319        }
320
321        // Consider restorecon over contents if label changed
322        if (restorecon_app_data_lazy(path, seInfo, uid, existing)) {
323            return error("Failed to restorecon " + path);
324        }
325
326        if (property_get_bool("dalvik.vm.usejitprofiles", false)) {
327            const std::string profile_path = create_data_user_profile_package_path(userId, pkgname);
328            // read-write-execute only for the app user.
329            if (fs_prepare_dir_strict(profile_path.c_str(), 0700, uid, uid) != 0) {
330                return error("Failed to prepare " + profile_path);
331            }
332            std::string profile_file = create_primary_profile(profile_path);
333            // read-write only for the app user.
334            if (fs_prepare_file_strict(profile_file.c_str(), 0600, uid, uid) != 0) {
335                return error("Failed to prepare " + profile_path);
336            }
337            const std::string ref_profile_path = create_data_ref_profile_package_path(pkgname);
338            // dex2oat/profman runs under the shared app gid and it needs to read/write reference
339            // profiles.
340            int shared_app_gid = multiuser_get_shared_app_gid(uid);
341            if ((shared_app_gid != -1) && fs_prepare_dir_strict(
342                    ref_profile_path.c_str(), 0700, shared_app_gid, shared_app_gid) != 0) {
343                return error("Failed to prepare " + ref_profile_path);
344            }
345        }
346    }
347    return ok();
348}
349
350binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
351        const std::string& packageName, int32_t userId, int32_t flags) {
352    ENFORCE_UID(AID_SYSTEM);
353    CHECK_ARGUMENT_UUID(uuid);
354    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
355
356    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
357    const char* pkgname = packageName.c_str();
358
359    // This method only exists to upgrade system apps that have requested
360    // forceDeviceEncrypted, so their default storage always lives in a
361    // consistent location.  This only works on non-FBE devices, since we
362    // never want to risk exposing data on a device with real CE/DE storage.
363
364    auto ce_path = create_data_user_ce_package_path(uuid_, userId, pkgname);
365    auto de_path = create_data_user_de_package_path(uuid_, userId, pkgname);
366
367    // If neither directory is marked as default, assume CE is default
368    if (getxattr(ce_path.c_str(), kXattrDefault, nullptr, 0) == -1
369            && getxattr(de_path.c_str(), kXattrDefault, nullptr, 0) == -1) {
370        if (setxattr(ce_path.c_str(), kXattrDefault, nullptr, 0, 0) != 0) {
371            return error("Failed to mark default storage " + ce_path);
372        }
373    }
374
375    // Migrate default data location if needed
376    auto target = (flags & FLAG_STORAGE_DE) ? de_path : ce_path;
377    auto source = (flags & FLAG_STORAGE_DE) ? ce_path : de_path;
378
379    if (getxattr(target.c_str(), kXattrDefault, nullptr, 0) == -1) {
380        LOG(WARNING) << "Requested default storage " << target
381                << " is not active; migrating from " << source;
382        if (delete_dir_contents_and_dir(target) != 0) {
383            return error("Failed to delete " + target);
384        }
385        if (rename(source.c_str(), target.c_str()) != 0) {
386            return error("Failed to rename " + source + " to " + target);
387        }
388    }
389
390    return ok();
391}
392
393
394binder::Status InstalldNativeService::clearAppProfiles(const std::string& packageName) {
395    ENFORCE_UID(AID_SYSTEM);
396    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
397
398    const char* pkgname = packageName.c_str();
399    binder::Status res = ok();
400    if (!clear_reference_profile(pkgname)) {
401        res = error("Failed to clear reference profile for " + packageName);
402    }
403    if (!clear_current_profiles(pkgname)) {
404        res = error("Failed to clear current profiles for " + packageName);
405    }
406    return res;
407}
408
409binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
410        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
411    ENFORCE_UID(AID_SYSTEM);
412    CHECK_ARGUMENT_UUID(uuid);
413    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
414
415    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
416    const char* pkgname = packageName.c_str();
417
418    binder::Status res = ok();
419    if (flags & FLAG_STORAGE_CE) {
420        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
421        if (flags & FLAG_CLEAR_CACHE_ONLY) {
422            path = read_path_inode(path, "cache", kXattrInodeCache);
423        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
424            path = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
425        }
426        if (access(path.c_str(), F_OK) == 0) {
427            if (delete_dir_contents(path) != 0) {
428                res = error("Failed to delete contents of " + path);
429            }
430        }
431    }
432    if (flags & FLAG_STORAGE_DE) {
433        std::string suffix = "";
434        bool only_cache = false;
435        if (flags & FLAG_CLEAR_CACHE_ONLY) {
436            suffix = CACHE_DIR_POSTFIX;
437            only_cache = true;
438        } else if (flags & FLAG_CLEAR_CODE_CACHE_ONLY) {
439            suffix = CODE_CACHE_DIR_POSTFIX;
440            only_cache = true;
441        }
442
443        auto path = create_data_user_de_package_path(uuid_, userId, pkgname) + suffix;
444        if (access(path.c_str(), F_OK) == 0) {
445            if (delete_dir_contents(path) != 0) {
446                res = error("Failed to delete contents of " + path);
447            }
448        }
449        if (!only_cache) {
450            if (!clear_current_profile(pkgname, userId)) {
451                res = error("Failed to clear current profile for " + packageName);
452            }
453        }
454    }
455    return res;
456}
457
458static int destroy_app_reference_profile(const char *pkgname) {
459    return delete_dir_contents_and_dir(
460        create_data_ref_profile_package_path(pkgname),
461        /*ignore_if_missing*/ true);
462}
463
464static int destroy_app_current_profiles(const char *pkgname, userid_t userid) {
465    return delete_dir_contents_and_dir(
466        create_data_user_profile_package_path(userid, pkgname),
467        /*ignore_if_missing*/ true);
468}
469
470binder::Status InstalldNativeService::destroyAppProfiles(const std::string& packageName) {
471    ENFORCE_UID(AID_SYSTEM);
472    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
473
474    const char* pkgname = packageName.c_str();
475    binder::Status res = ok();
476    std::vector<userid_t> users = get_known_users(/*volume_uuid*/ nullptr);
477    for (auto user : users) {
478        if (destroy_app_current_profiles(pkgname, user) != 0) {
479            res = error("Failed to destroy current profiles for " + packageName);
480        }
481    }
482    if (destroy_app_reference_profile(pkgname) != 0) {
483        res = error("Failed to destroy reference profile for " + packageName);
484    }
485    return res;
486}
487
488binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
489        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
490    ENFORCE_UID(AID_SYSTEM);
491    CHECK_ARGUMENT_UUID(uuid);
492    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
493
494    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
495    const char* pkgname = packageName.c_str();
496
497    binder::Status res = ok();
498    if (flags & FLAG_STORAGE_CE) {
499        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
500        if (delete_dir_contents_and_dir(path) != 0) {
501            res = error("Failed to delete " + path);
502        }
503    }
504    if (flags & FLAG_STORAGE_DE) {
505        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
506        if (delete_dir_contents_and_dir(path) != 0) {
507            res = error("Failed to delete " + path);
508        }
509        destroy_app_current_profiles(pkgname, userId);
510        // TODO(calin): If the package is still installed by other users it's probably
511        // beneficial to keep the reference profile around.
512        // Verify if it's ok to do that.
513        destroy_app_reference_profile(pkgname);
514    }
515    return res;
516}
517
518binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
519        const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
520        const std::string& dataAppName, int32_t appId, const std::string& seInfo,
521        int32_t targetSdkVersion) {
522    ENFORCE_UID(AID_SYSTEM);
523    CHECK_ARGUMENT_UUID(fromUuid);
524    CHECK_ARGUMENT_UUID(toUuid);
525    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
526
527    const char* from_uuid = fromUuid ? fromUuid->c_str() : nullptr;
528    const char* to_uuid = toUuid ? toUuid->c_str() : nullptr;
529    const char* package_name = packageName.c_str();
530    const char* data_app_name = dataAppName.c_str();
531
532    binder::Status res = ok();
533    std::vector<userid_t> users = get_known_users(from_uuid);
534
535    // Copy app
536    {
537        auto from = create_data_app_package_path(from_uuid, data_app_name);
538        auto to = create_data_app_package_path(to_uuid, data_app_name);
539        auto to_parent = create_data_app_path(to_uuid);
540
541        char *argv[] = {
542            (char*) kCpPath,
543            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
544            (char*) "-p", /* preserve timestamps, ownership, and permissions */
545            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
546            (char*) "-P", /* Do not follow symlinks [default] */
547            (char*) "-d", /* don't dereference symlinks */
548            (char*) from.c_str(),
549            (char*) to_parent.c_str()
550        };
551
552        LOG(DEBUG) << "Copying " << from << " to " << to;
553        int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
554        if (rc != 0) {
555            res = error(rc, "Failed copying " + from + " to " + to);
556            goto fail;
557        }
558
559        if (selinux_android_restorecon(to.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
560            res = error("Failed to restorecon " + to);
561            goto fail;
562        }
563    }
564
565    // Copy private data for all known users
566    for (auto user : users) {
567
568        // Data source may not exist for all users; that's okay
569        auto from_ce = create_data_user_ce_package_path(from_uuid, user, package_name);
570        if (access(from_ce.c_str(), F_OK) != 0) {
571            LOG(INFO) << "Missing source " << from_ce;
572            continue;
573        }
574
575        if (!createAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE, appId,
576                seInfo, targetSdkVersion, nullptr).isOk()) {
577            res = error("Failed to create package target");
578            goto fail;
579        }
580
581        char *argv[] = {
582            (char*) kCpPath,
583            (char*) "-F", /* delete any existing destination file first (--remove-destination) */
584            (char*) "-p", /* preserve timestamps, ownership, and permissions */
585            (char*) "-R", /* recurse into subdirectories (DEST must be a directory) */
586            (char*) "-P", /* Do not follow symlinks [default] */
587            (char*) "-d", /* don't dereference symlinks */
588            nullptr,
589            nullptr
590        };
591
592        {
593            auto from = create_data_user_de_package_path(from_uuid, user, package_name);
594            auto to = create_data_user_de_path(to_uuid, user);
595            argv[6] = (char*) from.c_str();
596            argv[7] = (char*) to.c_str();
597
598            LOG(DEBUG) << "Copying " << from << " to " << to;
599            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
600            if (rc != 0) {
601                res = error(rc, "Failed copying " + from + " to " + to);
602                goto fail;
603            }
604        }
605        {
606            auto from = create_data_user_ce_package_path(from_uuid, user, package_name);
607            auto to = create_data_user_ce_path(to_uuid, user);
608            argv[6] = (char*) from.c_str();
609            argv[7] = (char*) to.c_str();
610
611            LOG(DEBUG) << "Copying " << from << " to " << to;
612            int rc = android_fork_execvp(ARRAY_SIZE(argv), argv, NULL, false, true);
613            if (rc != 0) {
614                res = error(rc, "Failed copying " + from + " to " + to);
615                goto fail;
616            }
617        }
618
619        if (!restoreconAppData(toUuid, packageName, user, FLAG_STORAGE_CE | FLAG_STORAGE_DE,
620                appId, seInfo).isOk()) {
621            res = error("Failed to restorecon");
622            goto fail;
623        }
624    }
625
626    // We let the framework scan the new location and persist that before
627    // deleting the data in the old location; this ordering ensures that
628    // we can recover from things like battery pulls.
629    return ok();
630
631fail:
632    // Nuke everything we might have already copied
633    {
634        auto to = create_data_app_package_path(to_uuid, data_app_name);
635        if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
636            LOG(WARNING) << "Failed to rollback " << to;
637        }
638    }
639    for (auto user : users) {
640        {
641            auto to = create_data_user_de_package_path(to_uuid, user, package_name);
642            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
643                LOG(WARNING) << "Failed to rollback " << to;
644            }
645        }
646        {
647            auto to = create_data_user_ce_package_path(to_uuid, user, package_name);
648            if (delete_dir_contents(to.c_str(), 1, NULL) != 0) {
649                LOG(WARNING) << "Failed to rollback " << to;
650            }
651        }
652    }
653    return res;
654}
655
656binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
657        int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
658    ENFORCE_UID(AID_SYSTEM);
659    CHECK_ARGUMENT_UUID(uuid);
660
661    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
662    if (flags & FLAG_STORAGE_DE) {
663        if (uuid_ == nullptr) {
664            if (ensure_config_user_dirs(userId) != 0) {
665                return error(StringPrintf("Failed to ensure dirs for %d", userId));
666            }
667        }
668    }
669    return ok();
670}
671
672binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
673        int32_t userId, int32_t flags) {
674    ENFORCE_UID(AID_SYSTEM);
675    CHECK_ARGUMENT_UUID(uuid);
676
677    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
678    binder::Status res = ok();
679    if (flags & FLAG_STORAGE_DE) {
680        auto path = create_data_user_de_path(uuid_, userId);
681        if (delete_dir_contents_and_dir(path, true) != 0) {
682            res = error("Failed to delete " + path);
683        }
684        if (uuid_ == nullptr) {
685            path = create_data_misc_legacy_path(userId);
686            if (delete_dir_contents_and_dir(path, true) != 0) {
687                res = error("Failed to delete " + path);
688            }
689            path = create_data_user_profiles_path(userId);
690            if (delete_dir_contents_and_dir(path, true) != 0) {
691                res = error("Failed to delete " + path);
692            }
693        }
694    }
695    if (flags & FLAG_STORAGE_CE) {
696        auto path = create_data_user_ce_path(uuid_, userId);
697        if (delete_dir_contents_and_dir(path, true) != 0) {
698            res = error("Failed to delete " + path);
699        }
700        path = create_data_media_path(uuid_, userId);
701        if (delete_dir_contents_and_dir(path, true) != 0) {
702            res = error("Failed to delete " + path);
703        }
704    }
705    return res;
706}
707
708/* Try to ensure free_size bytes of storage are available.
709 * Returns 0 on success.
710 * This is rather simple-minded because doing a full LRU would
711 * be potentially memory-intensive, and without atime it would
712 * also require that apps constantly modify file metadata even
713 * when just reading from the cache, which is pretty awful.
714 */
715binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
716        int64_t freeStorageSize) {
717    ENFORCE_UID(AID_SYSTEM);
718    CHECK_ARGUMENT_UUID(uuid);
719
720    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
721    cache_t* cache;
722    int64_t avail;
723
724    auto data_path = create_data_path(uuid_);
725
726    avail = data_disk_free(data_path);
727    if (avail < 0) {
728        return error("Failed to determine free space for " + data_path);
729    }
730
731    ALOGI("free_cache(%" PRId64 ") avail %" PRId64 "\n", freeStorageSize, avail);
732    if (avail >= freeStorageSize) {
733        return ok();
734    }
735
736    cache = start_cache_collection();
737
738    auto users = get_known_users(uuid_);
739    for (auto user : users) {
740        add_cache_files(cache, create_data_user_ce_path(uuid_, user));
741        add_cache_files(cache, create_data_user_de_path(uuid_, user));
742        add_cache_files(cache,
743                StringPrintf("%s/Android/data", create_data_media_path(uuid_, user).c_str()));
744    }
745
746    clear_cache_files(data_path, cache, freeStorageSize);
747    finish_cache_collection(cache);
748
749    avail = data_disk_free(data_path);
750    if (avail >= freeStorageSize) {
751        return ok();
752    } else {
753        return error(StringPrintf("Failed to free up %" PRId64 " on %s; final free space %" PRId64,
754                freeStorageSize, data_path.c_str(), avail));
755    }
756}
757
758binder::Status InstalldNativeService::rmdex(const std::string& codePath,
759        const std::string& instructionSet) {
760    ENFORCE_UID(AID_SYSTEM);
761    char dex_path[PKG_PATH_MAX];
762
763    const char* path = codePath.c_str();
764    const char* instruction_set = instructionSet.c_str();
765
766    if (validate_apk_path(path) && validate_system_app_path(path)) {
767        return error("Invalid path " + codePath);
768    }
769
770    if (!create_cache_path(dex_path, path, instruction_set)) {
771        return error("Failed to create cache path for " + codePath);
772    }
773
774    ALOGV("unlink %s\n", dex_path);
775    if (unlink(dex_path) < 0) {
776        return error(StringPrintf("Failed to unlink %s", dex_path));
777    } else {
778        return ok();
779    }
780}
781
782static void add_app_data_size(std::string& path, int64_t *codesize, int64_t *datasize,
783        int64_t *cachesize) {
784    DIR *d;
785    int dfd;
786    struct dirent *de;
787    struct stat s;
788
789    d = opendir(path.c_str());
790    if (d == nullptr) {
791        PLOG(WARNING) << "Failed to open " << path;
792        return;
793    }
794    dfd = dirfd(d);
795    while ((de = readdir(d))) {
796        const char *name = de->d_name;
797
798        int64_t statsize = 0;
799        if (fstatat(dfd, name, &s, AT_SYMLINK_NOFOLLOW) == 0) {
800            statsize = stat_size(&s);
801        }
802
803        if (de->d_type == DT_DIR) {
804            int subfd;
805            int64_t dirsize = 0;
806            /* always skip "." and ".." */
807            if (name[0] == '.') {
808                if (name[1] == 0) continue;
809                if ((name[1] == '.') && (name[2] == 0)) continue;
810            }
811            subfd = openat(dfd, name, O_RDONLY | O_DIRECTORY);
812            if (subfd >= 0) {
813                dirsize = calculate_dir_size(subfd);
814                close(subfd);
815            }
816            // TODO: check xattrs!
817            if (!strcmp(name, "cache") || !strcmp(name, "code_cache")) {
818                *datasize += statsize;
819                *cachesize += dirsize;
820            } else {
821                *datasize += dirsize + statsize;
822            }
823        } else if (de->d_type == DT_LNK && !strcmp(name, "lib")) {
824            *codesize += statsize;
825        } else {
826            *datasize += statsize;
827        }
828    }
829    closedir(d);
830}
831
832binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
833        const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode,
834        const std::string& codePath, std::vector<int64_t>* _aidl_return) {
835    ENFORCE_UID(AID_SYSTEM);
836    CHECK_ARGUMENT_UUID(uuid);
837    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
838
839    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
840    const char* pkgname = packageName.c_str();
841    const char* code_path = codePath.c_str();
842
843    DIR *d;
844    int dfd;
845    int64_t codesize = 0;
846    int64_t datasize = 0;
847    int64_t cachesize = 0;
848    int64_t asecsize = 0;
849
850    d = opendir(code_path);
851    if (d != nullptr) {
852        dfd = dirfd(d);
853        codesize += calculate_dir_size(dfd);
854        closedir(d);
855    }
856
857    if (flags & FLAG_STORAGE_CE) {
858        auto path = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInode);
859        add_app_data_size(path, &codesize, &datasize, &cachesize);
860    }
861    if (flags & FLAG_STORAGE_DE) {
862        auto path = create_data_user_de_package_path(uuid_, userId, pkgname);
863        add_app_data_size(path, &codesize, &datasize, &cachesize);
864    }
865
866    std::vector<int64_t> res;
867    res.push_back(codesize);
868    res.push_back(datasize);
869    res.push_back(cachesize);
870    res.push_back(asecsize);
871    *_aidl_return = res;
872    return ok();
873}
874
875// Dumps the contents of a profile file, using pkgname's dex files for pretty
876// printing the result.
877binder::Status InstalldNativeService::dumpProfiles(int32_t uid, const std::string& packageName,
878        const std::string& codePaths, bool* _aidl_return) {
879    ENFORCE_UID(AID_SYSTEM);
880    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
881
882    const char* pkgname = packageName.c_str();
883    const char* code_paths = codePaths.c_str();
884
885    *_aidl_return = dump_profiles(uid, pkgname, code_paths);
886    return ok();
887}
888
889// TODO: Consider returning error codes.
890binder::Status InstalldNativeService::mergeProfiles(int32_t uid, const std::string& packageName,
891        bool* _aidl_return) {
892    ENFORCE_UID(AID_SYSTEM);
893    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
894
895    const char* pkgname = packageName.c_str();
896    *_aidl_return = analyse_profiles(uid, pkgname);
897    return ok();
898}
899
900binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
901        const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
902        int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
903        const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
904        const std::unique_ptr<std::string>& sharedLibraries) {
905    ENFORCE_UID(AID_SYSTEM);
906    CHECK_ARGUMENT_UUID(uuid);
907    if (packageName && *packageName != "*") {
908        CHECK_ARGUMENT_PACKAGE_NAME(*packageName);
909    }
910
911    const char* apk_path = apkPath.c_str();
912    const char* pkgname = packageName ? packageName->c_str() : "*";
913    const char* instruction_set = instructionSet.c_str();
914    const char* oat_dir = outputPath ? outputPath->c_str() : nullptr;
915    const char* compiler_filter = compilerFilter.c_str();
916    const char* volume_uuid = uuid ? uuid->c_str() : nullptr;
917    const char* shared_libraries = sharedLibraries ? sharedLibraries->c_str() : nullptr;
918
919    int res = android::installd::dexopt(apk_path, uid, pkgname, instruction_set, dexoptNeeded,
920            oat_dir, dexFlags, compiler_filter, volume_uuid, shared_libraries);
921    return res ? error(res, "Failed to dexopt") : ok();
922}
923
924binder::Status InstalldNativeService::markBootComplete(const std::string& instructionSet) {
925    ENFORCE_UID(AID_SYSTEM);
926    const char* instruction_set = instructionSet.c_str();
927
928    char boot_marker_path[PKG_PATH_MAX];
929    sprintf(boot_marker_path,
930          "%s/%s/%s/.booting",
931          android_data_dir.path,
932          DALVIK_CACHE,
933          instruction_set);
934
935    ALOGV("mark_boot_complete : %s", boot_marker_path);
936    if (unlink(boot_marker_path) != 0) {
937        return error(StringPrintf("Failed to unlink %s", boot_marker_path));
938    }
939    return ok();
940}
941
942void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
943        struct stat* statbuf)
944{
945    while (path[basepos] != 0) {
946        if (path[basepos] == '/') {
947            path[basepos] = 0;
948            if (lstat(path, statbuf) < 0) {
949                ALOGV("Making directory: %s\n", path);
950                if (mkdir(path, mode) == 0) {
951                    chown(path, uid, gid);
952                } else {
953                    ALOGW("Unable to make directory %s: %s\n", path, strerror(errno));
954                }
955            }
956            path[basepos] = '/';
957            basepos++;
958        }
959        basepos++;
960    }
961}
962
963binder::Status InstalldNativeService::linkNativeLibraryDirectory(
964        const std::unique_ptr<std::string>& uuid, const std::string& packageName,
965        const std::string& nativeLibPath32, int32_t userId) {
966    ENFORCE_UID(AID_SYSTEM);
967    CHECK_ARGUMENT_UUID(uuid);
968    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
969
970    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
971    const char* pkgname = packageName.c_str();
972    const char* asecLibDir = nativeLibPath32.c_str();
973    struct stat s, libStat;
974    binder::Status res = ok();
975
976    auto _pkgdir = create_data_user_ce_package_path(uuid_, userId, pkgname);
977    auto _libsymlink = _pkgdir + PKG_LIB_POSTFIX;
978
979    const char* pkgdir = _pkgdir.c_str();
980    const char* libsymlink = _libsymlink.c_str();
981
982    if (stat(pkgdir, &s) < 0) {
983        return error("Failed to stat " + _pkgdir);
984    }
985
986    if (chown(pkgdir, AID_INSTALL, AID_INSTALL) < 0) {
987        return error("Failed to chown " + _pkgdir);
988    }
989
990    if (chmod(pkgdir, 0700) < 0) {
991        res = error("Failed to chmod " + _pkgdir);
992        goto out;
993    }
994
995    if (lstat(libsymlink, &libStat) < 0) {
996        if (errno != ENOENT) {
997            res = error("Failed to stat " + _libsymlink);
998            goto out;
999        }
1000    } else {
1001        if (S_ISDIR(libStat.st_mode)) {
1002            if (delete_dir_contents(libsymlink, 1, NULL) < 0) {
1003                res = error("Failed to delete " + _libsymlink);
1004                goto out;
1005            }
1006        } else if (S_ISLNK(libStat.st_mode)) {
1007            if (unlink(libsymlink) < 0) {
1008                res = error("Failed to unlink " + _libsymlink);
1009                goto out;
1010            }
1011        }
1012    }
1013
1014    if (symlink(asecLibDir, libsymlink) < 0) {
1015        res = error("Failed to symlink " + _libsymlink + " to " + nativeLibPath32);
1016        goto out;
1017    }
1018
1019out:
1020    if (chmod(pkgdir, s.st_mode) < 0) {
1021        auto msg = "Failed to cleanup chmod " + _pkgdir;
1022        if (res.isOk()) {
1023            res = error(msg);
1024        } else {
1025            PLOG(ERROR) << msg;
1026        }
1027    }
1028
1029    if (chown(pkgdir, s.st_uid, s.st_gid) < 0) {
1030        auto msg = "Failed to cleanup chown " + _pkgdir;
1031        if (res.isOk()) {
1032            res = error(msg);
1033        } else {
1034            PLOG(ERROR) << msg;
1035        }
1036    }
1037
1038    return res;
1039}
1040
1041static void run_idmap(const char *target_apk, const char *overlay_apk, int idmap_fd)
1042{
1043    static const char *IDMAP_BIN = "/system/bin/idmap";
1044    static const size_t MAX_INT_LEN = 32;
1045    char idmap_str[MAX_INT_LEN];
1046
1047    snprintf(idmap_str, sizeof(idmap_str), "%d", idmap_fd);
1048
1049    execl(IDMAP_BIN, IDMAP_BIN, "--fd", target_apk, overlay_apk, idmap_str, (char*)NULL);
1050    ALOGE("execl(%s) failed: %s\n", IDMAP_BIN, strerror(errno));
1051}
1052
1053// Transform string /a/b/c.apk to (prefix)/a@b@c.apk@(suffix)
1054// eg /a/b/c.apk to /data/resource-cache/a@b@c.apk@idmap
1055static int flatten_path(const char *prefix, const char *suffix,
1056        const char *overlay_path, char *idmap_path, size_t N)
1057{
1058    if (overlay_path == NULL || idmap_path == NULL) {
1059        return -1;
1060    }
1061    const size_t len_overlay_path = strlen(overlay_path);
1062    // will access overlay_path + 1 further below; requires absolute path
1063    if (len_overlay_path < 2 || *overlay_path != '/') {
1064        return -1;
1065    }
1066    const size_t len_idmap_root = strlen(prefix);
1067    const size_t len_suffix = strlen(suffix);
1068    if (SIZE_MAX - len_idmap_root < len_overlay_path ||
1069            SIZE_MAX - (len_idmap_root + len_overlay_path) < len_suffix) {
1070        // additions below would cause overflow
1071        return -1;
1072    }
1073    if (N < len_idmap_root + len_overlay_path + len_suffix) {
1074        return -1;
1075    }
1076    memset(idmap_path, 0, N);
1077    snprintf(idmap_path, N, "%s%s%s", prefix, overlay_path + 1, suffix);
1078    char *ch = idmap_path + len_idmap_root;
1079    while (*ch != '\0') {
1080        if (*ch == '/') {
1081            *ch = '@';
1082        }
1083        ++ch;
1084    }
1085    return 0;
1086}
1087
1088binder::Status InstalldNativeService::idmap(const std::string& targetApkPath,
1089        const std::string& overlayApkPath, int32_t uid) {
1090    ENFORCE_UID(AID_SYSTEM);
1091    const char* target_apk = targetApkPath.c_str();
1092    const char* overlay_apk = overlayApkPath.c_str();
1093    ALOGV("idmap target_apk=%s overlay_apk=%s uid=%d\n", target_apk, overlay_apk, uid);
1094
1095    int idmap_fd = -1;
1096    char idmap_path[PATH_MAX];
1097
1098    if (flatten_path(IDMAP_PREFIX, IDMAP_SUFFIX, overlay_apk,
1099                idmap_path, sizeof(idmap_path)) == -1) {
1100        ALOGE("idmap cannot generate idmap path for overlay %s\n", overlay_apk);
1101        goto fail;
1102    }
1103
1104    unlink(idmap_path);
1105    idmap_fd = open(idmap_path, O_RDWR | O_CREAT | O_EXCL, 0644);
1106    if (idmap_fd < 0) {
1107        ALOGE("idmap cannot open '%s' for output: %s\n", idmap_path, strerror(errno));
1108        goto fail;
1109    }
1110    if (fchown(idmap_fd, AID_SYSTEM, uid) < 0) {
1111        ALOGE("idmap cannot chown '%s'\n", idmap_path);
1112        goto fail;
1113    }
1114    if (fchmod(idmap_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) {
1115        ALOGE("idmap cannot chmod '%s'\n", idmap_path);
1116        goto fail;
1117    }
1118
1119    pid_t pid;
1120    pid = fork();
1121    if (pid == 0) {
1122        /* child -- drop privileges before continuing */
1123        if (setgid(uid) != 0) {
1124            ALOGE("setgid(%d) failed during idmap\n", uid);
1125            exit(1);
1126        }
1127        if (setuid(uid) != 0) {
1128            ALOGE("setuid(%d) failed during idmap\n", uid);
1129            exit(1);
1130        }
1131        if (flock(idmap_fd, LOCK_EX | LOCK_NB) != 0) {
1132            ALOGE("flock(%s) failed during idmap: %s\n", idmap_path, strerror(errno));
1133            exit(1);
1134        }
1135
1136        run_idmap(target_apk, overlay_apk, idmap_fd);
1137        exit(1); /* only if exec call to idmap failed */
1138    } else {
1139        int status = wait_child(pid);
1140        if (status != 0) {
1141            ALOGE("idmap failed, status=0x%04x\n", status);
1142            goto fail;
1143        }
1144    }
1145
1146    close(idmap_fd);
1147    return ok();
1148fail:
1149    if (idmap_fd >= 0) {
1150        close(idmap_fd);
1151        unlink(idmap_path);
1152    }
1153    return error();
1154}
1155
1156binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
1157        const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
1158        const std::string& seInfo) {
1159    ENFORCE_UID(AID_SYSTEM);
1160    CHECK_ARGUMENT_UUID(uuid);
1161    CHECK_ARGUMENT_PACKAGE_NAME(packageName);
1162
1163    binder::Status res = ok();
1164
1165    // SELINUX_ANDROID_RESTORECON_DATADATA flag is set by libselinux. Not needed here.
1166    unsigned int seflags = SELINUX_ANDROID_RESTORECON_RECURSE;
1167    const char* uuid_ = uuid ? uuid->c_str() : nullptr;
1168    const char* pkgName = packageName.c_str();
1169    const char* seinfo = seInfo.c_str();
1170
1171    uid_t uid = multiuser_get_uid(userId, appId);
1172    if (flags & FLAG_STORAGE_CE) {
1173        auto path = create_data_user_ce_package_path(uuid_, userId, pkgName);
1174        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1175            res = error("restorecon failed for " + path);
1176        }
1177    }
1178    if (flags & FLAG_STORAGE_DE) {
1179        auto path = create_data_user_de_package_path(uuid_, userId, pkgName);
1180        if (selinux_android_restorecon_pkgdir(path.c_str(), seinfo, uid, seflags) < 0) {
1181            res = error("restorecon failed for " + path);
1182        }
1183    }
1184    return res;
1185}
1186
1187binder::Status InstalldNativeService::createOatDir(const std::string& oatDir,
1188        const std::string& instructionSet) {
1189    ENFORCE_UID(AID_SYSTEM);
1190    const char* oat_dir = oatDir.c_str();
1191    const char* instruction_set = instructionSet.c_str();
1192    char oat_instr_dir[PKG_PATH_MAX];
1193
1194    if (validate_apk_path(oat_dir)) {
1195        return error("Invalid path " + oatDir);
1196    }
1197    if (fs_prepare_dir(oat_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1198        return error("Failed to prepare " + oatDir);
1199    }
1200    if (selinux_android_restorecon(oat_dir, 0)) {
1201        return error("Failed to restorecon " + oatDir);
1202    }
1203    snprintf(oat_instr_dir, PKG_PATH_MAX, "%s/%s", oat_dir, instruction_set);
1204    if (fs_prepare_dir(oat_instr_dir, S_IRWXU | S_IRWXG | S_IXOTH, AID_SYSTEM, AID_INSTALL)) {
1205        return error(StringPrintf("Failed to prepare %s", oat_instr_dir));
1206    }
1207    return ok();
1208}
1209
1210binder::Status InstalldNativeService::rmPackageDir(const std::string& packageDir) {
1211    ENFORCE_UID(AID_SYSTEM);
1212    if (validate_apk_path(packageDir.c_str())) {
1213        return error("Invalid path " + packageDir);
1214    }
1215    if (delete_dir_contents_and_dir(packageDir) != 0) {
1216        return error("Failed to delete " + packageDir);
1217    }
1218    return ok();
1219}
1220
1221binder::Status InstalldNativeService::linkFile(const std::string& relativePath,
1222        const std::string& fromBase, const std::string& toBase) {
1223    ENFORCE_UID(AID_SYSTEM);
1224    const char* relative_path = relativePath.c_str();
1225    const char* from_base = fromBase.c_str();
1226    const char* to_base = toBase.c_str();
1227    char from_path[PKG_PATH_MAX];
1228    char to_path[PKG_PATH_MAX];
1229    snprintf(from_path, PKG_PATH_MAX, "%s/%s", from_base, relative_path);
1230    snprintf(to_path, PKG_PATH_MAX, "%s/%s", to_base, relative_path);
1231
1232    if (validate_apk_path_subdirs(from_path)) {
1233        return error(StringPrintf("Invalid from path %s", from_path));
1234    }
1235
1236    if (validate_apk_path_subdirs(to_path)) {
1237        return error(StringPrintf("Invalid to path %s", to_path));
1238    }
1239
1240    if (link(from_path, to_path) < 0) {
1241        return error(StringPrintf("Failed to link from %s to %s", from_path, to_path));
1242    }
1243
1244    return ok();
1245}
1246
1247binder::Status InstalldNativeService::moveAb(const std::string& apkPath,
1248        const std::string& instructionSet, const std::string& outputPath) {
1249    ENFORCE_UID(AID_SYSTEM);
1250
1251    const char* apk_path = apkPath.c_str();
1252    const char* instruction_set = instructionSet.c_str();
1253    const char* oat_dir = outputPath.c_str();
1254
1255    bool success = move_ab(apk_path, instruction_set, oat_dir);
1256    return success ? ok() : error();
1257}
1258
1259binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
1260        const std::string& instructionSet, const std::string& outputPath) {
1261    ENFORCE_UID(AID_SYSTEM);
1262
1263    const char* apk_path = apkPath.c_str();
1264    const char* instruction_set = instructionSet.c_str();
1265    const char* oat_dir = outputPath.c_str();
1266
1267    bool res = delete_odex(apk_path, instruction_set, oat_dir);
1268    return res ? ok() : error();
1269}
1270
1271}  // namespace installd
1272}  // namespace android
1273