blob: 0212bc55648ccf4b3ac48cb574c8eca921ba4da4 [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 Juravle0d0a4922018-01-23 19:54:11 -080017#include <cstdlib>
Calin Juravle29591732017-11-20 17:46:19 -080018#include <fcntl.h>
Calin Juravle7d765462017-09-04 15:57:10 -070019#include <stdlib.h>
20#include <string.h>
Calin Juravle29591732017-11-20 17:46:19 -080021#include <sys/types.h>
22#include <sys/stat.h>
Calin Juravle7d765462017-09-04 15:57:10 -070023
Calin Juravle29591732017-11-20 17:46:19 -080024#include <android-base/file.h>
Calin Juravle7d765462017-09-04 15:57:10 -070025#include <android-base/logging.h>
Mathieu Chartierd41622c2019-01-31 12:59:39 -080026#include <android-base/properties.h>
27#include <android-base/scopeguard.h>
Calin Juravle7d765462017-09-04 15:57:10 -070028#include <android-base/stringprintf.h>
Calin Juravle29591732017-11-20 17:46:19 -080029#include <android-base/unique_fd.h>
Andreas Gampef448ced2019-01-31 09:22:27 -080030#include <binder/Status.h>
Calin Juravle7d765462017-09-04 15:57:10 -070031#include <cutils/properties.h>
Calin Juravle29591732017-11-20 17:46:19 -080032
Calin Juravle7d765462017-09-04 15:57:10 -070033#include <gtest/gtest.h>
34
Calin Juravle29591732017-11-20 17:46:19 -080035#include <selinux/android.h>
36#include <selinux/avc.h>
37
Andreas Gampef448ced2019-01-31 09:22:27 -080038#include "binder_test_utils.h"
Calin Juravle7d765462017-09-04 15:57:10 -070039#include "dexopt.h"
40#include "InstalldNativeService.h"
41#include "globals.h"
42#include "tests/test_utils.h"
43#include "utils.h"
liulvping61907742018-08-21 09:36:52 +080044#include "ziparchive/zip_writer.h"
Calin Juravle7d765462017-09-04 15:57:10 -070045
Calin Juravle29591732017-11-20 17:46:19 -080046using android::base::ReadFully;
47using android::base::unique_fd;
48
Calin Juravle7d765462017-09-04 15:57:10 -070049namespace android {
50namespace installd {
51
52// TODO(calin): try to dedup this code.
53#if defined(__arm__)
54static const std::string kRuntimeIsa = "arm";
55#elif defined(__aarch64__)
56static const std::string kRuntimeIsa = "arm64";
57#elif defined(__mips__) && !defined(__LP64__)
58static const std::string kRuntimeIsa = "mips";
59#elif defined(__mips__) && defined(__LP64__)
60static const std::string kRuntimeIsa = "mips64";
61#elif defined(__i386__)
62static const std::string kRuntimeIsa = "x86";
63#elif defined(__x86_64__)
64static const std::string kRuntimeIsa = "x86_64";
65#else
66static const std::string kRuntimeIsa = "none";
67#endif
68
69int get_property(const char *key, char *value, const char *default_value) {
70 return property_get(key, value, default_value);
71}
72
73bool calculate_oat_file_path(char path[PKG_PATH_MAX], const char *oat_dir, const char *apk_path,
74 const char *instruction_set) {
75 return calculate_oat_file_path_default(path, oat_dir, apk_path, instruction_set);
76}
77
78bool calculate_odex_file_path(char path[PKG_PATH_MAX], const char *apk_path,
79 const char *instruction_set) {
80 return calculate_odex_file_path_default(path, apk_path, instruction_set);
81}
82
83bool create_cache_path(char path[PKG_PATH_MAX], const char *src, const char *instruction_set) {
84 return create_cache_path_default(path, src, instruction_set);
85}
86
87static void run_cmd(const std::string& cmd) {
88 system(cmd.c_str());
89}
90
Mathieu Chartierd41622c2019-01-31 12:59:39 -080091template <typename Visitor>
92static void run_cmd_and_process_output(const std::string& cmd, const Visitor& visitor) {
93 FILE* file = popen(cmd.c_str(), "r");
94 CHECK(file != nullptr) << "Failed to ptrace " << cmd;
95 char* line = nullptr;
96 while (true) {
97 size_t n = 0u;
98 ssize_t value = getline(&line, &n, file);
99 if (value == -1) {
100 break;
101 }
102 visitor(line);
103 }
104 free(line);
105 fclose(file);
106}
107
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700108static int mkdir(const std::string& path, uid_t owner, gid_t group, mode_t mode) {
109 int ret = ::mkdir(path.c_str(), mode);
110 if (ret != 0) {
111 return ret;
112 }
113 ret = ::chown(path.c_str(), owner, group);
114 if (ret != 0) {
115 return ret;
116 }
117 return ::chmod(path.c_str(), mode);
Calin Juravle7d765462017-09-04 15:57:10 -0700118}
119
Calin Juravle29591732017-11-20 17:46:19 -0800120static int log_callback(int type, const char *fmt, ...) { // NOLINT
121 va_list ap;
122 int priority;
123
124 switch (type) {
125 case SELINUX_WARNING:
126 priority = ANDROID_LOG_WARN;
127 break;
128 case SELINUX_INFO:
129 priority = ANDROID_LOG_INFO;
130 break;
131 default:
132 priority = ANDROID_LOG_ERROR;
133 break;
134 }
135 va_start(ap, fmt);
136 LOG_PRI_VA(priority, "SELinux", fmt, ap);
137 va_end(ap);
138 return 0;
139}
140
141static bool init_selinux() {
142 int selinux_enabled = (is_selinux_enabled() > 0);
143
144 union selinux_callback cb;
145 cb.func_log = log_callback;
146 selinux_set_callback(SELINUX_CB_LOG, cb);
147
148 if (selinux_enabled && selinux_status_open(true) < 0) {
149 LOG(ERROR) << "Could not open selinux status; exiting";
150 return false;
151 }
152
153 return true;
154}
155
Calin Juravle7d765462017-09-04 15:57:10 -0700156// Base64 encoding of a simple dex files with 2 methods.
157static const char kDexFile[] =
158 "UEsDBBQAAAAIAOiOYUs9y6BLCgEAABQCAAALABwAY2xhc3Nlcy5kZXhVVAkAA/Ns+lkOHv1ZdXgL"
159 "AAEEI+UCAASIEwAAS0mt4DIwNmX4qpn7j/2wA7v7N+ZvoQpCJRlVx5SWa4YaiDAxMBQwMDBUhJkI"
160 "MUBBDyMDAzsDRJwFxAdioBDDHAYEYAbiFUAM1M5wAIhFGCGKDIDYAogdgNgDiH2BOAiI0xghekDm"
161 "sQIxGxQzM6ACRijNhCbOhCZfyohdPYyuh8szgtVkMkLsLhAAqeCDi+ejibPZZOZlltgxsDnqZSWW"
162 "JTKwOUFoZh9HayDhZM0g5AMS0M9JzEvX90/KSk0usWZgDAMaws5nAyXBzmpoYGlgAjsAyJoBMp0b"
163 "zQ8gGhbOTEhhzYwU3qxIYc2GFN6MClC/AhUyKUDMAYU9M1Qc5F8GKBscVgIQM0FxCwBQSwECHgMU"
164 "AAAACADojmFLPcugSwoBAAAUAgAACwAYAAAAAAAAAAAAoIEAAAAAY2xhc3Nlcy5kZXhVVAUAA/Ns"
165 "+ll1eAsAAQQj5QIABIgTAABQSwUGAAAAAAEAAQBRAAAATwEAAAAA";
166
Andreas Gampe1b8700f2018-11-01 14:47:00 -0700167class DexoptTestEnvTest : public testing::Test {
168};
169
170TEST_F(DexoptTestEnvTest, CheckSelinux) {
171 ASSERT_EQ(1, is_selinux_enabled());
172
173 // Crude cutout for virtual devices.
174#if !defined(__i386__) && !defined(__x86_64__)
175 constexpr bool kIsX86 = false;
176#else
177 constexpr bool kIsX86 = true;
178#endif
Andreas Gampe1d1e7c92018-11-05 09:46:28 -0800179 ASSERT_TRUE(1 == security_getenforce() || kIsX86 || true /* b/119032200 */);
Andreas Gampe1b8700f2018-11-01 14:47:00 -0700180}
Calin Juravle7d765462017-09-04 15:57:10 -0700181
182class DexoptTest : public testing::Test {
183protected:
184 static constexpr bool kDebug = false;
185 static constexpr uid_t kSystemUid = 1000;
186 static constexpr uid_t kSystemGid = 1000;
187 static constexpr int32_t kOSdkVersion = 25;
188 static constexpr int32_t kAppDataFlags = FLAG_STORAGE_CE | FLAG_STORAGE_DE;
Calin Juravle7d765462017-09-04 15:57:10 -0700189 static constexpr int32_t kTestUserId = 0;
Calin Juravled2affb82017-11-28 17:41:43 -0800190 static constexpr uid_t kTestAppId = 19999;
191
192 const gid_t kTestAppUid = multiuser_get_uid(kTestUserId, kTestAppId);
193 const uid_t kTestAppGid = multiuser_get_shared_gid(kTestUserId, kTestAppId);
Calin Juravle7d765462017-09-04 15:57:10 -0700194
195 InstalldNativeService* service_;
196 std::unique_ptr<std::string> volume_uuid_;
197 std::string package_name_;
Calin Juravle0d0a4922018-01-23 19:54:11 -0800198 std::string apk_path_;
liulvping61907742018-08-21 09:36:52 +0800199 std::string empty_dm_file_;
Calin Juravle7d765462017-09-04 15:57:10 -0700200 std::string app_apk_dir_;
201 std::string app_private_dir_ce_;
202 std::string app_private_dir_de_;
203 std::string se_info_;
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000204 std::string app_oat_dir_;
Calin Juravle7d765462017-09-04 15:57:10 -0700205
206 int64_t ce_data_inode_;
207
208 std::string secondary_dex_ce_;
209 std::string secondary_dex_ce_link_;
210 std::string secondary_dex_de_;
211
212 virtual void SetUp() {
213 setenv("ANDROID_LOG_TAGS", "*:v", 1);
214 android::base::InitLogging(nullptr);
Calin Juravle29591732017-11-20 17:46:19 -0800215 // Initialize the globals holding the file system main paths (/data/, /system/ etc..).
216 // This is needed in order to compute the application and profile paths.
217 ASSERT_TRUE(init_globals_from_data_and_root());
218 // Initialize selinux log callbacks.
219 // This ensures that selinux is up and running and re-directs the selinux messages
220 // to logcat (in order to make it easier to investigate test results).
221 ASSERT_TRUE(init_selinux());
Calin Juravle7d765462017-09-04 15:57:10 -0700222 service_ = new InstalldNativeService();
223
224 volume_uuid_ = nullptr;
225 package_name_ = "com.installd.test.dexopt";
226 se_info_ = "default";
Calin Juravle7d765462017-09-04 15:57:10 -0700227 app_apk_dir_ = android_app_dir + package_name_;
228
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700229 ASSERT_TRUE(create_mock_app());
Calin Juravle7d765462017-09-04 15:57:10 -0700230 }
231
232 virtual void TearDown() {
233 if (!kDebug) {
234 service_->destroyAppData(
235 volume_uuid_, package_name_, kTestUserId, kAppDataFlags, ce_data_inode_);
236 run_cmd("rm -rf " + app_apk_dir_);
237 run_cmd("rm -rf " + app_private_dir_ce_);
238 run_cmd("rm -rf " + app_private_dir_de_);
239 }
240 delete service_;
241 }
242
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700243 ::testing::AssertionResult create_mock_app() {
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800244 // For debug mode, the directory might already exist. Avoid erroring out.
245 if (mkdir(app_apk_dir_, kSystemUid, kSystemGid, 0755) != 0 && !kDebug) {
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700246 return ::testing::AssertionFailure() << "Could not create app dir " << app_apk_dir_
247 << " : " << strerror(errno);
248 }
Alex Buynytskyy17d8f822019-06-20 16:29:57 -0700249
250 // Initialize the oat dir path.
251 app_oat_dir_ = app_apk_dir_ + "/oat";
Calin Juravle7d765462017-09-04 15:57:10 -0700252
253 // Copy the primary apk.
Calin Juravle0d0a4922018-01-23 19:54:11 -0800254 apk_path_ = app_apk_dir_ + "/base.jar";
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700255 std::string error_msg;
256 if (!WriteBase64ToFile(kDexFile, apk_path_, kSystemUid, kSystemGid, 0644, &error_msg)) {
257 return ::testing::AssertionFailure() << "Could not write base64 file to " << apk_path_
258 << " : " << error_msg;
259 }
Calin Juravle7d765462017-09-04 15:57:10 -0700260
liulvping61907742018-08-21 09:36:52 +0800261 // Create an empty dm file.
262 empty_dm_file_ = apk_path_ + ".dm";
263 {
264 int fd = open(empty_dm_file_.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
265 if (fd < 0) {
266 return ::testing::AssertionFailure() << "Could not open " << empty_dm_file_;
267 }
268 FILE* file = fdopen(fd, "wb");
269 if (file == nullptr) {
270 return ::testing::AssertionFailure() << "Null file for " << empty_dm_file_
271 << " fd=" << fd;
272 }
273 ZipWriter writer(file);
274 // Add vdex to zip.
275 writer.StartEntry("primary.prof", ZipWriter::kCompress);
276 writer.FinishEntry();
277 writer.Finish();
Josh Gao1197f722019-08-09 14:33:34 -0700278 fclose(file);
liulvping61907742018-08-21 09:36:52 +0800279 }
280
Calin Juravle7d765462017-09-04 15:57:10 -0700281 // Create the app user data.
Alex Buynytskyy17d8f822019-06-20 16:29:57 -0700282 binder::Status status = service_->createAppData(
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700283 volume_uuid_,
284 package_name_,
285 kTestUserId,
286 kAppDataFlags,
287 kTestAppUid,
288 se_info_,
289 kOSdkVersion,
290 &ce_data_inode_);
291 if (!status.isOk()) {
292 return ::testing::AssertionFailure() << "Could not create app data: "
293 << status.toString8().c_str();
294 }
Calin Juravle7d765462017-09-04 15:57:10 -0700295
296 // Create a secondary dex file on CE storage
297 const char* volume_uuid_cstr = volume_uuid_ == nullptr ? nullptr : volume_uuid_->c_str();
298 app_private_dir_ce_ = create_data_user_ce_package_path(
299 volume_uuid_cstr, kTestUserId, package_name_.c_str());
300 secondary_dex_ce_ = app_private_dir_ce_ + "/secondary_ce.jar";
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700301 if (!WriteBase64ToFile(kDexFile,
302 secondary_dex_ce_,
303 kTestAppUid,
304 kTestAppGid,
305 0600,
306 &error_msg)) {
307 return ::testing::AssertionFailure() << "Could not write base64 file to "
308 << secondary_dex_ce_ << " : " << error_msg;
309 }
Calin Juravle7d765462017-09-04 15:57:10 -0700310 std::string app_private_dir_ce_link = create_data_user_ce_package_path_as_user_link(
311 volume_uuid_cstr, kTestUserId, package_name_.c_str());
312 secondary_dex_ce_link_ = app_private_dir_ce_link + "/secondary_ce.jar";
313
314 // Create a secondary dex file on DE storage.
315 app_private_dir_de_ = create_data_user_de_package_path(
316 volume_uuid_cstr, kTestUserId, package_name_.c_str());
317 secondary_dex_de_ = app_private_dir_de_ + "/secondary_de.jar";
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700318 if (!WriteBase64ToFile(kDexFile,
319 secondary_dex_de_,
320 kTestAppUid,
321 kTestAppGid,
322 0600,
323 &error_msg)) {
324 return ::testing::AssertionFailure() << "Could not write base64 file to "
325 << secondary_dex_de_ << " : " << error_msg;
326 }
Calin Juravle7d765462017-09-04 15:57:10 -0700327
328 // Fix app data uid.
Andreas Gampe2ef09a72018-08-29 14:50:41 -0700329 status = service_->fixupAppData(volume_uuid_, kTestUserId);
330 if (!status.isOk()) {
331 return ::testing::AssertionFailure() << "Could not fixup app data: "
332 << status.toString8().c_str();
333 }
334
335 return ::testing::AssertionSuccess();
Calin Juravle7d765462017-09-04 15:57:10 -0700336 }
337
338
Calin Juravle29591732017-11-20 17:46:19 -0800339 std::string GetSecondaryDexArtifact(const std::string& path, const std::string& type) {
Calin Juravle7d765462017-09-04 15:57:10 -0700340 std::string::size_type end = path.rfind('.');
341 std::string::size_type start = path.rfind('/', end);
342 return path.substr(0, start) + "/oat/" + kRuntimeIsa + "/" +
343 path.substr(start + 1, end - start) + type;
344 }
345
Calin Juravle29591732017-11-20 17:46:19 -0800346 void CompileSecondaryDex(const std::string& path, int32_t dex_storage_flag,
Calin Juravle7d765462017-09-04 15:57:10 -0700347 bool should_binder_call_succeed, bool should_dex_be_compiled = true,
David Brazdil4f6027a2019-03-19 11:44:21 +0000348 /*out */ binder::Status* binder_result = nullptr, int32_t uid = -1,
349 const char* class_loader_context = nullptr) {
Calin Juravled2affb82017-11-28 17:41:43 -0800350 if (uid == -1) {
351 uid = kTestAppUid;
352 }
David Brazdil4f6027a2019-03-19 11:44:21 +0000353 if (class_loader_context == nullptr) {
354 class_loader_context = "&";
355 }
Calin Juravle7d765462017-09-04 15:57:10 -0700356 std::unique_ptr<std::string> package_name_ptr(new std::string(package_name_));
357 int32_t dexopt_needed = 0; // does not matter;
358 std::unique_ptr<std::string> out_path = nullptr; // does not matter
359 int32_t dex_flags = DEXOPT_SECONDARY_DEX | dex_storage_flag;
360 std::string compiler_filter = "speed-profile";
David Brazdil4f6027a2019-03-19 11:44:21 +0000361 std::unique_ptr<std::string> class_loader_context_ptr(
362 new std::string(class_loader_context));
Calin Juravle7d765462017-09-04 15:57:10 -0700363 std::unique_ptr<std::string> se_info_ptr(new std::string(se_info_));
364 bool downgrade = false;
David Brazdil570d3982018-01-16 20:15:43 +0000365 int32_t target_sdk_version = 0; // default
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000366 std::unique_ptr<std::string> profile_name_ptr = nullptr;
Calin Juravle62c5a372018-02-01 17:03:23 +0000367 std::unique_ptr<std::string> dm_path_ptr = nullptr;
Calin Juravle2efc4022018-02-13 18:31:32 -0800368 std::unique_ptr<std::string> compilation_reason_ptr = nullptr;
Calin Juravle7d765462017-09-04 15:57:10 -0700369
370 binder::Status result = service_->dexopt(path,
371 uid,
372 package_name_ptr,
373 kRuntimeIsa,
374 dexopt_needed,
375 out_path,
376 dex_flags,
377 compiler_filter,
378 volume_uuid_,
379 class_loader_context_ptr,
380 se_info_ptr,
David Brazdil570d3982018-01-16 20:15:43 +0000381 downgrade,
Calin Juravle408cd4a2018-01-20 23:34:18 -0800382 target_sdk_version,
Calin Juravle62c5a372018-02-01 17:03:23 +0000383 profile_name_ptr,
Calin Juravle2efc4022018-02-13 18:31:32 -0800384 dm_path_ptr,
385 compilation_reason_ptr);
Andreas Gampef6a93b12018-02-27 09:51:15 -0800386 ASSERT_EQ(should_binder_call_succeed, result.isOk()) << result.toString8().c_str();
Calin Juravle7d765462017-09-04 15:57:10 -0700387 int expected_access = should_dex_be_compiled ? 0 : -1;
Calin Juravle29591732017-11-20 17:46:19 -0800388 std::string odex = GetSecondaryDexArtifact(path, "odex");
389 std::string vdex = GetSecondaryDexArtifact(path, "vdex");
390 std::string art = GetSecondaryDexArtifact(path, "art");
Calin Juravle7d765462017-09-04 15:57:10 -0700391 ASSERT_EQ(expected_access, access(odex.c_str(), R_OK));
392 ASSERT_EQ(expected_access, access(vdex.c_str(), R_OK));
393 ASSERT_EQ(-1, access(art.c_str(), R_OK)); // empty profiles do not generate an image.
Andreas Gampe023b2242018-02-28 16:03:25 -0800394 if (binder_result != nullptr) {
395 *binder_result = result;
396 }
Calin Juravle7d765462017-09-04 15:57:10 -0700397 }
398
399 void reconcile_secondary_dex(const std::string& path, int32_t storage_flag,
400 bool should_binder_call_succeed, bool should_dex_exist, bool should_dex_be_deleted,
Calin Juravled2affb82017-11-28 17:41:43 -0800401 int32_t uid = -1, std::string* package_override = nullptr) {
402 if (uid == -1) {
403 uid = kTestAppUid;
404 }
Calin Juravle7d765462017-09-04 15:57:10 -0700405 std::vector<std::string> isas;
406 isas.push_back(kRuntimeIsa);
407 bool out_secondary_dex_exists = false;
408 binder::Status result = service_->reconcileSecondaryDexFile(
409 path,
410 package_override == nullptr ? package_name_ : *package_override,
411 uid,
412 isas,
413 volume_uuid_,
414 storage_flag,
415 &out_secondary_dex_exists);
416
Andreas Gampef6a93b12018-02-27 09:51:15 -0800417 ASSERT_EQ(should_binder_call_succeed, result.isOk()) << result.toString8().c_str();
Calin Juravle7d765462017-09-04 15:57:10 -0700418 ASSERT_EQ(should_dex_exist, out_secondary_dex_exists);
419
420 int expected_access = should_dex_be_deleted ? -1 : 0;
Calin Juravle29591732017-11-20 17:46:19 -0800421 std::string odex = GetSecondaryDexArtifact(path, "odex");
422 std::string vdex = GetSecondaryDexArtifact(path, "vdex");
423 std::string art = GetSecondaryDexArtifact(path, "art");
Calin Juravle7d765462017-09-04 15:57:10 -0700424 ASSERT_EQ(expected_access, access(odex.c_str(), F_OK));
425 ASSERT_EQ(expected_access, access(vdex.c_str(), F_OK));
426 ASSERT_EQ(-1, access(art.c_str(), R_OK)); // empty profiles do not generate an image.
427 }
Calin Juravle29591732017-11-20 17:46:19 -0800428
429 void CheckFileAccess(const std::string& file, uid_t uid, gid_t gid, mode_t mode) {
430 struct stat st;
431 ASSERT_EQ(0, stat(file.c_str(), &st));
432 ASSERT_EQ(uid, st.st_uid);
433 ASSERT_EQ(gid, st.st_gid);
434 ASSERT_EQ(mode, st.st_mode);
435 }
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000436
437 void CompilePrimaryDexOk(std::string compiler_filter,
438 int32_t dex_flags,
439 const char* oat_dir,
440 int32_t uid,
441 int32_t dexopt_needed,
Andreas Gampe023b2242018-02-28 16:03:25 -0800442 binder::Status* binder_result = nullptr,
Calin Juravle62c5a372018-02-01 17:03:23 +0000443 const char* dm_path = nullptr,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000444 bool downgrade = false) {
Andreas Gampe023b2242018-02-28 16:03:25 -0800445 CompilePrimaryDex(compiler_filter,
446 dex_flags,
447 oat_dir,
448 uid,
449 dexopt_needed,
450 dm_path,
451 downgrade,
452 true,
453 binder_result);
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000454 }
455
456 void CompilePrimaryDexFail(std::string compiler_filter,
457 int32_t dex_flags,
458 const char* oat_dir,
459 int32_t uid,
460 int32_t dexopt_needed,
Andreas Gampe023b2242018-02-28 16:03:25 -0800461 binder::Status* binder_result = nullptr,
Calin Juravle62c5a372018-02-01 17:03:23 +0000462 const char* dm_path = nullptr,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000463 bool downgrade = false) {
Andreas Gampe023b2242018-02-28 16:03:25 -0800464 CompilePrimaryDex(compiler_filter,
465 dex_flags,
466 oat_dir,
467 uid,
468 dexopt_needed,
469 dm_path,
470 downgrade,
471 false,
472 binder_result);
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000473 }
474
475 void CompilePrimaryDex(std::string compiler_filter,
476 int32_t dex_flags,
477 const char* oat_dir,
478 int32_t uid,
479 int32_t dexopt_needed,
Calin Juravle62c5a372018-02-01 17:03:23 +0000480 const char* dm_path,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000481 bool downgrade,
Andreas Gampe023b2242018-02-28 16:03:25 -0800482 bool should_binder_call_succeed,
483 /*out */ binder::Status* binder_result) {
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000484 std::unique_ptr<std::string> package_name_ptr(new std::string(package_name_));
485 std::unique_ptr<std::string> out_path(
486 oat_dir == nullptr ? nullptr : new std::string(oat_dir));
487 std::unique_ptr<std::string> class_loader_context_ptr(new std::string("&"));
488 std::unique_ptr<std::string> se_info_ptr(new std::string(se_info_));
489 int32_t target_sdk_version = 0; // default
490 std::unique_ptr<std::string> profile_name_ptr(new std::string("primary.prof"));
Calin Juravle62c5a372018-02-01 17:03:23 +0000491 std::unique_ptr<std::string> dm_path_ptr = nullptr;
492 if (dm_path != nullptr) {
493 dm_path_ptr.reset(new std::string(dm_path));
494 }
Calin Juravle2efc4022018-02-13 18:31:32 -0800495 std::unique_ptr<std::string> compilation_reason_ptr(new std::string("test-reason"));
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000496
497 bool prof_result;
Andreas Gampef448ced2019-01-31 09:22:27 -0800498 ASSERT_BINDER_SUCCESS(service_->prepareAppProfile(
Jeff Sharkey1ebe77f2018-02-27 11:40:45 -0700499 package_name_, kTestUserId, kTestAppId, *profile_name_ptr, apk_path_,
liulvping61907742018-08-21 09:36:52 +0800500 dm_path_ptr, &prof_result));
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000501 ASSERT_TRUE(prof_result);
502
503 binder::Status result = service_->dexopt(apk_path_,
504 uid,
505 package_name_ptr,
506 kRuntimeIsa,
507 dexopt_needed,
508 out_path,
509 dex_flags,
510 compiler_filter,
511 volume_uuid_,
512 class_loader_context_ptr,
513 se_info_ptr,
514 downgrade,
515 target_sdk_version,
Calin Juravle62c5a372018-02-01 17:03:23 +0000516 profile_name_ptr,
Calin Juravle2efc4022018-02-13 18:31:32 -0800517 dm_path_ptr,
518 compilation_reason_ptr);
Andreas Gampef6a93b12018-02-27 09:51:15 -0800519 ASSERT_EQ(should_binder_call_succeed, result.isOk()) << result.toString8().c_str();
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000520
521 if (!should_binder_call_succeed) {
Andreas Gampe023b2242018-02-28 16:03:25 -0800522 if (binder_result != nullptr) {
523 *binder_result = result;
524 }
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000525 return;
526 }
527 // Check the access to the compiler output.
528 // - speed-profile artifacts are not world-wide readable.
529 // - files are owned by the system uid.
530 std::string odex = GetPrimaryDexArtifact(oat_dir, apk_path_, "odex");
531 std::string vdex = GetPrimaryDexArtifact(oat_dir, apk_path_, "vdex");
532 std::string art = GetPrimaryDexArtifact(oat_dir, apk_path_, "art");
533
Calin Juravle5bd1c722018-02-01 17:23:54 +0000534 bool is_public = (dex_flags & DEXOPT_PUBLIC) != 0;
535 mode_t mode = S_IFREG | (is_public ? 0644 : 0640);
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000536 CheckFileAccess(odex, kSystemUid, uid, mode);
537 CheckFileAccess(vdex, kSystemUid, uid, mode);
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000538
Calin Juravle5bd1c722018-02-01 17:23:54 +0000539 if (compiler_filter == "speed-profile") {
540 CheckFileAccess(art, kSystemUid, uid, mode);
541 }
Andreas Gampe023b2242018-02-28 16:03:25 -0800542 if (binder_result != nullptr) {
543 *binder_result = result;
544 }
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000545 }
546
547 std::string GetPrimaryDexArtifact(const char* oat_dir,
548 const std::string& dex_path,
549 const std::string& type) {
550 if (oat_dir == nullptr) {
551 std::string path = dex_path;
552 for (auto it = path.begin() + 1; it < path.end(); ++it) {
553 if (*it == '/') {
554 *it = '@';
555 }
556 }
557 return android_data_dir + DALVIK_CACHE + '/' + kRuntimeIsa + "/" + path
558 + "@classes.dex";
559 } else {
560 std::string::size_type name_end = dex_path.rfind('.');
561 std::string::size_type name_start = dex_path.rfind('/');
562 return std::string(oat_dir) + "/" + kRuntimeIsa + "/" +
563 dex_path.substr(name_start + 1, name_end - name_start) + type;
564 }
565 }
Calin Juravle7d765462017-09-04 15:57:10 -0700566};
567
568
569TEST_F(DexoptTest, DexoptSecondaryCe) {
570 LOG(INFO) << "DexoptSecondaryCe";
Calin Juravle29591732017-11-20 17:46:19 -0800571 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700572 /*binder_ok*/ true, /*compile_ok*/ true);
573}
574
575TEST_F(DexoptTest, DexoptSecondaryCeLink) {
576 LOG(INFO) << "DexoptSecondaryCeLink";
Calin Juravle29591732017-11-20 17:46:19 -0800577 CompileSecondaryDex(secondary_dex_ce_link_, DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700578 /*binder_ok*/ true, /*compile_ok*/ true);
579}
580
David Brazdil4f6027a2019-03-19 11:44:21 +0000581TEST_F(DexoptTest, DexoptSecondaryCeWithContext) {
582 LOG(INFO) << "DexoptSecondaryCeWithContext";
583 std::string class_loader_context = "PCL[" + secondary_dex_ce_ + "]";
584 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_CE,
585 /*binder_ok*/ true, /*compile_ok*/ true, nullptr, -1, class_loader_context.c_str());
586}
587
Calin Juravle7d765462017-09-04 15:57:10 -0700588TEST_F(DexoptTest, DexoptSecondaryDe) {
589 LOG(INFO) << "DexoptSecondaryDe";
Calin Juravle29591732017-11-20 17:46:19 -0800590 CompileSecondaryDex(secondary_dex_de_, DEXOPT_STORAGE_DE,
Calin Juravle7d765462017-09-04 15:57:10 -0700591 /*binder_ok*/ true, /*compile_ok*/ true);
592}
593
David Brazdil4f6027a2019-03-19 11:44:21 +0000594TEST_F(DexoptTest, DexoptSecondaryDeWithContext) {
595 LOG(INFO) << "DexoptSecondaryDeWithContext";
596 std::string class_loader_context = "PCL[" + secondary_dex_de_ + "]";
597 CompileSecondaryDex(secondary_dex_de_, DEXOPT_STORAGE_DE,
598 /*binder_ok*/ true, /*compile_ok*/ true, nullptr, -1, class_loader_context.c_str());
599}
600
Calin Juravle7d765462017-09-04 15:57:10 -0700601TEST_F(DexoptTest, DexoptSecondaryDoesNotExist) {
602 LOG(INFO) << "DexoptSecondaryDoesNotExist";
603 // If the file validates but does not exist we do not treat it as an error.
Andreas Gampe023b2242018-02-28 16:03:25 -0800604 binder::Status status;
Calin Juravle29591732017-11-20 17:46:19 -0800605 CompileSecondaryDex(secondary_dex_ce_ + "not.there", DEXOPT_STORAGE_CE,
Andreas Gampe023b2242018-02-28 16:03:25 -0800606 /*binder_ok*/ true, /*compile_ok*/ false, &status);
607 EXPECT_STREQ(status.toString8().c_str(), "No error");
Calin Juravle7d765462017-09-04 15:57:10 -0700608}
609
610TEST_F(DexoptTest, DexoptSecondaryStorageValidationError) {
611 LOG(INFO) << "DexoptSecondaryStorageValidationError";
Andreas Gampe023b2242018-02-28 16:03:25 -0800612 binder::Status status;
Calin Juravle29591732017-11-20 17:46:19 -0800613 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_DE,
Andreas Gampe023b2242018-02-28 16:03:25 -0800614 /*binder_ok*/ false, /*compile_ok*/ false, &status);
Andreas Gampe3008bbe2018-02-28 20:24:48 -0800615 EXPECT_STREQ(status.toString8().c_str(),
Martijn Coenen290de462019-03-21 13:14:59 +0100616 "Status(-8, EX_SERVICE_SPECIFIC): '-1: Dexoptanalyzer path validation failed'");
Calin Juravle7d765462017-09-04 15:57:10 -0700617}
618
619TEST_F(DexoptTest, DexoptSecondaryAppOwnershipValidationError) {
620 LOG(INFO) << "DexoptSecondaryAppOwnershipValidationError";
Andreas Gampe023b2242018-02-28 16:03:25 -0800621 binder::Status status;
Calin Juravle29591732017-11-20 17:46:19 -0800622 CompileSecondaryDex("/data/data/random.app/secondary.jar", DEXOPT_STORAGE_CE,
Andreas Gampe023b2242018-02-28 16:03:25 -0800623 /*binder_ok*/ false, /*compile_ok*/ false, &status);
Andreas Gampe3008bbe2018-02-28 20:24:48 -0800624 EXPECT_STREQ(status.toString8().c_str(),
Martijn Coenen290de462019-03-21 13:14:59 +0100625 "Status(-8, EX_SERVICE_SPECIFIC): '-1: Dexoptanalyzer path validation failed'");
Calin Juravle7d765462017-09-04 15:57:10 -0700626}
627
628TEST_F(DexoptTest, DexoptSecondaryAcessViaDifferentUidError) {
629 LOG(INFO) << "DexoptSecondaryAcessViaDifferentUidError";
Andreas Gampe023b2242018-02-28 16:03:25 -0800630 binder::Status status;
Calin Juravle29591732017-11-20 17:46:19 -0800631 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_CE,
Andreas Gampe023b2242018-02-28 16:03:25 -0800632 /*binder_ok*/ false, /*compile_ok*/ false, &status, kSystemUid);
Martijn Coenen290de462019-03-21 13:14:59 +0100633 EXPECT_STREQ(status.toString8().c_str(),
634 "Status(-8, EX_SERVICE_SPECIFIC): '-1: Dexoptanalyzer open zip failed'");
Calin Juravle7d765462017-09-04 15:57:10 -0700635}
636
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000637TEST_F(DexoptTest, DexoptPrimaryPublic) {
638 LOG(INFO) << "DexoptPrimaryPublic";
639 CompilePrimaryDexOk("verify",
640 DEXOPT_BOOTCOMPLETE | DEXOPT_PUBLIC,
641 app_oat_dir_.c_str(),
642 kTestAppGid,
643 DEX2OAT_FROM_SCRATCH);
644}
645
Alex Buynytskyy17d8f822019-06-20 16:29:57 -0700646TEST_F(DexoptTest, DexoptPrimaryPublicCreateOatDir) {
647 LOG(INFO) << "DexoptPrimaryPublic";
648 ASSERT_BINDER_SUCCESS(service_->createOatDir(app_oat_dir_, kRuntimeIsa));
649 CompilePrimaryDexOk("verify",
650 DEXOPT_BOOTCOMPLETE | DEXOPT_PUBLIC,
651 app_oat_dir_.c_str(),
652 kTestAppGid,
653 DEX2OAT_FROM_SCRATCH);
654}
655
Calin Juravle5bd1c722018-02-01 17:23:54 +0000656TEST_F(DexoptTest, DexoptPrimaryFailedInvalidFilter) {
657 LOG(INFO) << "DexoptPrimaryFailedInvalidFilter";
Andreas Gampe023b2242018-02-28 16:03:25 -0800658 binder::Status status;
Calin Juravle5bd1c722018-02-01 17:23:54 +0000659 CompilePrimaryDexFail("awesome-filter",
660 DEXOPT_IDLE_BACKGROUND_JOB | DEXOPT_PUBLIC,
661 app_oat_dir_.c_str(),
662 kTestAppGid,
Andreas Gampe023b2242018-02-28 16:03:25 -0800663 DEX2OAT_FROM_SCRATCH,
664 &status);
665 EXPECT_STREQ(status.toString8().c_str(),
Martijn Coenen290de462019-03-21 13:14:59 +0100666 "Status(-8, EX_SERVICE_SPECIFIC): \'256: Dex2oat invocation for "
Andreas Gampefa2dadd2018-02-28 19:52:47 -0800667 "/data/app/com.installd.test.dexopt/base.jar failed: unspecified dex2oat error'");
Calin Juravle5bd1c722018-02-01 17:23:54 +0000668}
669
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000670TEST_F(DexoptTest, DexoptPrimaryProfileNonPublic) {
671 LOG(INFO) << "DexoptPrimaryProfileNonPublic";
672 CompilePrimaryDexOk("speed-profile",
Mathieu Chartier2d5a1bc2018-04-03 14:55:43 -0700673 DEXOPT_BOOTCOMPLETE | DEXOPT_PROFILE_GUIDED | DEXOPT_GENERATE_APP_IMAGE,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000674 app_oat_dir_.c_str(),
675 kTestAppGid,
liulvping61907742018-08-21 09:36:52 +0800676 DEX2OAT_FROM_SCRATCH,
677 /*binder_result=*/nullptr,
678 empty_dm_file_.c_str());
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000679}
680
681TEST_F(DexoptTest, DexoptPrimaryProfilePublic) {
682 LOG(INFO) << "DexoptPrimaryProfilePublic";
Calin Juravle5bd1c722018-02-01 17:23:54 +0000683 CompilePrimaryDexOk("speed-profile",
Mathieu Chartier2d5a1bc2018-04-03 14:55:43 -0700684 DEXOPT_BOOTCOMPLETE | DEXOPT_PROFILE_GUIDED | DEXOPT_PUBLIC |
685 DEXOPT_GENERATE_APP_IMAGE,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000686 app_oat_dir_.c_str(),
687 kTestAppGid,
liulvping61907742018-08-21 09:36:52 +0800688 DEX2OAT_FROM_SCRATCH,
689 /*binder_result=*/nullptr,
690 empty_dm_file_.c_str());
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000691}
692
693TEST_F(DexoptTest, DexoptPrimaryBackgroundOk) {
694 LOG(INFO) << "DexoptPrimaryBackgroundOk";
695 CompilePrimaryDexOk("speed-profile",
Mathieu Chartier2d5a1bc2018-04-03 14:55:43 -0700696 DEXOPT_IDLE_BACKGROUND_JOB | DEXOPT_PROFILE_GUIDED |
697 DEXOPT_GENERATE_APP_IMAGE,
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000698 app_oat_dir_.c_str(),
699 kTestAppGid,
liulvping61907742018-08-21 09:36:52 +0800700 DEX2OAT_FROM_SCRATCH,
701 /*binder_result=*/nullptr,
702 empty_dm_file_.c_str());
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000703}
704
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800705TEST_F(DexoptTest, ResolveStartupConstStrings) {
706 LOG(INFO) << "DexoptDex2oatResolveStartupStrings";
707 const std::string property = "persist.device_config.runtime.dex2oat_resolve_startup_strings";
708 const std::string previous_value = android::base::GetProperty(property, "");
709 auto restore_property = android::base::make_scope_guard([=]() {
710 android::base::SetProperty(property, previous_value);
711 });
712 std::string odex = GetPrimaryDexArtifact(app_oat_dir_.c_str(), apk_path_, "odex");
713 // Disable the property to start.
714 bool found_disable = false;
715 ASSERT_TRUE(android::base::SetProperty(property, "false")) << property;
716 CompilePrimaryDexOk("speed-profile",
717 DEXOPT_IDLE_BACKGROUND_JOB | DEXOPT_PROFILE_GUIDED |
718 DEXOPT_GENERATE_APP_IMAGE,
719 app_oat_dir_.c_str(),
720 kTestAppGid,
liulvping61907742018-08-21 09:36:52 +0800721 DEX2OAT_FROM_SCRATCH,
722 /*binder_result=*/nullptr,
723 empty_dm_file_.c_str());
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800724 run_cmd_and_process_output(
725 "oatdump --header-only --oat-file=" + odex,
726 [&](const std::string& line) {
727 if (line.find("--resolve-startup-const-strings=false") != std::string::npos) {
728 found_disable = true;
729 }
730 });
731 EXPECT_TRUE(found_disable);
732 // Enable the property and inspect that .art artifact is larger.
733 bool found_enable = false;
734 ASSERT_TRUE(android::base::SetProperty(property, "true")) << property;
735 CompilePrimaryDexOk("speed-profile",
736 DEXOPT_IDLE_BACKGROUND_JOB | DEXOPT_PROFILE_GUIDED |
737 DEXOPT_GENERATE_APP_IMAGE,
738 app_oat_dir_.c_str(),
739 kTestAppGid,
liulvping61907742018-08-21 09:36:52 +0800740 DEX2OAT_FROM_SCRATCH,
741 /*binder_result=*/nullptr,
742 empty_dm_file_.c_str());
Mathieu Chartierd41622c2019-01-31 12:59:39 -0800743 run_cmd_and_process_output(
744 "oatdump --header-only --oat-file=" + odex,
745 [&](const std::string& line) {
746 if (line.find("--resolve-startup-const-strings=true") != std::string::npos) {
747 found_enable = true;
748 }
749 });
750 EXPECT_TRUE(found_enable);
751}
752
Calin Juravlec4f6a0b2018-02-01 01:27:24 +0000753class PrimaryDexReCompilationTest : public DexoptTest {
754 public:
755 virtual void SetUp() {
756 DexoptTest::SetUp();
757 CompilePrimaryDexOk("verify",
758 DEXOPT_BOOTCOMPLETE | DEXOPT_PUBLIC,
759 app_oat_dir_.c_str(),
760 kTestAppGid,
761 DEX2OAT_FROM_SCRATCH);
762 std::string odex = GetSecondaryDexArtifact(apk_path_, "odex");
763 std::string vdex = GetSecondaryDexArtifact(apk_path_, "vdex");
764
765 first_compilation_odex_fd_.reset(open(odex.c_str(), O_RDONLY));
766 first_compilation_vdex_fd_.reset(open(vdex.c_str(), O_RDONLY));
767 }
768
769 virtual void TearDown() {
770 first_compilation_odex_fd_.reset(-1);
771 first_compilation_vdex_fd_.reset(-1);
772 DexoptTest::TearDown();
773 }
774
775 protected:
776 unique_fd first_compilation_odex_fd_;
777 unique_fd first_compilation_vdex_fd_;
778};
779
780TEST_F(PrimaryDexReCompilationTest, DexoptPrimaryUpdateInPlaceVdex) {
781 LOG(INFO) << "DexoptPrimaryUpdateInPlaceVdex";
782
783 CompilePrimaryDexOk("verify",
784 DEXOPT_IDLE_BACKGROUND_JOB | DEXOPT_PUBLIC,
785 app_oat_dir_.c_str(),
786 kTestAppGid,
787 DEX2OAT_FOR_BOOT_IMAGE);
788}
Calin Juravle7d765462017-09-04 15:57:10 -0700789
790class ReconcileTest : public DexoptTest {
791 virtual void SetUp() {
792 DexoptTest::SetUp();
Calin Juravle29591732017-11-20 17:46:19 -0800793 CompileSecondaryDex(secondary_dex_ce_, DEXOPT_STORAGE_CE,
Calin Juravle7d765462017-09-04 15:57:10 -0700794 /*binder_ok*/ true, /*compile_ok*/ true);
Calin Juravle29591732017-11-20 17:46:19 -0800795 CompileSecondaryDex(secondary_dex_de_, DEXOPT_STORAGE_DE,
Calin Juravle7d765462017-09-04 15:57:10 -0700796 /*binder_ok*/ true, /*compile_ok*/ true);
797 }
798};
799
800TEST_F(ReconcileTest, ReconcileSecondaryCeExists) {
801 LOG(INFO) << "ReconcileSecondaryCeExists";
802 reconcile_secondary_dex(secondary_dex_ce_, FLAG_STORAGE_CE,
803 /*binder_ok*/ true, /*dex_ok */ true, /*odex_deleted*/ false);
804}
805
806TEST_F(ReconcileTest, ReconcileSecondaryCeLinkExists) {
807 LOG(INFO) << "ReconcileSecondaryCeLinkExists";
808 reconcile_secondary_dex(secondary_dex_ce_link_, FLAG_STORAGE_CE,
809 /*binder_ok*/ true, /*dex_ok */ true, /*odex_deleted*/ false);
810}
811
812TEST_F(ReconcileTest, ReconcileSecondaryDeExists) {
813 LOG(INFO) << "ReconcileSecondaryDeExists";
814 reconcile_secondary_dex(secondary_dex_de_, FLAG_STORAGE_DE,
815 /*binder_ok*/ true, /*dex_ok */ true, /*odex_deleted*/ false);
816}
817
818TEST_F(ReconcileTest, ReconcileSecondaryDeDoesNotExist) {
819 LOG(INFO) << "ReconcileSecondaryDeDoesNotExist";
820 run_cmd("rm -rf " + secondary_dex_de_);
821 reconcile_secondary_dex(secondary_dex_de_, FLAG_STORAGE_DE,
822 /*binder_ok*/ true, /*dex_ok */ false, /*odex_deleted*/ true);
823}
824
825TEST_F(ReconcileTest, ReconcileSecondaryStorageValidationError) {
826 // Validation errors will not clean the odex/vdex/art files but will mark
827 // the file as non existent so that the PM knows it should purge it from its
828 // records.
829 LOG(INFO) << "ReconcileSecondaryStorageValidationError";
830 reconcile_secondary_dex(secondary_dex_ce_, FLAG_STORAGE_DE,
831 /*binder_ok*/ true, /*dex_ok */ false, /*odex_deleted*/ false);
832}
833
834TEST_F(ReconcileTest, ReconcileSecondaryAppOwnershipValidationError) {
835 LOG(INFO) << "ReconcileSecondaryAppOwnershipValidationError";
836 // Attempt to reconcile the dex files of the test app from a different app.
837 std::string another_app = "another.app";
838 reconcile_secondary_dex(secondary_dex_ce_, FLAG_STORAGE_CE,
839 /*binder_ok*/ true, /*dex_ok */ false, /*odex_deleted*/ false, kSystemUid, &another_app);
840}
841
842TEST_F(ReconcileTest, ReconcileSecondaryAcessViaDifferentUidError) {
843 LOG(INFO) << "ReconcileSecondaryAcessViaDifferentUidError";
844 reconcile_secondary_dex(secondary_dex_ce_, FLAG_STORAGE_CE,
845 /*binder_ok*/ true, /*dex_ok */ false, /*odex_deleted*/ false, kSystemUid);
846}
847
Calin Juravle29591732017-11-20 17:46:19 -0800848class ProfileTest : public DexoptTest {
849 protected:
850 std::string cur_profile_;
851 std::string ref_profile_;
852 std::string snap_profile_;
853
Calin Juravle824a64d2018-01-18 20:23:17 -0800854 static constexpr const char* kPrimaryProfile = "primary.prof";
855
Calin Juravle29591732017-11-20 17:46:19 -0800856 virtual void SetUp() {
857 DexoptTest::SetUp();
858 cur_profile_ = create_current_profile_path(
Calin Juravle824a64d2018-01-18 20:23:17 -0800859 kTestUserId, package_name_, kPrimaryProfile, /*is_secondary_dex*/ false);
860 ref_profile_ = create_reference_profile_path(package_name_, kPrimaryProfile,
861 /*is_secondary_dex*/ false);
862 snap_profile_ = create_snapshot_profile_path(package_name_, kPrimaryProfile);
Calin Juravle29591732017-11-20 17:46:19 -0800863 }
864
Calin Juravle824a64d2018-01-18 20:23:17 -0800865 void SetupProfile(const std::string& path, uid_t uid, gid_t gid, mode_t mode,
866 int32_t num_dex) {
867 run_cmd("profman --generate-test-profile-seed=" + std::to_string(num_dex) +
868 " --generate-test-profile-num-dex=" + std::to_string(num_dex) +
869 " --generate-test-profile=" + path);
Calin Juravle29591732017-11-20 17:46:19 -0800870 ::chmod(path.c_str(), mode);
871 ::chown(path.c_str(), uid, gid);
872 }
873
874 void SetupProfiles(bool setup_ref) {
875 SetupProfile(cur_profile_, kTestAppUid, kTestAppGid, 0600, 1);
876 if (setup_ref) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800877 SetupProfile(ref_profile_, kTestAppUid, kTestAppGid, 0600, 2);
Calin Juravle29591732017-11-20 17:46:19 -0800878 }
879 }
880
Calin Juravlec3596c32017-12-05 12:29:15 -0800881 void createProfileSnapshot(int32_t appid, const std::string& package_name,
882 bool expected_result) {
Calin Juravle29591732017-11-20 17:46:19 -0800883 bool result;
Andreas Gampef448ced2019-01-31 09:22:27 -0800884 ASSERT_BINDER_SUCCESS(service_->createProfileSnapshot(
885 appid, package_name, kPrimaryProfile, apk_path_, &result));
Calin Juravle29591732017-11-20 17:46:19 -0800886 ASSERT_EQ(expected_result, result);
887
888 if (!expected_result) {
889 // Do not check the files if we expect to fail.
890 return;
891 }
892
893 // Check that the snapshot was created witht he expected acess flags.
894 CheckFileAccess(snap_profile_, kSystemUid, kSystemGid, 0600 | S_IFREG);
895
896 // The snapshot should be equivalent to the merge of profiles.
897 std::string expected_profile_content = snap_profile_ + ".expected";
898 run_cmd("rm -f " + expected_profile_content);
899 run_cmd("touch " + expected_profile_content);
900 run_cmd("profman --profile-file=" + cur_profile_ +
901 " --profile-file=" + ref_profile_ +
Calin Juravle40b5f462018-02-07 04:11:52 -0800902 " --reference-profile-file=" + expected_profile_content +
903 " --apk=" + apk_path_);
Calin Juravle29591732017-11-20 17:46:19 -0800904
905 ASSERT_TRUE(AreFilesEqual(expected_profile_content, snap_profile_));
906
907 pid_t pid = fork();
908 if (pid == 0) {
909 /* child */
910 TransitionToSystemServer();
911
912 // System server should be able to open the the spanshot.
913 unique_fd fd(open(snap_profile_.c_str(), O_RDONLY));
914 ASSERT_TRUE(fd > -1) << "Failed to open profile as kSystemUid: " << strerror(errno);
915 _exit(0);
916 }
917 /* parent */
918 ASSERT_TRUE(WIFEXITED(wait_child(pid)));
919 }
920
Calin Juravle408cd4a2018-01-20 23:34:18 -0800921 void mergePackageProfiles(const std::string& package_name,
922 const std::string& code_path,
923 bool expected_result) {
Calin Juravle824a64d2018-01-18 20:23:17 -0800924 bool result;
Andreas Gampef448ced2019-01-31 09:22:27 -0800925 ASSERT_BINDER_SUCCESS(service_->mergeProfiles(
926 kTestAppUid, package_name, code_path, &result));
Calin Juravle824a64d2018-01-18 20:23:17 -0800927 ASSERT_EQ(expected_result, result);
928
929 if (!expected_result) {
930 // Do not check the files if we expect to fail.
931 return;
932 }
933
934 // Check that the snapshot was created witht he expected acess flags.
935 CheckFileAccess(ref_profile_, kTestAppUid, kTestAppUid, 0600 | S_IFREG);
936
937 // The snapshot should be equivalent to the merge of profiles.
938 std::string ref_profile_content = ref_profile_ + ".expected";
939 run_cmd("rm -f " + ref_profile_content);
940 run_cmd("touch " + ref_profile_content);
941 run_cmd("profman --profile-file=" + cur_profile_ +
942 " --profile-file=" + ref_profile_ +
943 " --reference-profile-file=" + ref_profile_content);
944
945 ASSERT_TRUE(AreFilesEqual(ref_profile_content, ref_profile_));
946 }
947
Calin Juravlec3b049e2018-01-18 22:32:58 -0800948 // TODO(calin): add dex metadata tests once the ART change is merged.
949 void preparePackageProfile(const std::string& package_name, const std::string& profile_name,
950 bool expected_result) {
951 bool result;
Andreas Gampef448ced2019-01-31 09:22:27 -0800952 ASSERT_BINDER_SUCCESS(service_->prepareAppProfile(
Jeff Sharkey1ebe77f2018-02-27 11:40:45 -0700953 package_name, kTestUserId, kTestAppId, profile_name, apk_path_,
Andreas Gampef448ced2019-01-31 09:22:27 -0800954 /*dex_metadata*/ nullptr, &result));
Calin Juravlec3b049e2018-01-18 22:32:58 -0800955 ASSERT_EQ(expected_result, result);
956
957 if (!expected_result) {
958 // Do not check the files if we expect to fail.
959 return;
960 }
961
962 std::string code_path_cur_prof = create_current_profile_path(
963 kTestUserId, package_name, profile_name, /*is_secondary_dex*/ false);
964 std::string code_path_ref_profile = create_reference_profile_path(package_name,
965 profile_name, /*is_secondary_dex*/ false);
966
967 // Check that we created the current profile.
968 CheckFileAccess(code_path_cur_prof, kTestAppUid, kTestAppUid, 0600 | S_IFREG);
969
970 // Without dex metadata we don't generate a reference profile.
971 ASSERT_EQ(-1, access(code_path_ref_profile.c_str(), R_OK));
972 }
973
Calin Juravle0d0a4922018-01-23 19:54:11 -0800974 protected:
Calin Juravle29591732017-11-20 17:46:19 -0800975 void TransitionToSystemServer() {
976 ASSERT_TRUE(DropCapabilities(kSystemUid, kSystemGid));
Andreas Gampef04b0b42019-03-25 11:20:57 -0700977 int32_t res = selinux_android_setcon("u:r:system_server:s0");
Calin Juravle29591732017-11-20 17:46:19 -0800978 ASSERT_EQ(0, res) << "Failed to setcon " << strerror(errno);
979 }
980
981 bool AreFilesEqual(const std::string& file1, const std::string& file2) {
982 std::vector<uint8_t> content1;
983 std::vector<uint8_t> content2;
984
985 if (!ReadAll(file1, &content1)) return false;
986 if (!ReadAll(file2, &content2)) return false;
987 return content1 == content2;
988 }
989
990 bool ReadAll(const std::string& file, std::vector<uint8_t>* content) {
991 unique_fd fd(open(file.c_str(), O_RDONLY));
992 if (fd < 0) {
993 PLOG(ERROR) << "Failed to open " << file;
994 return false;
995 }
996 struct stat st;
997 if (fstat(fd, &st) != 0) {
998 PLOG(ERROR) << "Failed to stat " << file;
999 return false;
1000 }
1001 content->resize(st.st_size);
1002 bool result = ReadFully(fd, content->data(), content->size());
1003 if (!result) {
1004 PLOG(ERROR) << "Failed to read " << file;
1005 }
1006 return result;
1007 }
1008};
1009
1010TEST_F(ProfileTest, ProfileSnapshotOk) {
1011 LOG(INFO) << "ProfileSnapshotOk";
1012
1013 SetupProfiles(/*setup_ref*/ true);
Calin Juravlec3596c32017-12-05 12:29:15 -08001014 createProfileSnapshot(kTestAppId, package_name_, /*expected_result*/ true);
Calin Juravle29591732017-11-20 17:46:19 -08001015}
1016
1017// The reference profile is created on the fly. We need to be able to
1018// snapshot without one.
1019TEST_F(ProfileTest, ProfileSnapshotOkNoReference) {
1020 LOG(INFO) << "ProfileSnapshotOkNoReference";
1021
1022 SetupProfiles(/*setup_ref*/ false);
Calin Juravlec3596c32017-12-05 12:29:15 -08001023 createProfileSnapshot(kTestAppId, package_name_, /*expected_result*/ true);
Calin Juravle29591732017-11-20 17:46:19 -08001024}
1025
1026TEST_F(ProfileTest, ProfileSnapshotFailWrongPackage) {
1027 LOG(INFO) << "ProfileSnapshotFailWrongPackage";
1028
1029 SetupProfiles(/*setup_ref*/ true);
Calin Juravlec3596c32017-12-05 12:29:15 -08001030 createProfileSnapshot(kTestAppId, "not.there", /*expected_result*/ false);
Calin Juravle29591732017-11-20 17:46:19 -08001031}
1032
1033TEST_F(ProfileTest, ProfileSnapshotDestroySnapshot) {
1034 LOG(INFO) << "ProfileSnapshotDestroySnapshot";
1035
1036 SetupProfiles(/*setup_ref*/ true);
Calin Juravlec3596c32017-12-05 12:29:15 -08001037 createProfileSnapshot(kTestAppId, package_name_, /*expected_result*/ true);
Calin Juravle29591732017-11-20 17:46:19 -08001038
Andreas Gampef448ced2019-01-31 09:22:27 -08001039 ASSERT_BINDER_SUCCESS(service_->destroyProfileSnapshot(package_name_, kPrimaryProfile));
Calin Juravle29591732017-11-20 17:46:19 -08001040 struct stat st;
1041 ASSERT_EQ(-1, stat(snap_profile_.c_str(), &st));
1042 ASSERT_EQ(ENOENT, errno);
1043}
1044
Calin Juravle824a64d2018-01-18 20:23:17 -08001045TEST_F(ProfileTest, ProfileMergeOk) {
1046 LOG(INFO) << "ProfileMergeOk";
1047
1048 SetupProfiles(/*setup_ref*/ true);
Calin Juravle408cd4a2018-01-20 23:34:18 -08001049 mergePackageProfiles(package_name_, "primary.prof", /*expected_result*/ true);
Calin Juravle824a64d2018-01-18 20:23:17 -08001050}
1051
1052// The reference profile is created on the fly. We need to be able to
1053// merge without one.
1054TEST_F(ProfileTest, ProfileMergeOkNoReference) {
1055 LOG(INFO) << "ProfileMergeOkNoReference";
1056
1057 SetupProfiles(/*setup_ref*/ false);
Calin Juravle408cd4a2018-01-20 23:34:18 -08001058 mergePackageProfiles(package_name_, "primary.prof", /*expected_result*/ true);
Calin Juravle824a64d2018-01-18 20:23:17 -08001059}
1060
1061TEST_F(ProfileTest, ProfileMergeFailWrongPackage) {
1062 LOG(INFO) << "ProfileMergeFailWrongPackage";
1063
1064 SetupProfiles(/*setup_ref*/ true);
Calin Juravle408cd4a2018-01-20 23:34:18 -08001065 mergePackageProfiles("not.there", "primary.prof", /*expected_result*/ false);
Calin Juravle824a64d2018-01-18 20:23:17 -08001066}
1067
Calin Juravled2affb82017-11-28 17:41:43 -08001068TEST_F(ProfileTest, ProfileDirOk) {
1069 LOG(INFO) << "ProfileDirOk";
1070
1071 std::string cur_profile_dir = create_primary_current_profile_package_dir_path(
1072 kTestUserId, package_name_);
1073 std::string cur_profile_file = create_current_profile_path(kTestUserId, package_name_,
Calin Juravle824a64d2018-01-18 20:23:17 -08001074 kPrimaryProfile, /*is_secondary_dex*/false);
Calin Juravled2affb82017-11-28 17:41:43 -08001075 std::string ref_profile_dir = create_primary_reference_profile_package_dir_path(package_name_);
1076
1077 CheckFileAccess(cur_profile_dir, kTestAppUid, kTestAppUid, 0700 | S_IFDIR);
Calin Juravle6f06eb62017-11-28 18:44:53 -08001078 CheckFileAccess(ref_profile_dir, kSystemUid, kTestAppGid, 0770 | S_IFDIR);
1079}
1080
1081// Verify that the profile directories are fixed up during an upgrade.
1082// (The reference profile directory is prepared lazily).
1083TEST_F(ProfileTest, ProfileDirOkAfterFixup) {
1084 LOG(INFO) << "ProfileDirOkAfterFixup";
1085
1086 std::string cur_profile_dir = create_primary_current_profile_package_dir_path(
1087 kTestUserId, package_name_);
1088 std::string cur_profile_file = create_current_profile_path(kTestUserId, package_name_,
Calin Juravle824a64d2018-01-18 20:23:17 -08001089 kPrimaryProfile, /*is_secondary_dex*/false);
Calin Juravle6f06eb62017-11-28 18:44:53 -08001090 std::string ref_profile_dir = create_primary_reference_profile_package_dir_path(package_name_);
1091
1092 // Simulate a pre-P setup by changing the owner to kTestAppGid and permissions to 0700.
1093 ASSERT_EQ(0, chown(ref_profile_dir.c_str(), kTestAppGid, kTestAppGid));
1094 ASSERT_EQ(0, chmod(ref_profile_dir.c_str(), 0700));
1095
1096 // Run createAppData again which will offer to fix-up the profile directories.
Andreas Gampef448ced2019-01-31 09:22:27 -08001097 ASSERT_BINDER_SUCCESS(service_->createAppData(
Calin Juravle6f06eb62017-11-28 18:44:53 -08001098 volume_uuid_,
1099 package_name_,
1100 kTestUserId,
1101 kAppDataFlags,
1102 kTestAppUid,
1103 se_info_,
1104 kOSdkVersion,
Andreas Gampef448ced2019-01-31 09:22:27 -08001105 &ce_data_inode_));
Calin Juravle6f06eb62017-11-28 18:44:53 -08001106
1107 // Check the file access.
1108 CheckFileAccess(cur_profile_dir, kTestAppUid, kTestAppUid, 0700 | S_IFDIR);
Calin Juravle6f06eb62017-11-28 18:44:53 -08001109 CheckFileAccess(ref_profile_dir, kSystemUid, kTestAppGid, 0770 | S_IFDIR);
Calin Juravled2affb82017-11-28 17:41:43 -08001110}
1111
Calin Juravlec3b049e2018-01-18 22:32:58 -08001112TEST_F(ProfileTest, ProfilePrepareOk) {
1113 LOG(INFO) << "ProfilePrepareOk";
1114 preparePackageProfile(package_name_, "split.prof", /*expected_result*/ true);
1115}
1116
1117TEST_F(ProfileTest, ProfilePrepareFailInvalidPackage) {
1118 LOG(INFO) << "ProfilePrepareFailInvalidPackage";
1119 preparePackageProfile("not.there.package", "split.prof", /*expected_result*/ false);
1120}
1121
1122TEST_F(ProfileTest, ProfilePrepareFailProfileChangedUid) {
1123 LOG(INFO) << "ProfilePrepareFailProfileChangedUid";
1124 SetupProfiles(/*setup_ref*/ false);
1125 // Change the uid on the profile to trigger a failure.
1126 ::chown(cur_profile_.c_str(), kTestAppUid + 1, kTestAppGid + 1);
1127 preparePackageProfile(package_name_, "primary.prof", /*expected_result*/ false);
1128}
1129
Calin Juravle0d0a4922018-01-23 19:54:11 -08001130
1131class BootProfileTest : public ProfileTest {
1132 public:
1133 virtual void setup() {
1134 ProfileTest::SetUp();
1135 intial_android_profiles_dir = android_profiles_dir;
1136 }
1137
1138 virtual void TearDown() {
1139 android_profiles_dir = intial_android_profiles_dir;
1140 ProfileTest::TearDown();
1141 }
1142
1143 void UpdateAndroidProfilesDir(const std::string& profile_dir) {
1144 android_profiles_dir = profile_dir;
1145 // We need to create the reference profile directory in the new profile dir.
1146 run_cmd("mkdir -p " + profile_dir + "/ref");
1147 }
1148
1149 void createBootImageProfileSnapshot(const std::string& classpath, bool expected_result) {
1150 bool result;
Andreas Gampef448ced2019-01-31 09:22:27 -08001151 ASSERT_BINDER_SUCCESS(service_->createProfileSnapshot(
1152 -1, "android", "android.prof", classpath, &result));
Calin Juravle0d0a4922018-01-23 19:54:11 -08001153 ASSERT_EQ(expected_result, result);
1154
1155 if (!expected_result) {
1156 // Do not check the files if we expect to fail.
1157 return;
1158 }
1159
1160 // Check that the snapshot was created with he expected access flags.
1161 const std::string boot_profile = create_snapshot_profile_path("android", "android.prof");
1162 CheckFileAccess(boot_profile, kSystemUid, kSystemGid, 0600 | S_IFREG);
1163
1164 pid_t pid = fork();
1165 if (pid == 0) {
1166 /* child */
1167 TransitionToSystemServer();
1168
1169 // System server should be able to open the snapshot.
1170 unique_fd fd(open(boot_profile.c_str(), O_RDONLY));
1171 ASSERT_TRUE(fd > -1) << "Failed to open profile as kSystemUid: " << strerror(errno);
1172 _exit(0);
1173 }
1174 /* parent */
1175 ASSERT_TRUE(WIFEXITED(wait_child(pid)));
1176 }
1177 protected:
1178 std::string intial_android_profiles_dir;
1179};
1180
1181TEST_F(BootProfileTest, BootProfileSnapshotOk) {
1182 LOG(INFO) << "BootProfileSnapshotOk";
1183 char* boot_classpath = getenv("BOOTCLASSPATH");
1184 ASSERT_TRUE(boot_classpath != nullptr);
1185 createBootImageProfileSnapshot(boot_classpath, /*expected_result*/ true);
1186}
1187
1188TEST_F(BootProfileTest, BootProfileSnapshotFailEmptyClasspath) {
1189 LOG(INFO) << "BootProfileSnapshotFailEmptyClasspath";
1190
1191 createBootImageProfileSnapshot(/*boot_classpath*/ "", /*expected_result*/ false);
1192}
1193
1194TEST_F(BootProfileTest, BootProfileSnapshotOkNoProfiles) {
1195 LOG(INFO) << "BootProfileSnapshotOkNoProfiles";
1196 char* boot_classpath = getenv("BOOTCLASSPATH");
1197 ASSERT_TRUE(boot_classpath != nullptr);
1198
1199 // The app_apk_dir has no profiles. So we shouldn't be able to merge anything.
1200 // Still, this is not a failure case.
1201 UpdateAndroidProfilesDir(app_apk_dir_);
1202 createBootImageProfileSnapshot(boot_classpath, /*expected_result*/ true);
1203}
1204
1205// Verify that profile collection.
1206TEST_F(BootProfileTest, CollectProfiles) {
1207 LOG(INFO) << "CollectProfiles";
1208
1209 // Create some profile directories mimicking the real profile structure.
1210 run_cmd("mkdir -p " + app_private_dir_de_ + "/profiles/ref");
1211 run_cmd("mkdir -p " + app_private_dir_de_ + "/profiles/cur/0/");
1212 run_cmd("mkdir -p " + app_private_dir_de_ + "/profiles/cur/1/");
1213 // Create an empty profile.
1214 run_cmd("touch " + app_private_dir_de_ + "/profiles/cur/1/primary.prof");
1215 // Create a random file.
1216 run_cmd("touch " + app_private_dir_de_ + "/profiles/cur/0/non.profile.file");
1217
1218 // Create some non-empty profiles.
1219 std::string current_prof = app_private_dir_de_ + "/profiles/cur/0/primary.prof";
1220 run_cmd("echo 1 > " + current_prof);
1221 std::string ref_prof = app_private_dir_de_ + "/profiles/ref/primary.prof";
1222 run_cmd("echo 1 > " + ref_prof);
1223
1224 UpdateAndroidProfilesDir(app_private_dir_de_ + "/profiles");
1225
1226 std::vector<std::string> profiles;
1227 collect_profiles(&profiles);
1228
1229 // Only two profiles should be in the output.
1230 ASSERT_EQ(2u, profiles.size());
1231 ASSERT_TRUE(std::find(profiles.begin(), profiles.end(), current_prof) != profiles.end());
1232 ASSERT_TRUE(std::find(profiles.begin(), profiles.end(), ref_prof) != profiles.end());
1233}
1234
Calin Juravlef74a7372019-02-28 20:29:41 -08001235TEST_F(DexoptTest, select_execution_binary) {
1236 LOG(INFO) << "DexoptTestselect_execution_binary";
1237
1238 std::string release_str = app_private_dir_ce_ + "/release";
1239 std::string debug_str = app_private_dir_ce_ + "/debug";
1240
1241 // Setup the binaries. Note that we only need executable files to actually
1242 // test the execution binary selection
1243 run_cmd("touch " + release_str);
1244 run_cmd("touch " + debug_str);
1245 run_cmd("chmod 777 " + release_str);
1246 run_cmd("chmod 777 " + debug_str);
1247
1248 const char* release = release_str.c_str();
1249 const char* debug = debug_str.c_str();
1250
1251 ASSERT_STREQ(release, select_execution_binary(
1252 release,
1253 debug,
1254 /*background_job_compile=*/ false,
1255 /*is_debug_runtime=*/ false,
1256 /*is_release=*/ false,
1257 /*is_debuggable_build=*/ false));
1258
1259 ASSERT_STREQ(release, select_execution_binary(
1260 release,
1261 debug,
1262 /*background_job_compile=*/ true,
1263 /*is_debug_runtime=*/ false,
1264 /*is_release=*/ true,
1265 /*is_debuggable_build=*/ true));
1266
1267 ASSERT_STREQ(debug, select_execution_binary(
1268 release,
1269 debug,
1270 /*background_job_compile=*/ false,
1271 /*is_debug_runtime=*/ true,
1272 /*is_release=*/ false,
1273 /*is_debuggable_build=*/ false));
1274
1275 ASSERT_STREQ(debug, select_execution_binary(
1276 release,
1277 debug,
1278 /*background_job_compile=*/ true,
1279 /*is_debug_runtime=*/ false,
1280 /*is_release=*/ false,
1281 /*is_debuggable_build=*/ true));
1282
1283
1284 // Select the release when the debug file is not there.
1285 ASSERT_STREQ(release, select_execution_binary(
1286 release,
1287 "does_not_exist",
1288 /*background_job_compile=*/ false,
1289 /*is_debug_runtime=*/ true,
1290 /*is_release=*/ false,
1291 /*is_debuggable_build=*/ false));
1292}
1293
Calin Juravle7d765462017-09-04 15:57:10 -07001294} // namespace installd
1295} // namespace android