1 /*
2  * Copyright 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "GraphicBufferTest"
18 
19 #include <ui/GraphicBuffer.h>
20 
21 #include <gtest/gtest.h>
22 
23 namespace android {
24 
25 namespace {
26 
27 constexpr uint32_t kTestWidth = 1024;
28 constexpr uint32_t kTestHeight = 1;
29 constexpr uint32_t kTestLayerCount = 1;
30 constexpr uint64_t kTestUsage = GraphicBuffer::USAGE_SW_WRITE_OFTEN;
31 
32 } // namespace
33 
34 class GraphicBufferTest : public testing::Test {};
35 
TEST_F(GraphicBufferTest,AllocateNoError)36 TEST_F(GraphicBufferTest, AllocateNoError) {
37     PixelFormat format = PIXEL_FORMAT_RGBA_8888;
38     sp<GraphicBuffer> gb(new GraphicBuffer(kTestWidth, kTestHeight, format, kTestLayerCount,
39                                            kTestUsage, std::string("test")));
40     ASSERT_EQ(NO_ERROR, gb->initCheck());
41 }
42 
TEST_F(GraphicBufferTest,AllocateBadDimensions)43 TEST_F(GraphicBufferTest, AllocateBadDimensions) {
44     PixelFormat format = PIXEL_FORMAT_RGBA_8888;
45     if (std::numeric_limits<size_t>::max() / std::numeric_limits<uint32_t>::max() /
46                 bytesPerPixel(format) >=
47         std::numeric_limits<uint32_t>::max()) {
48         GTEST_SUCCEED() << "Cannot overflow with this format";
49     }
50     uint32_t width, height;
51     width = height = std::numeric_limits<uint32_t>::max();
52     sp<GraphicBuffer> gb(new GraphicBuffer(width, height, format, kTestLayerCount, kTestUsage,
53                                            std::string("test")));
54     ASSERT_EQ(BAD_VALUE, gb->initCheck());
55 
56     const size_t targetArea = std::numeric_limits<size_t>::max() / bytesPerPixel(format);
57     const size_t widthCandidate = targetArea / std::numeric_limits<uint32_t>::max();
58     if (widthCandidate == 0) {
59         width = 1;
60     } else {
61         width = std::numeric_limits<uint32_t>::max();
62     }
63     height = (targetArea / width) + 1;
64     sp<GraphicBuffer> gb2(new GraphicBuffer(width, height, format, kTestLayerCount, kTestUsage,
65                                             std::string("test")));
66     ASSERT_EQ(BAD_VALUE, gb2->initCheck());
67 }
68 
69 } // namespace android
70