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