1 // Copyright 2014 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.
4
5 #include <stddef.h>
6 #include <stdint.h>
7
8 #include <string>
9 #include <utility>
10
11 #include "base/at_exit.h"
12 #include "base/files/file_path.h"
13 #include "base/files/file_util.h"
14 #include "base/macros.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/run_loop.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "gin/array_buffer.h"
19 #include "gin/public/isolate_holder.h"
20 #include "gin/v8_initializer.h"
21 #include "mojo/common/data_pipe_utils.h"
22 #include "mojo/edk/js/mojo_runner_delegate.h"
23 #include "mojo/edk/js/tests/js_to_cpp.mojom.h"
24 #include "mojo/edk/test/test_utils.h"
25 #include "mojo/public/cpp/bindings/binding.h"
26 #include "mojo/public/cpp/system/core.h"
27 #include "testing/gtest/include/gtest/gtest.h"
28
29 namespace mojo {
30 namespace edk {
31 namespace js {
32
33 // Global value updated by some checks to prevent compilers from optimizing
34 // reads out of existence.
35 uint32_t g_waste_accumulator = 0;
36
37 namespace {
38
39 // Negative numbers with different values in each byte, the last of
40 // which can survive promotion to double and back.
41 const int8_t kExpectedInt8Value = -65;
42 const int16_t kExpectedInt16Value = -16961;
43 const int32_t kExpectedInt32Value = -1145258561;
44 const int64_t kExpectedInt64Value = -77263311946305LL;
45
46 // Positive numbers with different values in each byte, the last of
47 // which can survive promotion to double and back.
48 const uint8_t kExpectedUInt8Value = 65;
49 const uint16_t kExpectedUInt16Value = 16961;
50 const uint32_t kExpectedUInt32Value = 1145258561;
51 const uint64_t kExpectedUInt64Value = 77263311946305LL;
52
53 // Double/float values, including special case constants.
54 const double kExpectedDoubleVal = 3.14159265358979323846;
55 const double kExpectedDoubleInf = std::numeric_limits<double>::infinity();
56 const double kExpectedDoubleNan = std::numeric_limits<double>::quiet_NaN();
57 const float kExpectedFloatVal = static_cast<float>(kExpectedDoubleVal);
58 const float kExpectedFloatInf = std::numeric_limits<float>::infinity();
59 const float kExpectedFloatNan = std::numeric_limits<float>::quiet_NaN();
60
61 // NaN has the property that it is not equal to itself.
62 #define EXPECT_NAN(x) EXPECT_NE(x, x)
63
CheckDataPipe(ScopedDataPipeConsumerHandle data_pipe_handle)64 void CheckDataPipe(ScopedDataPipeConsumerHandle data_pipe_handle) {
65 std::string buffer;
66 bool result = common::BlockingCopyToString(std::move(data_pipe_handle),
67 &buffer);
68 EXPECT_TRUE(result);
69 EXPECT_EQ(64u, buffer.size());
70 for (int i = 0; i < 64; ++i) {
71 EXPECT_EQ(i, buffer[i]);
72 }
73 }
74
CheckMessagePipe(MessagePipeHandle message_pipe_handle)75 void CheckMessagePipe(MessagePipeHandle message_pipe_handle) {
76 unsigned char buffer[100];
77 uint32_t buffer_size = static_cast<uint32_t>(sizeof(buffer));
78 MojoResult result = Wait(
79 message_pipe_handle, MOJO_HANDLE_SIGNAL_READABLE,
80 MOJO_DEADLINE_INDEFINITE, nullptr);
81 EXPECT_EQ(MOJO_RESULT_OK, result);
82 result = ReadMessageRaw(
83 message_pipe_handle, buffer, &buffer_size, 0, 0, 0);
84 EXPECT_EQ(MOJO_RESULT_OK, result);
85 EXPECT_EQ(64u, buffer_size);
86 for (int i = 0; i < 64; ++i) {
87 EXPECT_EQ(255 - i, buffer[i]);
88 }
89 }
90
BuildSampleEchoArgs()91 js_to_cpp::EchoArgsPtr BuildSampleEchoArgs() {
92 js_to_cpp::EchoArgsPtr args(js_to_cpp::EchoArgs::New());
93 args->si64 = kExpectedInt64Value;
94 args->si32 = kExpectedInt32Value;
95 args->si16 = kExpectedInt16Value;
96 args->si8 = kExpectedInt8Value;
97 args->ui64 = kExpectedUInt64Value;
98 args->ui32 = kExpectedUInt32Value;
99 args->ui16 = kExpectedUInt16Value;
100 args->ui8 = kExpectedUInt8Value;
101 args->float_val = kExpectedFloatVal;
102 args->float_inf = kExpectedFloatInf;
103 args->float_nan = kExpectedFloatNan;
104 args->double_val = kExpectedDoubleVal;
105 args->double_inf = kExpectedDoubleInf;
106 args->double_nan = kExpectedDoubleNan;
107 args->name = "coming";
108 Array<String> string_array(3);
109 string_array[0] = "one";
110 string_array[1] = "two";
111 string_array[2] = "three";
112 args->string_array = std::move(string_array);
113 return args;
114 }
115
CheckSampleEchoArgs(js_to_cpp::EchoArgsPtr arg)116 void CheckSampleEchoArgs(js_to_cpp::EchoArgsPtr arg) {
117 EXPECT_EQ(kExpectedInt64Value, arg->si64);
118 EXPECT_EQ(kExpectedInt32Value, arg->si32);
119 EXPECT_EQ(kExpectedInt16Value, arg->si16);
120 EXPECT_EQ(kExpectedInt8Value, arg->si8);
121 EXPECT_EQ(kExpectedUInt64Value, arg->ui64);
122 EXPECT_EQ(kExpectedUInt32Value, arg->ui32);
123 EXPECT_EQ(kExpectedUInt16Value, arg->ui16);
124 EXPECT_EQ(kExpectedUInt8Value, arg->ui8);
125 EXPECT_EQ(kExpectedFloatVal, arg->float_val);
126 EXPECT_EQ(kExpectedFloatInf, arg->float_inf);
127 EXPECT_NAN(arg->float_nan);
128 EXPECT_EQ(kExpectedDoubleVal, arg->double_val);
129 EXPECT_EQ(kExpectedDoubleInf, arg->double_inf);
130 EXPECT_NAN(arg->double_nan);
131 EXPECT_EQ(std::string("coming"), arg->name.get());
132 EXPECT_EQ(std::string("one"), arg->string_array[0].get());
133 EXPECT_EQ(std::string("two"), arg->string_array[1].get());
134 EXPECT_EQ(std::string("three"), arg->string_array[2].get());
135 CheckDataPipe(std::move(arg->data_handle));
136 CheckMessagePipe(arg->message_handle.get());
137 }
138
CheckSampleEchoArgsList(const js_to_cpp::EchoArgsListPtr & list)139 void CheckSampleEchoArgsList(const js_to_cpp::EchoArgsListPtr& list) {
140 if (list.is_null())
141 return;
142 CheckSampleEchoArgs(std::move(list->item));
143 CheckSampleEchoArgsList(list->next);
144 }
145
146 // More forgiving checks are needed in the face of potentially corrupt
147 // messages. The values don't matter so long as all accesses are within
148 // bounds.
CheckCorruptedString(const String & arg)149 void CheckCorruptedString(const String& arg) {
150 if (arg.is_null())
151 return;
152 for (size_t i = 0; i < arg.size(); ++i)
153 g_waste_accumulator += arg[i];
154 }
155
CheckCorruptedStringArray(const Array<String> & string_array)156 void CheckCorruptedStringArray(const Array<String>& string_array) {
157 if (string_array.is_null())
158 return;
159 for (size_t i = 0; i < string_array.size(); ++i)
160 CheckCorruptedString(string_array[i]);
161 }
162
CheckCorruptedDataPipe(MojoHandle data_pipe_handle)163 void CheckCorruptedDataPipe(MojoHandle data_pipe_handle) {
164 unsigned char buffer[100];
165 uint32_t buffer_size = static_cast<uint32_t>(sizeof(buffer));
166 MojoResult result = MojoReadData(
167 data_pipe_handle, buffer, &buffer_size, MOJO_READ_DATA_FLAG_NONE);
168 if (result != MOJO_RESULT_OK)
169 return;
170 for (uint32_t i = 0; i < buffer_size; ++i)
171 g_waste_accumulator += buffer[i];
172 }
173
CheckCorruptedMessagePipe(MojoHandle message_pipe_handle)174 void CheckCorruptedMessagePipe(MojoHandle message_pipe_handle) {
175 unsigned char buffer[100];
176 uint32_t buffer_size = static_cast<uint32_t>(sizeof(buffer));
177 MojoResult result = MojoReadMessage(
178 message_pipe_handle, buffer, &buffer_size, 0, 0, 0);
179 if (result != MOJO_RESULT_OK)
180 return;
181 for (uint32_t i = 0; i < buffer_size; ++i)
182 g_waste_accumulator += buffer[i];
183 }
184
CheckCorruptedEchoArgs(const js_to_cpp::EchoArgsPtr & arg)185 void CheckCorruptedEchoArgs(const js_to_cpp::EchoArgsPtr& arg) {
186 if (arg.is_null())
187 return;
188 CheckCorruptedString(arg->name);
189 CheckCorruptedStringArray(arg->string_array);
190 if (arg->data_handle.is_valid())
191 CheckCorruptedDataPipe(arg->data_handle.get().value());
192 if (arg->message_handle.is_valid())
193 CheckCorruptedMessagePipe(arg->message_handle.get().value());
194 }
195
CheckCorruptedEchoArgsList(const js_to_cpp::EchoArgsListPtr & list)196 void CheckCorruptedEchoArgsList(const js_to_cpp::EchoArgsListPtr& list) {
197 if (list.is_null())
198 return;
199 CheckCorruptedEchoArgs(list->item);
200 CheckCorruptedEchoArgsList(list->next);
201 }
202
203 // Base Provider implementation class. It's expected that tests subclass and
204 // override the appropriate Provider functions. When test is done quit the
205 // run_loop().
206 class CppSideConnection : public js_to_cpp::CppSide {
207 public:
CppSideConnection()208 CppSideConnection()
209 : run_loop_(nullptr),
210 js_side_(nullptr),
211 mishandled_messages_(0),
212 binding_(this) {}
~CppSideConnection()213 ~CppSideConnection() override {}
214
set_run_loop(base::RunLoop * run_loop)215 void set_run_loop(base::RunLoop* run_loop) { run_loop_ = run_loop; }
run_loop()216 base::RunLoop* run_loop() { return run_loop_; }
217
set_js_side(js_to_cpp::JsSide * js_side)218 void set_js_side(js_to_cpp::JsSide* js_side) { js_side_ = js_side; }
js_side()219 js_to_cpp::JsSide* js_side() { return js_side_; }
220
Bind(InterfaceRequest<js_to_cpp::CppSide> request)221 void Bind(InterfaceRequest<js_to_cpp::CppSide> request) {
222 binding_.Bind(std::move(request));
223 // Keep the pipe open even after validation errors.
224 binding_.EnableTestingMode();
225 }
226
227 // js_to_cpp::CppSide:
StartTest()228 void StartTest() override { NOTREACHED(); }
229
TestFinished()230 void TestFinished() override { NOTREACHED(); }
231
PingResponse()232 void PingResponse() override { mishandled_messages_ += 1; }
233
EchoResponse(js_to_cpp::EchoArgsListPtr list)234 void EchoResponse(js_to_cpp::EchoArgsListPtr list) override {
235 mishandled_messages_ += 1;
236 }
237
BitFlipResponse(js_to_cpp::EchoArgsListPtr list)238 void BitFlipResponse(js_to_cpp::EchoArgsListPtr list) override {
239 mishandled_messages_ += 1;
240 }
241
BackPointerResponse(js_to_cpp::EchoArgsListPtr list)242 void BackPointerResponse(js_to_cpp::EchoArgsListPtr list) override {
243 mishandled_messages_ += 1;
244 }
245
246 protected:
247 base::RunLoop* run_loop_;
248 js_to_cpp::JsSide* js_side_;
249 int mishandled_messages_;
250 mojo::Binding<js_to_cpp::CppSide> binding_;
251
252 private:
253 DISALLOW_COPY_AND_ASSIGN(CppSideConnection);
254 };
255
256 // Trivial test to verify a message sent from JS is received.
257 class PingCppSideConnection : public CppSideConnection {
258 public:
PingCppSideConnection()259 PingCppSideConnection() : got_message_(false) {}
~PingCppSideConnection()260 ~PingCppSideConnection() override {}
261
262 // js_to_cpp::CppSide:
StartTest()263 void StartTest() override { js_side_->Ping(); }
264
PingResponse()265 void PingResponse() override {
266 got_message_ = true;
267 run_loop()->Quit();
268 }
269
DidSucceed()270 bool DidSucceed() {
271 return got_message_ && !mishandled_messages_;
272 }
273
274 private:
275 bool got_message_;
276 DISALLOW_COPY_AND_ASSIGN(PingCppSideConnection);
277 };
278
279 // Test that parameters are passed with correct values.
280 class EchoCppSideConnection : public CppSideConnection {
281 public:
EchoCppSideConnection()282 EchoCppSideConnection() :
283 message_count_(0),
284 termination_seen_(false) {
285 }
~EchoCppSideConnection()286 ~EchoCppSideConnection() override {}
287
288 // js_to_cpp::CppSide:
StartTest()289 void StartTest() override {
290 js_side_->Echo(kExpectedMessageCount, BuildSampleEchoArgs());
291 }
292
EchoResponse(js_to_cpp::EchoArgsListPtr list)293 void EchoResponse(js_to_cpp::EchoArgsListPtr list) override {
294 const js_to_cpp::EchoArgsPtr& special_arg = list->item;
295 message_count_ += 1;
296 EXPECT_EQ(-1, special_arg->si64);
297 EXPECT_EQ(-1, special_arg->si32);
298 EXPECT_EQ(-1, special_arg->si16);
299 EXPECT_EQ(-1, special_arg->si8);
300 EXPECT_EQ(std::string("going"), special_arg->name.To<std::string>());
301 CheckSampleEchoArgsList(list->next);
302 }
303
TestFinished()304 void TestFinished() override {
305 termination_seen_ = true;
306 run_loop()->Quit();
307 }
308
DidSucceed()309 bool DidSucceed() {
310 return termination_seen_ &&
311 !mishandled_messages_ &&
312 message_count_ == kExpectedMessageCount;
313 }
314
315 private:
316 static const int kExpectedMessageCount = 10;
317 int message_count_;
318 bool termination_seen_;
319 DISALLOW_COPY_AND_ASSIGN(EchoCppSideConnection);
320 };
321
322 // Test that corrupted messages don't wreak havoc.
323 class BitFlipCppSideConnection : public CppSideConnection {
324 public:
BitFlipCppSideConnection()325 BitFlipCppSideConnection() : termination_seen_(false) {}
~BitFlipCppSideConnection()326 ~BitFlipCppSideConnection() override {}
327
328 // js_to_cpp::CppSide:
StartTest()329 void StartTest() override { js_side_->BitFlip(BuildSampleEchoArgs()); }
330
BitFlipResponse(js_to_cpp::EchoArgsListPtr list)331 void BitFlipResponse(js_to_cpp::EchoArgsListPtr list) override {
332 CheckCorruptedEchoArgsList(list);
333 }
334
TestFinished()335 void TestFinished() override {
336 termination_seen_ = true;
337 run_loop()->Quit();
338 }
339
DidSucceed()340 bool DidSucceed() {
341 return termination_seen_;
342 }
343
344 private:
345 bool termination_seen_;
346 DISALLOW_COPY_AND_ASSIGN(BitFlipCppSideConnection);
347 };
348
349 // Test that severely random messages don't wreak havoc.
350 class BackPointerCppSideConnection : public CppSideConnection {
351 public:
BackPointerCppSideConnection()352 BackPointerCppSideConnection() : termination_seen_(false) {}
~BackPointerCppSideConnection()353 ~BackPointerCppSideConnection() override {}
354
355 // js_to_cpp::CppSide:
StartTest()356 void StartTest() override { js_side_->BackPointer(BuildSampleEchoArgs()); }
357
BackPointerResponse(js_to_cpp::EchoArgsListPtr list)358 void BackPointerResponse(js_to_cpp::EchoArgsListPtr list) override {
359 CheckCorruptedEchoArgsList(list);
360 }
361
TestFinished()362 void TestFinished() override {
363 termination_seen_ = true;
364 run_loop()->Quit();
365 }
366
DidSucceed()367 bool DidSucceed() {
368 return termination_seen_;
369 }
370
371 private:
372 bool termination_seen_;
373 DISALLOW_COPY_AND_ASSIGN(BackPointerCppSideConnection);
374 };
375
376 } // namespace
377
378 class JsToCppTest : public testing::Test {
379 public:
JsToCppTest()380 JsToCppTest() {}
381
RunTest(const std::string & test,CppSideConnection * cpp_side)382 void RunTest(const std::string& test, CppSideConnection* cpp_side) {
383 cpp_side->set_run_loop(&run_loop_);
384
385 js_to_cpp::JsSidePtr js_side;
386 auto js_side_proxy = GetProxy(&js_side);
387
388 cpp_side->set_js_side(js_side.get());
389 js_to_cpp::CppSidePtr cpp_side_ptr;
390 cpp_side->Bind(GetProxy(&cpp_side_ptr));
391
392 js_side->SetCppSide(std::move(cpp_side_ptr));
393
394 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
395 gin::V8Initializer::LoadV8Snapshot();
396 gin::V8Initializer::LoadV8Natives();
397 #endif
398
399 gin::IsolateHolder::Initialize(gin::IsolateHolder::kStrictMode,
400 gin::IsolateHolder::kStableV8Extras,
401 gin::ArrayBufferAllocator::SharedInstance());
402 gin::IsolateHolder instance;
403 MojoRunnerDelegate delegate;
404 gin::ShellRunner runner(&delegate, instance.isolate());
405 delegate.Start(&runner, js_side_proxy.PassMessagePipe().release().value(),
406 test);
407
408 run_loop_.Run();
409 }
410
411 private:
412 base::ShadowingAtExitManager at_exit_;
413 base::MessageLoop loop;
414 base::RunLoop run_loop_;
415
416 DISALLOW_COPY_AND_ASSIGN(JsToCppTest);
417 };
418
TEST_F(JsToCppTest,Ping)419 TEST_F(JsToCppTest, Ping) {
420 PingCppSideConnection cpp_side_connection;
421 RunTest("mojo/edk/js/tests/js_to_cpp_tests", &cpp_side_connection);
422 EXPECT_TRUE(cpp_side_connection.DidSucceed());
423 }
424
TEST_F(JsToCppTest,Echo)425 TEST_F(JsToCppTest, Echo) {
426 EchoCppSideConnection cpp_side_connection;
427 RunTest("mojo/edk/js/tests/js_to_cpp_tests", &cpp_side_connection);
428 EXPECT_TRUE(cpp_side_connection.DidSucceed());
429 }
430
TEST_F(JsToCppTest,BitFlip)431 TEST_F(JsToCppTest, BitFlip) {
432 BitFlipCppSideConnection cpp_side_connection;
433 RunTest("mojo/edk/js/tests/js_to_cpp_tests", &cpp_side_connection);
434 EXPECT_TRUE(cpp_side_connection.DidSucceed());
435 }
436
TEST_F(JsToCppTest,BackPointer)437 TEST_F(JsToCppTest, BackPointer) {
438 BackPointerCppSideConnection cpp_side_connection;
439 RunTest("mojo/edk/js/tests/js_to_cpp_tests", &cpp_side_connection);
440 EXPECT_TRUE(cpp_side_connection.DidSucceed());
441 }
442
443 } // namespace js
444 } // namespace edk
445 } // namespace mojo
446