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 "chrome/common/chrome_utility_messages.h" 6 #include "chrome/utility/chrome_content_utility_client.h" 7 #include "ipc/ipc_channel.h" 8 #include "testing/gtest/include/gtest/gtest.h" 9 #include "ui/gfx/codec/jpeg_codec.h" 10 11 namespace { 12 13 bool CreateJPEGImage(int width, 14 int height, 15 SkColor color, 16 std::vector<unsigned char>* output) { 17 SkBitmap bitmap; 18 bitmap.allocN32Pixels(width, height); 19 bitmap.eraseColor(color); 20 21 const int kQuality = 50; 22 if (!gfx::JPEGCodec::Encode( 23 static_cast<const unsigned char*>(bitmap.getPixels()), 24 gfx::JPEGCodec::FORMAT_SkBitmap, 25 width, 26 height, 27 bitmap.rowBytes(), 28 kQuality, 29 output)) { 30 LOG(ERROR) << "Unable to encode " << width << "x" << height << " bitmap"; 31 return false; 32 } 33 return true; 34 } 35 36 } // namespace 37 38 typedef testing::Test ChromeContentUtilityClientTest; 39 40 // Test that DecodeImage() doesn't return image message > (max message size) 41 TEST_F(ChromeContentUtilityClientTest, DecodeImageSizeLimit) { 42 // Using actual limit generates 14000 x 9400 images, which causes the test to 43 // timeout. We test with a smaller limit for efficiency. 44 const size_t kTestMessageSize = IPC::Channel::kMaximumMessageSize / 1024; 45 ChromeContentUtilityClient::set_max_ipc_message_size_for_test( 46 kTestMessageSize); 47 // Approx max height for 3:2 image that will fit in IPC message; 48 // 1.5 for width/height ratio, 4 for bytes/pixel 49 int max_height_for_msg = sqrt(kTestMessageSize / (1.5 * 4)); 50 int base_msg_size = sizeof(ChromeUtilityHostMsg_DecodeImage_Succeeded); 51 52 // Sizes which should trigger dimension-halving 0, 1 and 2 times 53 int heights[] = { max_height_for_msg - 10, 54 max_height_for_msg + 10, 55 2 * max_height_for_msg + 10 }; 56 int widths[] = { heights[0] * 3 / 2, heights[1] * 3 / 2, heights[2] * 3 / 2 }; 57 for (size_t i = 0; i < arraysize(heights); i++) { 58 std::vector<unsigned char> jpg; 59 CreateJPEGImage(widths[i], heights[i], SK_ColorRED, &jpg); 60 SkBitmap bitmap = ChromeContentUtilityClient::DecodeImage(jpg, true); 61 62 // Check that image has been shrunk appropriately 63 EXPECT_LT(bitmap.computeSize64() + base_msg_size, 64 static_cast<int64_t>(kTestMessageSize)); 65 // Android does its own image shrinking for memory conservation deeper in 66 // the decode, so more specific tests here won't work. 67 #if !defined(OS_ANDROID) 68 EXPECT_EQ(widths[i] >> i, bitmap.width()); 69 EXPECT_EQ(heights[i] >> i, bitmap.height()); 70 71 // Check that if resize not requested and image exceeds IPC size limit, 72 // an empty image is returned 73 if (heights[i] > max_height_for_msg) { 74 SkBitmap empty_bmp = ChromeContentUtilityClient::DecodeImage(jpg, false); 75 EXPECT_TRUE(empty_bmp.empty()); 76 } 77 #endif 78 } 79 } 80