1 // Copyright 2019 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //    http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "System/Memory.hpp"
16 #ifdef __linux__
17 #	include "System/Linux/MemFd.hpp"
18 #endif
19 
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 
23 #include <cstdlib>
24 
25 using namespace sw;
26 
27 #ifdef __linux__
TEST(MemFd,DefaultConstructor)28 TEST(MemFd, DefaultConstructor)
29 {
30 	LinuxMemFd memfd;
31 	ASSERT_FALSE(memfd.isValid());
32 	ASSERT_EQ(-1, memfd.exportFd());
33 }
34 
TEST(MemFd,AllocatingConstructor)35 TEST(MemFd, AllocatingConstructor)
36 {
37 	const size_t kRegionSize = sw::memoryPageSize() * 8;
38 	LinuxMemFd memfd("test-region", kRegionSize);
39 	ASSERT_TRUE(memfd.isValid());
40 	ASSERT_GE(memfd.fd(), 0);
41 	void *addr = memfd.mapReadWrite(0, kRegionSize);
42 	ASSERT_TRUE(addr);
43 	memfd.unmap(addr, kRegionSize);
44 }
45 
TEST(MemFd,ExplicitAllocation)46 TEST(MemFd, ExplicitAllocation)
47 {
48 	const size_t kRegionSize = sw::memoryPageSize() * 8;
49 	LinuxMemFd memfd;
50 	ASSERT_FALSE(memfd.isValid());
51 	ASSERT_EQ(-1, memfd.exportFd());
52 	ASSERT_TRUE(memfd.allocate("test-region", kRegionSize));
53 	ASSERT_TRUE(memfd.isValid());
54 }
55 
TEST(MemFd,Close)56 TEST(MemFd, Close)
57 {
58 	const size_t kRegionSize = sw::memoryPageSize() * 8;
59 	LinuxMemFd memfd("test-region", kRegionSize);
60 	ASSERT_TRUE(memfd.isValid());
61 	int fd = memfd.exportFd();
62 	memfd.close();
63 	ASSERT_FALSE(memfd.isValid());
64 	ASSERT_EQ(-1, memfd.exportFd());
65 	::close(fd);
66 }
67 
TEST(MemFd,ExportImportFd)68 TEST(MemFd, ExportImportFd)
69 {
70 	const size_t kRegionSize = sw::memoryPageSize() * 8;
71 	LinuxMemFd memfd("test-region1", kRegionSize);
72 	auto *addr = reinterpret_cast<uint8_t *>(memfd.mapReadWrite(0, kRegionSize));
73 	ASSERT_TRUE(addr);
74 	for(size_t n = 0; n < kRegionSize; ++n)
75 	{
76 		addr[n] = static_cast<uint8_t>(n);
77 	}
78 	int fd = memfd.exportFd();
79 	ASSERT_TRUE(memfd.unmap(addr, kRegionSize));
80 	memfd.close();
81 
82 	LinuxMemFd memfd2;
83 	memfd2.importFd(fd);
84 	ASSERT_TRUE(memfd2.isValid());
85 	addr = reinterpret_cast<uint8_t *>(memfd2.mapReadWrite(0, kRegionSize));
86 	ASSERT_TRUE(addr);
87 	for(size_t n = 0; n < kRegionSize; ++n)
88 	{
89 		ASSERT_EQ(addr[n], static_cast<uint8_t>(n)) << "# " << n;
90 	}
91 	ASSERT_TRUE(memfd2.unmap(addr, kRegionSize));
92 }
93 #endif  // __linux__
94