1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
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,
9 // These markers are read by the test runner script to generate test results.
10 // It installs signal handlers to detect crashes.
12 #include <android/log.h>
15 #include "base/android/base_jni_registrar.h"
16 #include "base/android/fifo_utils.h"
17 #include "base/android/jni_android.h"
18 #include "base/android/jni_string.h"
19 #include "base/android/scoped_java_ref.h"
20 #include "base/at_exit.h"
21 #include "base/base_switches.h"
22 #include "base/command_line.h"
23 #include "base/files/file_path.h"
24 #include "base/files/file_util.h"
25 #include "base/logging.h"
26 #include "base/strings/stringprintf.h"
27 #include "gtest/gtest.h"
28 #include "jni/ChromeNativeTestActivity_jni.h"
29 #include "testing/android/native_test_util.h"
31 using testing::native_test_util::ArgsToArgv
;
32 using testing::native_test_util::ParseArgsFromCommandLineFile
;
33 using testing::native_test_util::ParseArgsFromString
;
34 using testing::native_test_util::ScopedMainEntryLogger
;
36 // The main function of the program to be wrapped as a test apk.
37 extern int main(int argc
, char** argv
);
41 // These two command line flags are supported for DumpRenderTree, which needs
42 // three fifos rather than a combined one: one for stderr, stdin and stdout.
43 const char kSeparateStderrFifo
[] = "separate-stderr-fifo";
44 const char kCreateStdinFifo
[] = "create-stdin-fifo";
46 // The test runner script writes the command line file in
48 static const char kCommandLineFilePath
[] =
49 "/data/local/tmp/chrome-native-tests-command-line";
51 const char kLogTag
[] = "chromium";
52 const char kCrashedMarker
[] = "[ CRASHED ]\n";
54 // The list of signals which are considered to be crashes.
55 const int kExceptionSignals
[] = {
56 SIGSEGV
, SIGABRT
, SIGFPE
, SIGILL
, SIGBUS
, -1
59 struct sigaction g_old_sa
[NSIG
];
61 // This function runs in a compromised context. It should not allocate memory.
62 void SignalHandler(int sig
, siginfo_t
* info
, void* reserved
) {
63 // Output the crash marker.
64 write(STDOUT_FILENO
, kCrashedMarker
, sizeof(kCrashedMarker
));
65 g_old_sa
[sig
].sa_sigaction(sig
, info
, reserved
);
68 // TODO(nileshagrawal): now that we're using FIFO, test scripts can detect EOF.
69 // Remove the signal handlers.
70 void InstallHandlers() {
72 memset(&sa
, 0, sizeof(sa
));
74 sa
.sa_sigaction
= SignalHandler
;
75 sa
.sa_flags
= SA_SIGINFO
;
77 for (unsigned int i
= 0; kExceptionSignals
[i
] != -1; ++i
) {
78 sigaction(kExceptionSignals
[i
], &sa
, &g_old_sa
[kExceptionSignals
[i
]]);
82 // Writes printf() style string to Android's logger where |priority| is one of
83 // the levels defined in <android/log.h>.
84 void AndroidLog(int priority
, const char* format
, ...) {
86 va_start(args
, format
);
87 __android_log_vprint(priority
, kLogTag
, format
, args
);
91 // Ensures that the fifo at |path| is created by deleting whatever is at |path|
92 // prior to (re)creating the fifo, otherwise logs the error and terminates the
94 void EnsureCreateFIFO(const base::FilePath
& path
) {
95 unlink(path
.value().c_str());
96 if (base::android::CreateFIFO(path
, 0666))
99 AndroidLog(ANDROID_LOG_ERROR
, "Failed to create fifo %s: %s\n",
100 path
.value().c_str(), strerror(errno
));
104 // Ensures that |stream| is redirected to |path|, otherwise logs the error and
105 // terminates the program.
106 void EnsureRedirectStream(FILE* stream
,
107 const base::FilePath
& path
,
109 if (base::android::RedirectStream(stream
, path
, mode
))
112 AndroidLog(ANDROID_LOG_ERROR
, "Failed to redirect stream to file: %s: %s\n",
113 path
.value().c_str(), strerror(errno
));
119 static void RunTests(JNIEnv
* env
,
121 jstring jcommand_line_flags
,
122 jstring jcommand_line_file_path
,
124 jobject app_context
) {
125 base::AtExitManager exit_manager
;
127 // Command line initialized basically, will be fully initialized later.
128 static const char* const kInitialArgv
[] = { "ChromeTestActivity" };
129 base::CommandLine::Init(arraysize(kInitialArgv
), kInitialArgv
);
131 // Set the application context in base.
132 base::android::ScopedJavaLocalRef
<jobject
> scoped_context(
133 env
, env
->NewLocalRef(app_context
));
134 base::android::InitApplicationContext(env
, scoped_context
);
135 base::android::RegisterJni(env
);
137 std::vector
<std::string
> args
;
139 const std::string
command_line_file_path(
140 base::android::ConvertJavaStringToUTF8(env
, jcommand_line_file_path
));
141 if (command_line_file_path
.empty())
142 ParseArgsFromCommandLineFile(kCommandLineFilePath
, &args
);
144 ParseArgsFromCommandLineFile(command_line_file_path
.c_str(), &args
);
146 const std::string
command_line_flags(
147 base::android::ConvertJavaStringToUTF8(env
, jcommand_line_flags
));
148 ParseArgsFromString(command_line_flags
, &args
);
150 std::vector
<char*> argv
;
151 int argc
= ArgsToArgv(args
, &argv
);
153 // Fully initialize command line with arguments.
154 base::CommandLine::ForCurrentProcess()->AppendArguments(
155 base::CommandLine(argc
, &argv
[0]), false);
156 const base::CommandLine
& command_line
=
157 *base::CommandLine::ForCurrentProcess();
159 base::FilePath
files_dir(
160 base::android::ConvertJavaStringToUTF8(env
, jfiles_dir
));
162 // A few options, such "--gtest_list_tests", will just use printf directly
163 // Always redirect stdout to a known file.
164 base::FilePath
fifo_path(files_dir
.Append(base::FilePath("test.fifo")));
165 EnsureCreateFIFO(fifo_path
);
167 base::FilePath stderr_fifo_path
, stdin_fifo_path
;
169 // DumpRenderTree needs a separate fifo for the stderr output. For all
170 // other tests, insert stderr content to the same fifo we use for stdout.
171 if (command_line
.HasSwitch(kSeparateStderrFifo
)) {
172 stderr_fifo_path
= files_dir
.Append(base::FilePath("stderr.fifo"));
173 EnsureCreateFIFO(stderr_fifo_path
);
176 // DumpRenderTree uses stdin to receive input about which test to run.
177 if (command_line
.HasSwitch(kCreateStdinFifo
)) {
178 stdin_fifo_path
= files_dir
.Append(base::FilePath("stdin.fifo"));
179 EnsureCreateFIFO(stdin_fifo_path
);
182 // Only redirect the streams after all fifos have been created.
183 EnsureRedirectStream(stdout
, fifo_path
, "w");
184 if (!stdin_fifo_path
.empty())
185 EnsureRedirectStream(stdin
, stdin_fifo_path
, "r");
186 if (!stderr_fifo_path
.empty())
187 EnsureRedirectStream(stderr
, stderr_fifo_path
, "w");
189 dup2(STDOUT_FILENO
, STDERR_FILENO
);
191 if (command_line
.HasSwitch(switches::kWaitForDebugger
)) {
192 AndroidLog(ANDROID_LOG_VERBOSE
,
193 "Native test waiting for GDB because flag %s was supplied",
194 switches::kWaitForDebugger
);
195 base::debug::WaitForDebugger(24 * 60 * 60, false);
198 ScopedMainEntryLogger scoped_main_entry_logger
;
199 main(argc
, &argv
[0]);
202 // This is called by the VM when the shared library is first loaded.
203 JNI_EXPORT jint
JNI_OnLoad(JavaVM
* vm
, void* reserved
) {
204 // Install signal handlers to detect crashes.
207 base::android::InitVM(vm
);
208 JNIEnv
* env
= base::android::AttachCurrentThread();
209 if (!RegisterNativesImpl(env
)) {
213 return JNI_VERSION_1_4
;