1 /*
2  * Copyright (C) 2015 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 <gtest/gtest.h>
18 
19 #include <libgen.h>
20 
21 #include <memory>
22 
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/test_utils.h>
26 #include <ziparchive/zip_archive.h>
27 
28 #if defined(__ANDROID__)
29 #include <sys/system_properties.h>
30 #endif
31 
32 #include "get_test_data.h"
33 #include "read_elf.h"
34 #include "utils.h"
35 
36 static std::string testdata_dir;
37 
38 #if defined(__ANDROID__)
39 static const std::string testdata_section = ".testzipdata";
40 
ExtractTestDataFromElfSection()41 static bool ExtractTestDataFromElfSection() {
42   if (!MkdirWithParents(testdata_dir)) {
43     PLOG(ERROR) << "failed to create testdata_dir " << testdata_dir;
44     return false;
45   }
46   std::string content;
47   ElfStatus result = ReadSectionFromElfFile("/proc/self/exe", testdata_section, &content);
48   if (result != ElfStatus::NO_ERROR) {
49     LOG(ERROR) << "failed to read section " << testdata_section
50                << ": " << result;
51     return false;
52   }
53   TemporaryFile tmp_file;
54   if (!android::base::WriteStringToFile(content, tmp_file.path)) {
55     PLOG(ERROR) << "failed to write file " << tmp_file.path;
56     return false;
57   }
58   ArchiveHelper ahelper(tmp_file.fd, tmp_file.path);
59   if (!ahelper) {
60     LOG(ERROR) << "failed to open archive " << tmp_file.path;
61     return false;
62   }
63   ZipArchiveHandle& handle = ahelper.archive_handle();
64   void* cookie;
65   int ret = StartIteration(handle, &cookie, nullptr, nullptr);
66   if (ret != 0) {
67     LOG(ERROR) << "failed to start iterating zip entries";
68     return false;
69   }
70   std::unique_ptr<void, decltype(&EndIteration)> guard(cookie, EndIteration);
71   ZipEntry entry;
72   ZipString name;
73   while (Next(cookie, &entry, &name) == 0) {
74     std::string entry_name(name.name, name.name + name.name_length);
75     std::string path = testdata_dir + entry_name;
76     // Skip dir.
77     if (path.back() == '/') {
78       continue;
79     }
80     if (!MkdirWithParents(path)) {
81       LOG(ERROR) << "failed to create dir for " << path;
82       return false;
83     }
84     FileHelper fhelper = FileHelper::OpenWriteOnly(path);
85     if (!fhelper) {
86       PLOG(ERROR) << "failed to create file " << path;
87       return false;
88     }
89     std::vector<uint8_t> data(entry.uncompressed_length);
90     if (ExtractToMemory(handle, &entry, data.data(), data.size()) != 0) {
91       LOG(ERROR) << "failed to extract entry " << entry_name;
92       return false;
93     }
94     if (!android::base::WriteFully(fhelper.fd(), data.data(), data.size())) {
95       LOG(ERROR) << "failed to write file " << path;
96       return false;
97     }
98   }
99   return true;
100 }
101 
102 class ScopedEnablingPerf {
103  public:
ScopedEnablingPerf()104   ScopedEnablingPerf() {
105     memset(prop_value_, '\0', sizeof(prop_value_));
106     __system_property_get("security.perf_harden", prop_value_);
107     SetProp("0");
108   }
109 
~ScopedEnablingPerf()110   ~ScopedEnablingPerf() {
111     if (strlen(prop_value_) != 0) {
112       SetProp(prop_value_);
113     }
114   }
115 
116  private:
SetProp(const char * value)117   void SetProp(const char* value) {
118     __system_property_set("security.perf_harden", value);
119     // Sleep one second to wait for security.perf_harden changing
120     // /proc/sys/kernel/perf_event_paranoid.
121     sleep(1);
122   }
123 
124   char prop_value_[PROP_VALUE_MAX];
125 };
126 
TestInAppContext(int argc,char ** argv)127 static bool TestInAppContext(int argc, char** argv) {
128   // Use run-as to move the test executable to the data directory of debuggable app
129   // 'com.android.simpleperf', and run it.
130   std::string exe_path;
131   if (!android::base::Readlink("/proc/self/exe", &exe_path)) {
132     PLOG(ERROR) << "readlink failed";
133     return false;
134   }
135   std::string copy_cmd = android::base::StringPrintf("run-as com.android.simpleperf cp %s .",
136                                                      exe_path.c_str());
137   if (system(copy_cmd.c_str()) == -1) {
138     PLOG(ERROR) << "system(" << copy_cmd << ") failed";
139     return false;
140   }
141   std::string arg_str;
142   arg_str += basename(argv[0]);
143   for (int i = 1; i < argc; ++i) {
144     arg_str.push_back(' ');
145     arg_str += argv[i];
146   }
147   std::string test_cmd = android::base::StringPrintf("run-as com.android.simpleperf ./%s",
148                                                      arg_str.c_str());
149   test_cmd += " --in-app-context";
150   if (system(test_cmd.c_str()) == -1) {
151     PLOG(ERROR) << "system(" << test_cmd << ") failed";
152     return false;
153   }
154   return true;
155 }
156 
157 #endif  // defined(__ANDROID__)
158 
main(int argc,char ** argv)159 int main(int argc, char** argv) {
160   android::base::InitLogging(argv, android::base::StderrLogger);
161   android::base::LogSeverity log_severity = android::base::WARNING;
162   bool need_app_context __attribute__((unused)) = false;
163   bool in_app_context __attribute__((unused)) = false;
164 
165 #if defined(RUN_IN_APP_CONTEXT)
166   need_app_context = true;
167 #endif
168 
169   for (int i = 1; i < argc; ++i) {
170     if (strcmp(argv[i], "-t") == 0 && i + 1 < argc) {
171       testdata_dir = argv[i + 1];
172       i++;
173     } else if (strcmp(argv[i], "--log") == 0) {
174       if (i + 1 < argc) {
175         ++i;
176         if (!GetLogSeverity(argv[i], &log_severity)) {
177           LOG(ERROR) << "Unknown log severity: " << argv[i];
178           return 1;
179         }
180       } else {
181         LOG(ERROR) << "Missing argument for --log option.\n";
182         return 1;
183       }
184     } else if (strcmp(argv[i], "--in-app-context") == 0) {
185       in_app_context = true;
186     }
187   }
188   android::base::ScopedLogSeverity severity(log_severity);
189 
190 #if defined(__ANDROID__)
191   std::unique_ptr<ScopedEnablingPerf> scoped_enabling_perf;
192   if (!in_app_context) {
193     // A cts test PerfEventParanoidTest.java is testing if
194     // /proc/sys/kernel/perf_event_paranoid is 3, so restore perf_harden
195     // value after current test to not break that test.
196     scoped_enabling_perf.reset(new ScopedEnablingPerf);
197   }
198 
199   if (need_app_context && !in_app_context) {
200     return TestInAppContext(argc, argv) ? 0 : 1;
201   }
202 
203   std::unique_ptr<TemporaryDir> tmp_dir;
204   if (!::testing::GTEST_FLAG(list_tests) && testdata_dir.empty()) {
205     testdata_dir = std::string(dirname(argv[0])) + "/testdata";
206     if (!IsDir(testdata_dir)) {
207       tmp_dir.reset(new TemporaryDir);
208       testdata_dir = std::string(tmp_dir->path) + "/";
209       if (!ExtractTestDataFromElfSection()) {
210         LOG(ERROR) << "failed to extract test data from elf section";
211         return 1;
212       }
213     }
214   }
215 
216 #endif
217 
218   testing::InitGoogleTest(&argc, argv);
219   if (!::testing::GTEST_FLAG(list_tests) && testdata_dir.empty()) {
220     printf("Usage: %s -t <testdata_dir>\n", argv[0]);
221     return 1;
222   }
223   if (testdata_dir.back() != '/') {
224     testdata_dir.push_back('/');
225   }
226   LOG(INFO) << "testdata is in " << testdata_dir;
227   return RUN_ALL_TESTS();
228 }
229 
GetTestData(const std::string & filename)230 std::string GetTestData(const std::string& filename) {
231   return testdata_dir + filename;
232 }
233 
GetTestDataDir()234 const std::string& GetTestDataDir() {
235   return testdata_dir;
236 }
237