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