1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // This class sets up the environment for running the native tests inside an
6 // android application. It outputs (to a fifo) markers identifying the
7 // START/PASSED/CRASH of the test suite, FAILURE/SUCCESS of individual tests,
8 // etc.
9 // These markers are read by the test runner script to generate test results.
10 // It installs signal handlers to detect crashes.
11
12 #include <android/log.h>
13 #include <errno.h>
14 #include <pthread.h>
15 #include <signal.h>
16 #include <string.h>
17
18 #include <iterator>
19
20 #include "base/android/jni_string.h"
21 #include "base/android/scoped_java_ref.h"
22 #include "base/at_exit.h"
23 #include "base/base_switches.h"
24 #include "base/clang_profiling_buildflags.h"
25 #include "base/command_line.h"
26 #include "base/debug/debugger.h"
27 #include "base/files/file_path.h"
28 #include "base/files/file_util.h"
29 #include "base/logging.h"
30 #include "base/test/test_support_android.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "gtest/gtest.h"
33 #include "testing/android/native_test/main_runner.h"
34 #include "testing/android/native_test/native_test_jni/NativeTest_jni.h"
35 #include "testing/android/native_test/native_test_util.h"
36
37 #if BUILDFLAG(CLANG_PROFILING)
38 #include "base/test/clang_profiling.h"
39 #endif
40
41 #if defined(__ANDROID_CLANG_COVERAGE__)
42 // This is only used by Cronet in AOSP.
43 extern "C" int __llvm_profile_dump(void);
44 #endif
45
46 using jni_zero::JavaParamRef;
47
48 // The main function of the program to be wrapped as a test apk.
49 extern int main(int argc, char** argv);
50
51 namespace testing {
52 namespace android {
53
54 namespace {
55
56 const char kLogTag[] = "chromium";
57 const char kCrashedMarker[] = "[ CRASHED ]\n";
58
59 // The list of signals which are considered to be crashes.
60 const int kExceptionSignals[] = {
61 SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, -1
62 };
63
64 struct sigaction g_old_sa[NSIG];
65
66 // This function runs in a compromised context. It should not allocate memory.
SignalHandler(int sig,siginfo_t * info,void * reserved)67 void SignalHandler(int sig, siginfo_t* info, void* reserved) {
68 // Output the crash marker.
69 write(STDOUT_FILENO, kCrashedMarker, sizeof(kCrashedMarker) - 1);
70 g_old_sa[sig].sa_sigaction(sig, info, reserved);
71 }
72
73 // Writes printf() style string to Android's logger where |priority| is one of
74 // the levels defined in <android/log.h>.
AndroidLog(int priority,const char * format,...)75 void AndroidLog(int priority, const char* format, ...) {
76 va_list args;
77 va_start(args, format);
78 __android_log_vprint(priority, kLogTag, format, args);
79 va_end(args);
80 }
81
82 } // namespace
83
JNI_NativeTest_RunTests(JNIEnv * env,const JavaParamRef<jstring> & jcommand_line_flags,const JavaParamRef<jstring> & jcommand_line_file_path,const JavaParamRef<jstring> & jstdout_file_path,const JavaParamRef<jobject> & app_context,const JavaParamRef<jstring> & jtest_data_dir)84 static void JNI_NativeTest_RunTests(
85 JNIEnv* env,
86 const JavaParamRef<jstring>& jcommand_line_flags,
87 const JavaParamRef<jstring>& jcommand_line_file_path,
88 const JavaParamRef<jstring>& jstdout_file_path,
89 const JavaParamRef<jobject>& app_context,
90 const JavaParamRef<jstring>& jtest_data_dir) {
91 base::ScopedAllowBlockingForTesting allow;
92
93 // Required for DEATH_TESTS.
94 pthread_atfork(nullptr, nullptr, jni_zero::DisableJvmForTesting);
95
96 // Command line initialized basically, will be fully initialized later.
97 static const char* const kInitialArgv[] = { "ChromeTestActivity" };
98 base::CommandLine::Init(std::size(kInitialArgv), kInitialArgv);
99
100 std::vector<std::string> args;
101
102 const std::string command_line_file_path(
103 base::android::ConvertJavaStringToUTF8(env, jcommand_line_file_path));
104 if (command_line_file_path.empty())
105 args.push_back("_");
106 else
107 ParseArgsFromCommandLineFile(command_line_file_path.c_str(), &args);
108
109 const std::string command_line_flags(
110 base::android::ConvertJavaStringToUTF8(env, jcommand_line_flags));
111 ParseArgsFromString(command_line_flags, &args);
112
113 std::vector<char*> argv;
114 int argc = ArgsToArgv(args, &argv);
115
116 // Fully initialize command line with arguments.
117 base::CommandLine::ForCurrentProcess()->AppendArguments(
118 base::CommandLine(argc, &argv[0]), false);
119 const base::CommandLine& command_line =
120 *base::CommandLine::ForCurrentProcess();
121
122 base::FilePath stdout_file_path(
123 base::android::ConvertJavaStringToUTF8(env, jstdout_file_path));
124
125 // A few options, such "--gtest_list_tests", will just use printf directly
126 // Always redirect stdout to a known file.
127 if (freopen(stdout_file_path.value().c_str(), "a+", stdout) == NULL) {
128 AndroidLog(ANDROID_LOG_ERROR, "Failed to redirect stream to file: %s: %s\n",
129 stdout_file_path.value().c_str(), strerror(errno));
130 exit(EXIT_FAILURE);
131 }
132 // TODO(jbudorick): Remove this after resolving crbug.com/726880
133 AndroidLog(ANDROID_LOG_INFO, "Redirecting stdout to file: %s\n",
134 stdout_file_path.value().c_str());
135 dup2(STDOUT_FILENO, STDERR_FILENO);
136
137 if (command_line.HasSwitch(switches::kWaitForDebugger)) {
138 AndroidLog(ANDROID_LOG_VERBOSE,
139 "Native test waiting for GDB because flag %s was supplied",
140 switches::kWaitForDebugger);
141 base::debug::WaitForDebugger(24 * 60 * 60, true);
142 }
143
144 base::FilePath test_data_dir(
145 base::android::ConvertJavaStringToUTF8(env, jtest_data_dir));
146 base::InitAndroidTestPaths(test_data_dir);
147
148 ScopedMainEntryLogger scoped_main_entry_logger;
149 main(argc, &argv[0]);
150
151 // Explicitly write profiling data to LLVM profile file.
152 #if BUILDFLAG(CLANG_PROFILING)
153 base::WriteClangProfilingProfile();
154 #elif defined(__ANDROID_CLANG_COVERAGE__)
155 // Cronet runs tests in AOSP, where due to build system constraints, compiler
156 // flags can be changed (to enable coverage), but source files cannot be
157 // conditionally linked (as is the case with `clang_profiling.cc`).
158 //
159 // This will always get called from a single thread unlike
160 // base::WriteClangProfilingProfile hence the lack of locks.
161 __llvm_profile_dump();
162 #endif
163 }
164
165 // TODO(nileshagrawal): now that we're using FIFO, test scripts can detect EOF.
166 // Remove the signal handlers.
InstallHandlers()167 void InstallHandlers() {
168 struct sigaction sa;
169 memset(&sa, 0, sizeof(sa));
170
171 sa.sa_sigaction = SignalHandler;
172 sa.sa_flags = SA_SIGINFO;
173
174 for (unsigned int i = 0; kExceptionSignals[i] != -1; ++i) {
175 sigaction(kExceptionSignals[i], &sa, &g_old_sa[kExceptionSignals[i]]);
176 }
177 }
178
179 } // namespace android
180 } // namespace testing
181