blob: 4d6d234615a92735281c8e1141fe1a0ab9f7c98e [file] [log] [blame]
Calin Juravle7d765462017-09-04 15:57:10 -07001/*
2 * Copyright (C) 2017 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
Calin Juravle29591732017-11-20 17:46:19 -080017#include <fcntl.h>
Calin Juravle7d765462017-09-04 15:57:10 -070018#include <stdlib.h>
19#include <string.h>
Calin Juravle29591732017-11-20 17:46:19 -080020#include <sys/types.h>
21#include <sys/stat.h>
Calin Juravle7d765462017-09-04 15:57:10 -070022
Calin Juravle29591732017-11-20 17:46:19 -080023#include <android-base/file.h>
Calin Juravle7d765462017-09-04 15:57:10 -070024#include <android-base/logging.h>
25#include <android-base/stringprintf.h>
Calin Juravle29591732017-11-20 17:46:19 -080026#include <android-base/unique_fd.h>
27
Calin Juravle7d765462017-09-04 15:57:10 -070028#include <cutils/properties.h>
Calin Juravle29591732017-11-20 17:46:19 -080029
Calin Juravle7d765462017-09-04 15:57:10 -070030#include <gtest/gtest.h>
31
Calin Juravle29591732017-11-20 17:46:19 -080032#include <selinux/android.h>
33#include <selinux/avc.h>
34
Calin Juravle7d765462017-09-04 15:57:10 -070035#include "dexopt.h"
36#include "InstalldNativeService.h"
37#include "globals.h"
38#include "tests/test_utils.h"
39#include "utils.h"
40
Calin Juravle29591732017-11-20 17:46:19 -080041using android::base::ReadFully;
42using android::base::unique_fd;
43
Calin Juravle7d765462017-09-04 15:57:10 -070044namespace android {
45namespace installd {
46
47// TODO(calin): try to dedup this code.
48#if defined(__arm__)
49static const std::string kRuntimeIsa = "arm";
50#elif defined(__aarch64__)
51static const std::string kRuntimeIsa = "arm64";
52#elif defined(__mips__) && !defined(__LP64__)
53static const std::string kRuntimeIsa = "mips";
54#elif defined(__mips__) && defined(__LP64__)
55static const std::string kRuntimeIsa = "mips64";
56#elif defined(__i386__)
57static const std::string kRuntimeIsa = "x86";
58#elif defined(__x86_64__)
59static const std::string kRuntimeIsa = "x86_64";
60#else
61static const std::string kRuntimeIsa = "none";
62#endif
63
64int get_property(const char *key, char *value, const char *default_value) {
65 return property_get(key, value, default_value);
66}
67
68bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir, const char *apk_path,
69 const char *instruction_set) {
70 return calculate_oat_file_path_default(path, oat_dir, apk_path, instruction_set);
71}
72
73bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
74 const char *instruction_set) {
75 return calculate_odex_file_path_default(path, apk_path, instruction_set);
76}
77
78bool create_cache_path(char path[PKG_PATH_MAX], const char *src, const char *instruction_set) {
79 return create_cache_path_default(path, src, instruction_set);
80}
81
82static void run_cmd(const std::string& cmd) {
83 system(cmd.c_str());
84}
85
86static void mkdir(const std::string& path, uid_t owner, gid_t group, mode_t mode) {
87 ::mkdir(path.c_str(), mode);
88 ::chown(path.c_str(), owner, group);
89 ::chmod(path.c_str(), mode);
90}
91
Calin Juravle29591732017-11-20 17:46:19 -080092static int log_callback(int type, const char *fmt, ...) { // NOLINT
93 va_list ap;
94 int priority;
95
96 switch (type) {
97 case SELINUX_WARNING:
98 priority = ANDROID_LOG_WARN;
99 break;
100 case SELINUX_INFO:
101 priority = ANDROID_LOG_INFO;
102 break;
103 default:
104 priority = ANDROID_LOG_ERROR;
105 break;
106 }
107 va_start(ap, fmt);
108 LOG_PRI_VA(priority, "SELinux", fmt, ap);
109 va_end(ap);
110 return 0;
111}
112
113static bool init_selinux() {
114 int selinux_enabled = (is_selinux_enabled() > 0);
115
116 union selinux_callback cb;
117 cb.func_log = log_callback;
118 selinux_set_callback(SELINUX_CB_LOG, cb);
119
120 if (selinux_enabled && selinux_status_open(true) < 0) {
121 LOG(ERROR) << "Could not open selinux status; exiting";
122 return false;
123 }
124
125 return true;
126}
127
Calin Juravle7d765462017-09-04 15:57:10 -0700128// Base64 encoding of a simple dex files with 2 methods.
129static const char kDexFile[] =
130 "UEsDBBQAAAAIAOiOYUs9y6BLCgEAABQCAAALABwAY2xhc3Nlcy5kZXhVVAkAA/Ns+lkOHv1ZdXgL"
131 "AAEEI+UCAASIEwAAS0mt4DIwNmX4qpn7j/2wA7v7N+ZvoQpCJRlVx5SWa4YaiDAxMBQwMDBUhJkI"
132 "MUBBDyMDAzsDRJwFxAdioBDDHAYEYAbiFUAM1M5wAIhFGCGKDIDYAogdgNgDiH2BOAiI0xghekDm"
133 "sQIxGxQzM6ACRijNhCbOhCZfyohdPYyuh8szgtVkMkLsLhAAqeCDi+ejibPZZOZlltgxsDnqZSWW"
134 "JTKwOUFoZh9HayDhZM0g5AMS0M9JzEvX90/KSk0usWZgDAMaws5nAyXBzmpoYGlgAjsAyJoBMp0b"
135 "zQ8gGhbOTEhhzYwU3qxIYc2GFN6MClC/AhUyKUDMAYU9M1Qc5F8GKBscVgIQM0FxCwBQSwECHgMU"
136 "AAAACADojmFLPcugSwoBAAAUAgAACwAYAAAAAAAAAAAAoIEAAAAAY2xhc3Nlcy5kZXhVVAUAA/Ns"
137 "+ll1eAsAAQQj5QIABIgTAABQSwUGAAAAAAEAAQBRAAAATwEAAAAA";
138
139
140class DexoptTest : public testing::Test {
141protected:
142 static constexpr bool kDebug = false;
143 static constexpr uid_t kSystemUid = 1000;
144 static constexpr uid_t kSystemGid = 1000;
145 static constexpr int32_t kOSdkVersion = 25;
146 static constexpr int32_t kAppDataFlags = FLAG_STORAGE_CE | FLAG_STORAGE_DE;
Calin Juravle7d765462017-09-04 15:57:10 -0700147 static constexpr int32_t kTestUserId = 0;
Calin Juravled2affb82017-11-28 17:41:43 -0800148 static constexpr uid_t kTestAppId = 19999;
149
150 const gid_t kTestAppUid = multiuser_get_uid(kTestUserId, kTestAppId);
151 const uid_t kTestAppGid = multiuser_get_shared_gid(kTestUserId, kTestAppId);
Calin Juravle7d765462017-09-04 15:57:10 -0700152
153 InstalldNativeService* service_;
154 std::unique_ptr<std::string> volume_uuid_;
155 std::string package_name_;
156 std::string app_apk_dir_;
157 std::string app_private_dir_ce_;
158 std::string app_private_dir_de_;
159 std::string se_info_;
160
161 int64_t ce_data_inode_;
162
163 std::string secondary_dex_ce_;
164 std::string secondary_dex_ce_link_;
165 std::string secondary_dex_de_;
166
167 virtual void SetUp() {
168 setenv("ANDROID_LOG_TAGS", "*:v", 1);
169 android::base::InitLogging(nullptr);
Calin Juravle29591732017-11-20 17:46:19 -0800170 // Initialize the globals holding the file system main paths (/data/, /system/ etc..).
171 // This is needed in order to compute the application and profile paths.
172 ASSERT_TRUE(init_globals_from_data_and_root());
173 // Initialize selinux log callbacks.
174 // This ensures that selinux is up and running and re-directs the selinux messages
175 // to logcat (in order to make it easier to investigate test results).
176 ASSERT_TRUE(init_selinux());
Calin Juravle7d765462017-09-04 15:57:10 -0700177 service_ = new InstalldNativeService();
178
179 volume_uuid_ = nullptr;
180 package_name_ = "com.installd.test.dexopt";
181 se_info_ = "default";
Calin Juravle7d765462017-09-04 15:57:10 -0700182 app_apk_dir_ = android_app_dir + package_name_;
183
184 create_mock_app();
185 }
186
187 virtual void TearDown() {
188 if (!kDebug) {
189 service_->destroyAppData(
190 volume_uuid_, package_name_, kTestUserId, kAppDataFlags, ce_data_inode_);
191 run_cmd("rm -rf " + app_apk_dir_);
192 run_cmd("rm -rf " + app_private_dir_ce_);
193 run_cmd("rm -rf " + app_private_dir_de_);
194 }
195 delete service_;
196 }
197
198 void create_mock_app() {
199 // Create the oat dir.
200 std::string app_oat_dir = app_apk_dir_ + "/oat";
201 mkdir(app_apk_dir_, kSystemUid, kSystemGid, 0755);
202 service_->createOatDir(app_oat_dir, kRuntimeIsa);
203
204 // Copy the primary apk.
205 std::string apk_path = app_apk_dir_ + "/base.jar";
206 ASSERT_TRUE(WriteBase64ToFile(kDexFile, apk_path, kSystemUid, kSystemGid, 0644));
207
208 // Create the app user data.
209 ASSERT_TRUE(service_->createAppData(
210 volume_uuid_,
211 package_name_,
212 kTestUserId,
213 kAppDataFlags,
214 kTestAppUid,
215 se_info_,
216 kOSdkVersion,
217 &ce_data_inode_).isOk());
218
219 // Create a secondary dex file on CE storage
220 const char* volume_uuid_cstr = volume_uuid_ == nullptr ? nullptr : volume_uuid_->c_str();
221 app_private_dir_ce_ = create_data_user_ce_package_path(
222 volume_uuid_cstr, kTestUserId, package_name_.c_str());
223 secondary_dex_ce_ = app_private_dir_ce_ + "/secondary_ce.jar";
224 ASSERT_TRUE(WriteBase64ToFile(kDexFile, secondary_dex_ce_, kTestAppUid, kTestAppGid, 0600));
225 std::string app_private_dir_ce_link = create_data_user_ce_package_path_as_user_link(
226 volume_uuid_cstr, kTestUserId, package_name_.c_str());
227 secondary_dex_ce_link_ = app_private_dir_ce_link + "/secondary_ce.jar";
228
229 // Create a secondary dex file on DE storage.
230 app_private_dir_de_ = create_data_user_de_package_path(
231 volume_uuid_cstr, kTestUserId, package_name_.c_str());
232 secondary_dex_de_ = app_private_dir_de_ + "/secondary_de.jar";
233 ASSERT_TRUE(WriteBase64ToFile(kDexFile, secondary_dex_de_, kTestAppUid, kTestAppGid, 0600));
234
235 // Fix app data uid.
236 ASSERT_TRUE(service_->fixupAppData(volume_uuid_, kTestUserId).isOk());
237 }
238
239
Calin Juravle29591732017-11-20 17:46:19 -0800240 std::string GetSecondaryDexArtifact(const std::string& path, const std::string& type) {
Calin Juravle7d765462017-09-04 15:57:10 -0700241 std::string::size_type end = path.rfind('.');
242 std::string::size_type start = path.rfind('/', end);
243 return path.substr(0, start) + "/oat/" + kRuntimeIsa + "/" +
244 path.substr(start + 1, end - start) + type;
245 }
246
Calin Juravle29591732017-11-20 17:46:19 -0800247 void CompileSecondaryDex(const std::string& path, int32_t dex_storage_flag,
Calin Juravle7d765462017-09-04 15:57:10 -0700248 bool should_binder_call_succeed, bool should_dex_be_compiled = true,
Calin Juravled2affb82017-11-28 17:41:43 -0800249 int32_t uid = -1) {
250 if (uid == -1) {
251 uid = kTestAppUid;
252 }
Calin Juravle7d765462017-09-04 15:57:10 -0700253 std::unique_ptr<std::string> package_name_ptr(new std::string(package_name_));
254 int32_t dexopt_needed = 0; // does not matter;
255 std::unique_ptr<std::string> out_path = nullptr; // does not matter
256 int32_t dex_flags = DEXOPT_SECONDARY_DEX | dex_storage_flag;
257 std::string compiler_filter = "speed-profile";
258 std::unique_ptr<std::string> class_loader_context_ptr(new std::string("&"));
259 std::unique_ptr<std::string> se_info_ptr(new std::string(se_info_));
260 bool downgrade = false;
David Brazdil570d3982018-01-16 20:15:43 +0000261 int32_t target_sdk_version = 0; // default
Calin Juravle7d765462017-09-04 15:57:10 -0700262
263 binder::Status result = service_->dexopt(path,
264 uid,
265 package_name_ptr,
266 kRuntimeIsa,
267 dexopt_needed,
268 out_path,
269 dex_flags,
270 compiler_filter,
271 volume_uuid_,
272 class_loader_context_ptr,
273 se_info_ptr,
David Brazdil570d3982018-01-16 20:15:43 +0000274 downgrade,
275 target_sdk_version);
Calin Juravle7d765462017-09-04 15:57:10 -0700276 ASSERT_EQ(should_binder_call_succeed, result.isOk());
277 int expected_access = should_dex_be_compiled ? 0 : -1;
Calin Juravle29591732017-11-20 17:46:19 -0800278 std::string odex = GetSecondaryDexArtifact(path, "odex");
279 std::string vdex = GetSecondaryDexArtifact(path, "vdex");
280 std::string art = GetSecondaryDexArtifact(path, "art");
Calin Juravle7d765462017-09-04 15:57:10 -0700281 ASSERT_EQ(expected_access, access(odex.c_str(), R_OK));
282 ASSERT_EQ(expected_access, access(vdex.c_str(), R_OK));
283 ASSERT_EQ(-1, access(art.c_str(), R_OK)); // empty profiles do not generate an image.
284 }
285
286 void reconcile_secondary_dex(const std::string& path, int32_t storage_flag,
287 bool should_binder_call_succeed, bool should_dex_exist, bool should_dex_be_deleted,
Calin Juravled2affb82017-11-28 17:41:43 -0800288 int32_t uid = -1, std::string* package_override = nullptr) {
289 if (uid == -1) {
290 uid = kTestAppUid;
291 }
Calin Juravle7d765462017-09-04 15:57:10 -0700292 std::vector<std::string> isas;
293 isas.push_back(kRuntimeIsa);
294 bool out_secondary_dex_exists = false;
295 binder::Status result = service_->reconcileSecondaryDexFile(
296 path,
297 package_override == nullptr ? package_name_ : *package_override,
298 uid,
299 isas,
300 volume_uuid_,
301 storage_flag,
302 &out_secondary_dex_exists);
303
304 ASSERT_EQ(should_binder_call_succeed, result.isOk());
305 ASSERT_EQ(should_dex_exist, out_secondary_dex_exists);
306
307 int expected_access = should_dex_be_deleted ? -1 : 0;
Calin Juravle29591732017-11-20 17:46:19 -0800308 std::string odex = GetSecondaryDexArtifact(path, "odex");
309 std::string vdex = GetSecondaryDexArtifact(path, "vdex");
310 std::string art = GetSecondaryDexArtifact(path, "art");
Calin Juravle7d765462017-09-04 15:57:10 -0700311 ASSERT_EQ(expected_access, access(odex.c_str(), F_OK));
312 ASSERT_EQ(expected_access, access(vdex.c_str(), F_OK));
313 ASSERT_EQ(-1, access(art.c_str(), R_OK)); // empty profiles do not generate an image.
314 }
Calin Juravle29591732017-11-20 17:46:19 -0800315
316 void CheckFileAccess(const std::string& file, uid_t uid, gid_t gid, mode_t mode) {
317 struct stat st;
318 ASSERT_EQ(0, stat(file.c_str(), &st));
319 ASSERT_EQ(uid, st.st_uid);
320 ASSERT_EQ(gid, st.st_gid);
321 ASSERT_EQ(mode, st.st_mode);
322 }
Calin Juravle7d765462017-09-04 15:57:10 -0700323};
324
325
326TEST_F(DexoptTest, DexoptSecondaryCe) {
327 LOG(INFO) << "DexoptSecondaryCe";
Calin Juravle29591732017-11-20 17:46:19 -0800328 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700329 /*binder_ok*/ true, /*compile_ok*/ true);
330}
331
332TEST_F(DexoptTest, DexoptSecondaryCeLink) {
333 LOG(INFO) << "DexoptSecondaryCeLink";
Calin Juravle29591732017-11-20 17:46:19 -0800334 CompileSecondaryDex(secondary_dex_ce_link_, DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700335 /*binder_ok*/ true, /*compile_ok*/ true);
336}
337
338TEST_F(DexoptTest, DexoptSecondaryDe) {
339 LOG(INFO) << "DexoptSecondaryDe";
Calin Juravle29591732017-11-20 17:46:19 -0800340 CompileSecondaryDex(secondary_dex_de_, DEXOPT_STORAGE_DE,
Calin Juravle7d765462017-09-04 15:57:10 -0700341 /*binder_ok*/ true, /*compile_ok*/ true);
342}
343
344TEST_F(DexoptTest, DexoptSecondaryDoesNotExist) {
345 LOG(INFO) << "DexoptSecondaryDoesNotExist";
346 // If the file validates but does not exist we do not treat it as an error.
Calin Juravle29591732017-11-20 17:46:19 -0800347 CompileSecondaryDex(secondary_dex_ce_ + "not.there", DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700348 /*binder_ok*/ true, /*compile_ok*/ false);
349}
350
351TEST_F(DexoptTest, DexoptSecondaryStorageValidationError) {
352 LOG(INFO) << "DexoptSecondaryStorageValidationError";
Calin Juravle29591732017-11-20 17:46:19 -0800353 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_DE,
Calin Juravle7d765462017-09-04 15:57:10 -0700354 /*binder_ok*/ false, /*compile_ok*/ false);
355}
356
357TEST_F(DexoptTest, DexoptSecondaryAppOwnershipValidationError) {
358 LOG(INFO) << "DexoptSecondaryAppOwnershipValidationError";
Calin Juravle29591732017-11-20 17:46:19 -0800359 CompileSecondaryDex("/data/data/random.app/secondary.jar", DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700360 /*binder_ok*/ false, /*compile_ok*/ false);
361}
362
363TEST_F(DexoptTest, DexoptSecondaryAcessViaDifferentUidError) {
364 LOG(INFO) << "DexoptSecondaryAcessViaDifferentUidError";
Calin Juravle29591732017-11-20 17:46:19 -0800365 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700366 /*binder_ok*/ false, /*compile_ok*/ false, kSystemUid);
367}
368
369
370class ReconcileTest : public DexoptTest {
371 virtual void SetUp() {
372 DexoptTest::SetUp();
Calin Juravle29591732017-11-20 17:46:19 -0800373 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700374 /*binder_ok*/ true, /*compile_ok*/ true);
Calin Juravle29591732017-11-20 17:46:19 -0800375 CompileSecondaryDex(secondary_dex_de_, DEXOPT_STORAGE_DE,
Calin Juravle7d765462017-09-04 15:57:10 -0700376 /*binder_ok*/ true, /*compile_ok*/ true);
377 }
378};
379
380TEST_F(ReconcileTest, ReconcileSecondaryCeExists) {
381 LOG(INFO) << "ReconcileSecondaryCeExists";
382 reconcile_secondary_dex(secondary_dex_ce_, FLAG_STORAGE_CE,
383 /*binder_ok*/ true, /*dex_ok */ true, /*odex_deleted*/ false);
384}
385
386TEST_F(ReconcileTest, ReconcileSecondaryCeLinkExists) {
387 LOG(INFO) << "ReconcileSecondaryCeLinkExists";
388 reconcile_secondary_dex(secondary_dex_ce_link_, FLAG_STORAGE_CE,
389 /*binder_ok*/ true, /*dex_ok */ true, /*odex_deleted*/ false);
390}
391
392TEST_F(ReconcileTest, ReconcileSecondaryDeExists) {
393 LOG(INFO) << "ReconcileSecondaryDeExists";
394 reconcile_secondary_dex(secondary_dex_de_, FLAG_STORAGE_DE,
395 /*binder_ok*/ true, /*dex_ok */ true, /*odex_deleted*/ false);
396}
397
398TEST_F(ReconcileTest, ReconcileSecondaryDeDoesNotExist) {
399 LOG(INFO) << "ReconcileSecondaryDeDoesNotExist";
400 run_cmd("rm -rf " + secondary_dex_de_);
401 reconcile_secondary_dex(secondary_dex_de_, FLAG_STORAGE_DE,
402 /*binder_ok*/ true, /*dex_ok */ false, /*odex_deleted*/ true);
403}
404
405TEST_F(ReconcileTest, ReconcileSecondaryStorageValidationError) {
406 // Validation errors will not clean the odex/vdex/art files but will mark
407 // the file as non existent so that the PM knows it should purge it from its
408 // records.
409 LOG(INFO) << "ReconcileSecondaryStorageValidationError";
410 reconcile_secondary_dex(secondary_dex_ce_, FLAG_STORAGE_DE,
411 /*binder_ok*/ true, /*dex_ok */ false, /*odex_deleted*/ false);
412}
413
414TEST_F(ReconcileTest, ReconcileSecondaryAppOwnershipValidationError) {
415 LOG(INFO) << "ReconcileSecondaryAppOwnershipValidationError";
416 // Attempt to reconcile the dex files of the test app from a different app.
417 std::string another_app = "another.app";
418 reconcile_secondary_dex(secondary_dex_ce_, FLAG_STORAGE_CE,
419 /*binder_ok*/ true, /*dex_ok */ false, /*odex_deleted*/ false, kSystemUid, &another_app);
420}
421
422TEST_F(ReconcileTest, ReconcileSecondaryAcessViaDifferentUidError) {
423 LOG(INFO) << "ReconcileSecondaryAcessViaDifferentUidError";
424 reconcile_secondary_dex(secondary_dex_ce_, FLAG_STORAGE_CE,
425 /*binder_ok*/ true, /*dex_ok */ false, /*odex_deleted*/ false, kSystemUid);
426}
427
Calin Juravle29591732017-11-20 17:46:19 -0800428class ProfileTest : public DexoptTest {
429 protected:
430 std::string cur_profile_;
431 std::string ref_profile_;
432 std::string snap_profile_;
433
Calin Juravle824a64d2018-01-18 20:23:17 -0800434 static constexpr const char* kPrimaryProfile = "primary.prof";
435
Calin Juravle29591732017-11-20 17:46:19 -0800436 virtual void SetUp() {
437 DexoptTest::SetUp();
438 cur_profile_ = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -0800439 kTestUserId, package_name_, kPrimaryProfile, /*is_secondary_dex*/ false);
440 ref_profile_ = create_reference_profile_path(package_name_, kPrimaryProfile,
441 /*is_secondary_dex*/ false);
442 snap_profile_ = create_snapshot_profile_path(package_name_, kPrimaryProfile);
Calin Juravle29591732017-11-20 17:46:19 -0800443 }
444
Calin Juravle824a64d2018-01-18 20:23:17 -0800445 void SetupProfile(const std::string& path, uid_t uid, gid_t gid, mode_t mode,
446 int32_t num_dex) {
447 run_cmd("profman --generate-test-profile-seed=" + std::to_string(num_dex) +
448 " --generate-test-profile-num-dex=" + std::to_string(num_dex) +
449 " --generate-test-profile=" + path);
Calin Juravle29591732017-11-20 17:46:19 -0800450 ::chmod(path.c_str(), mode);
451 ::chown(path.c_str(), uid, gid);
452 }
453
454 void SetupProfiles(bool setup_ref) {
455 SetupProfile(cur_profile_, kTestAppUid, kTestAppGid, 0600, 1);
456 if (setup_ref) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800457 SetupProfile(ref_profile_, kTestAppUid, kTestAppGid, 0600, 2);
Calin Juravle29591732017-11-20 17:46:19 -0800458 }
459 }
460
Calin Juravlec3596c32017-12-05 12:29:15 -0800461 void createProfileSnapshot(int32_t appid, const std::string& package_name,
462 bool expected_result) {
Calin Juravle29591732017-11-20 17:46:19 -0800463 bool result;
Calin Juravlec3596c32017-12-05 12:29:15 -0800464 binder::Status binder_result = service_->createProfileSnapshot(
Calin Juravle824a64d2018-01-18 20:23:17 -0800465 appid, package_name, kPrimaryProfile, &result);
Calin Juravle29591732017-11-20 17:46:19 -0800466 ASSERT_TRUE(binder_result.isOk());
467 ASSERT_EQ(expected_result, result);
468
469 if (!expected_result) {
470 // Do not check the files if we expect to fail.
471 return;
472 }
473
474 // Check that the snapshot was created witht he expected acess flags.
475 CheckFileAccess(snap_profile_, kSystemUid, kSystemGid, 0600 | S_IFREG);
476
477 // The snapshot should be equivalent to the merge of profiles.
478 std::string expected_profile_content = snap_profile_ + ".expected";
479 run_cmd("rm -f " + expected_profile_content);
480 run_cmd("touch " + expected_profile_content);
481 run_cmd("profman --profile-file=" + cur_profile_ +
482 " --profile-file=" + ref_profile_ +
483 " --reference-profile-file=" + expected_profile_content);
484
485 ASSERT_TRUE(AreFilesEqual(expected_profile_content, snap_profile_));
486
487 pid_t pid = fork();
488 if (pid == 0) {
489 /* child */
490 TransitionToSystemServer();
491
492 // System server should be able to open the the spanshot.
493 unique_fd fd(open(snap_profile_.c_str(), O_RDONLY));
494 ASSERT_TRUE(fd > -1) << "Failed to open profile as kSystemUid: " << strerror(errno);
495 _exit(0);
496 }
497 /* parent */
498 ASSERT_TRUE(WIFEXITED(wait_child(pid)));
499 }
500
Calin Juravle824a64d2018-01-18 20:23:17 -0800501 void mergePackageProfiles(const std::string& package_name, bool expected_result) {
502 bool result;
503 binder::Status binder_result = service_->mergeProfiles(
504 kTestAppUid, package_name, &result);
505 ASSERT_TRUE(binder_result.isOk());
506 ASSERT_EQ(expected_result, result);
507
508 if (!expected_result) {
509 // Do not check the files if we expect to fail.
510 return;
511 }
512
513 // Check that the snapshot was created witht he expected acess flags.
514 CheckFileAccess(ref_profile_, kTestAppUid, kTestAppUid, 0600 | S_IFREG);
515
516 // The snapshot should be equivalent to the merge of profiles.
517 std::string ref_profile_content = ref_profile_ + ".expected";
518 run_cmd("rm -f " + ref_profile_content);
519 run_cmd("touch " + ref_profile_content);
520 run_cmd("profman --profile-file=" + cur_profile_ +
521 " --profile-file=" + ref_profile_ +
522 " --reference-profile-file=" + ref_profile_content);
523
524 ASSERT_TRUE(AreFilesEqual(ref_profile_content, ref_profile_));
525 }
526
Calin Juravlec3b049e2018-01-18 22:32:58 -0800527 // TODO(calin): add dex metadata tests once the ART change is merged.
528 void preparePackageProfile(const std::string& package_name, const std::string& profile_name,
529 bool expected_result) {
530 bool result;
531 binder::Status binder_result = service_->prepareAppProfile(
532 package_name, kTestUserId, kTestAppId, profile_name, /*code path*/ "base.apk",
533 /*dex_metadata*/ nullptr, &result);
534 ASSERT_TRUE(binder_result.isOk());
535 ASSERT_EQ(expected_result, result);
536
537 if (!expected_result) {
538 // Do not check the files if we expect to fail.
539 return;
540 }
541
542 std::string code_path_cur_prof = create_current_profile_path(
543 kTestUserId, package_name, profile_name, /*is_secondary_dex*/ false);
544 std::string code_path_ref_profile = create_reference_profile_path(package_name,
545 profile_name, /*is_secondary_dex*/ false);
546
547 // Check that we created the current profile.
548 CheckFileAccess(code_path_cur_prof, kTestAppUid, kTestAppUid, 0600 | S_IFREG);
549
550 // Without dex metadata we don't generate a reference profile.
551 ASSERT_EQ(-1, access(code_path_ref_profile.c_str(), R_OK));
552 }
553
Calin Juravle29591732017-11-20 17:46:19 -0800554 private:
555 void TransitionToSystemServer() {
556 ASSERT_TRUE(DropCapabilities(kSystemUid, kSystemGid));
557 int32_t res = selinux_android_setcontext(
558 kSystemUid, true, se_info_.c_str(), "system_server");
559 ASSERT_EQ(0, res) << "Failed to setcon " << strerror(errno);
560 }
561
562 bool AreFilesEqual(const std::string& file1, const std::string& file2) {
563 std::vector<uint8_t> content1;
564 std::vector<uint8_t> content2;
565
566 if (!ReadAll(file1, &content1)) return false;
567 if (!ReadAll(file2, &content2)) return false;
568 return content1 == content2;
569 }
570
571 bool ReadAll(const std::string& file, std::vector<uint8_t>* content) {
572 unique_fd fd(open(file.c_str(), O_RDONLY));
573 if (fd < 0) {
574 PLOG(ERROR) << "Failed to open " << file;
575 return false;
576 }
577 struct stat st;
578 if (fstat(fd, &st) != 0) {
579 PLOG(ERROR) << "Failed to stat " << file;
580 return false;
581 }
582 content->resize(st.st_size);
583 bool result = ReadFully(fd, content->data(), content->size());
584 if (!result) {
585 PLOG(ERROR) << "Failed to read " << file;
586 }
587 return result;
588 }
589};
590
591TEST_F(ProfileTest, ProfileSnapshotOk) {
592 LOG(INFO) << "ProfileSnapshotOk";
593
594 SetupProfiles(/*setup_ref*/ true);
Calin Juravlec3596c32017-12-05 12:29:15 -0800595 createProfileSnapshot(kTestAppId, package_name_, /*expected_result*/ true);
Calin Juravle29591732017-11-20 17:46:19 -0800596}
597
598// The reference profile is created on the fly. We need to be able to
599// snapshot without one.
600TEST_F(ProfileTest, ProfileSnapshotOkNoReference) {
601 LOG(INFO) << "ProfileSnapshotOkNoReference";
602
603 SetupProfiles(/*setup_ref*/ false);
Calin Juravlec3596c32017-12-05 12:29:15 -0800604 createProfileSnapshot(kTestAppId, package_name_, /*expected_result*/ true);
Calin Juravle29591732017-11-20 17:46:19 -0800605}
606
607TEST_F(ProfileTest, ProfileSnapshotFailWrongPackage) {
608 LOG(INFO) << "ProfileSnapshotFailWrongPackage";
609
610 SetupProfiles(/*setup_ref*/ true);
Calin Juravlec3596c32017-12-05 12:29:15 -0800611 createProfileSnapshot(kTestAppId, "not.there", /*expected_result*/ false);
Calin Juravle29591732017-11-20 17:46:19 -0800612}
613
614TEST_F(ProfileTest, ProfileSnapshotDestroySnapshot) {
615 LOG(INFO) << "ProfileSnapshotDestroySnapshot";
616
617 SetupProfiles(/*setup_ref*/ true);
Calin Juravlec3596c32017-12-05 12:29:15 -0800618 createProfileSnapshot(kTestAppId, package_name_, /*expected_result*/ true);
Calin Juravle29591732017-11-20 17:46:19 -0800619
Calin Juravle824a64d2018-01-18 20:23:17 -0800620 binder::Status binder_result = service_->destroyProfileSnapshot(package_name_, kPrimaryProfile);
Calin Juravle29591732017-11-20 17:46:19 -0800621 ASSERT_TRUE(binder_result.isOk());
622 struct stat st;
623 ASSERT_EQ(-1, stat(snap_profile_.c_str(), &st));
624 ASSERT_EQ(ENOENT, errno);
625}
626
Calin Juravle824a64d2018-01-18 20:23:17 -0800627TEST_F(ProfileTest, ProfileMergeOk) {
628 LOG(INFO) << "ProfileMergeOk";
629
630 SetupProfiles(/*setup_ref*/ true);
631 mergePackageProfiles(package_name_, /*expected_result*/ true);
632}
633
634// The reference profile is created on the fly. We need to be able to
635// merge without one.
636TEST_F(ProfileTest, ProfileMergeOkNoReference) {
637 LOG(INFO) << "ProfileMergeOkNoReference";
638
639 SetupProfiles(/*setup_ref*/ false);
640 mergePackageProfiles(package_name_, /*expected_result*/ true);
641}
642
643TEST_F(ProfileTest, ProfileMergeFailWrongPackage) {
644 LOG(INFO) << "ProfileMergeFailWrongPackage";
645
646 SetupProfiles(/*setup_ref*/ true);
647 mergePackageProfiles("not.there", /*expected_result*/ false);
648}
649
Calin Juravled2affb82017-11-28 17:41:43 -0800650TEST_F(ProfileTest, ProfileDirOk) {
651 LOG(INFO) << "ProfileDirOk";
652
653 std::string cur_profile_dir = create_primary_current_profile_package_dir_path(
654 kTestUserId, package_name_);
655 std::string cur_profile_file = create_current_profile_path(kTestUserId, package_name_,
Calin Juravle824a64d2018-01-18 20:23:17 -0800656 kPrimaryProfile, /*is_secondary_dex*/false);
Calin Juravled2affb82017-11-28 17:41:43 -0800657 std::string ref_profile_dir = create_primary_reference_profile_package_dir_path(package_name_);
658
659 CheckFileAccess(cur_profile_dir, kTestAppUid, kTestAppUid, 0700 | S_IFDIR);
660 CheckFileAccess(cur_profile_file, kTestAppUid, kTestAppUid, 0600 | S_IFREG);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800661 CheckFileAccess(ref_profile_dir, kSystemUid, kTestAppGid, 0770 | S_IFDIR);
662}
663
664// Verify that the profile directories are fixed up during an upgrade.
665// (The reference profile directory is prepared lazily).
666TEST_F(ProfileTest, ProfileDirOkAfterFixup) {
667 LOG(INFO) << "ProfileDirOkAfterFixup";
668
669 std::string cur_profile_dir = create_primary_current_profile_package_dir_path(
670 kTestUserId, package_name_);
671 std::string cur_profile_file = create_current_profile_path(kTestUserId, package_name_,
Calin Juravle824a64d2018-01-18 20:23:17 -0800672 kPrimaryProfile, /*is_secondary_dex*/false);
Calin Juravle6f06eb62017-11-28 18:44:53 -0800673 std::string ref_profile_dir = create_primary_reference_profile_package_dir_path(package_name_);
674
675 // Simulate a pre-P setup by changing the owner to kTestAppGid and permissions to 0700.
676 ASSERT_EQ(0, chown(ref_profile_dir.c_str(), kTestAppGid, kTestAppGid));
677 ASSERT_EQ(0, chmod(ref_profile_dir.c_str(), 0700));
678
679 // Run createAppData again which will offer to fix-up the profile directories.
680 ASSERT_TRUE(service_->createAppData(
681 volume_uuid_,
682 package_name_,
683 kTestUserId,
684 kAppDataFlags,
685 kTestAppUid,
686 se_info_,
687 kOSdkVersion,
688 &ce_data_inode_).isOk());
689
690 // Check the file access.
691 CheckFileAccess(cur_profile_dir, kTestAppUid, kTestAppUid, 0700 | S_IFDIR);
692 CheckFileAccess(cur_profile_file, kTestAppUid, kTestAppUid, 0600 | S_IFREG);
693 CheckFileAccess(ref_profile_dir, kSystemUid, kTestAppGid, 0770 | S_IFDIR);
Calin Juravled2affb82017-11-28 17:41:43 -0800694}
695
Calin Juravlec3b049e2018-01-18 22:32:58 -0800696TEST_F(ProfileTest, ProfilePrepareOk) {
697 LOG(INFO) << "ProfilePrepareOk";
698 preparePackageProfile(package_name_, "split.prof", /*expected_result*/ true);
699}
700
701TEST_F(ProfileTest, ProfilePrepareFailInvalidPackage) {
702 LOG(INFO) << "ProfilePrepareFailInvalidPackage";
703 preparePackageProfile("not.there.package", "split.prof", /*expected_result*/ false);
704}
705
706TEST_F(ProfileTest, ProfilePrepareFailProfileChangedUid) {
707 LOG(INFO) << "ProfilePrepareFailProfileChangedUid";
708 SetupProfiles(/*setup_ref*/ false);
709 // Change the uid on the profile to trigger a failure.
710 ::chown(cur_profile_.c_str(), kTestAppUid + 1, kTestAppGid + 1);
711 preparePackageProfile(package_name_, "primary.prof", /*expected_result*/ false);
712}
713
Calin Juravle7d765462017-09-04 15:57:10 -0700714} // namespace installd
715} // namespace android