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