1 /*
2  * Copyright (C) 2024 HiHope Open Source Organization.
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 
16 #include <cstdio>
17 #include <cstdlib>
18 #include <fcntl.h>
19 #include <string>
20 #include <unistd.h>
21 #include <vector>
22 #include <gtest/gtest.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <sys/ipc.h>
26 #include <sys/shm.h>
27 #include "securec.h"
28 
29 using namespace testing::ext;
30 using namespace std;
31 
32 class ShmatApiTest : public testing::Test {
33 public:
34     static void SetUpTestCase();
35     static void TearDownTestCase();
36     void SetUp();
37     void TearDown();
38 private:
39 };
SetUp()40 void ShmatApiTest::SetUp()
41 {
42 }
TearDown()43 void ShmatApiTest::TearDown()
44 {
45 }
SetUpTestCase()46 void ShmatApiTest::SetUpTestCase()
47 {
48 }
TearDownTestCase()49 void ShmatApiTest::TearDownTestCase()
50 {
51 }
52 
53 const int NAME_SIZE = 50;
54 const int MEM_SIZE = 1024;
55 
56 typedef struct {
57     int id;
58     char name[NAME_SIZE];
59 } TestData;
60 
61 /*
62  * @tc.number : SUB_KERNEL_SYSCALL_SHMAT_0100
63  * @tc.name   : ShmdtAttachShmSuccess_0001
64  * @tc.desc   : shmat attaches shared memory segment by shmid success.
65  * @tc.size   : MediumTest
66  * @tc.type   : Function
67  * @tc.level  : Level 1
68  */
HWTEST_F(ShmatApiTest, ShmdtAttachShmSuccess_0001, Function | MediumTest | Level1)69 HWTEST_F(ShmatApiTest, ShmdtAttachShmSuccess_0001, Function | MediumTest | Level1)
70 {
71     key_t key = ftok("shmfile", 65);
72     int shmid = shmget(key, MEM_SIZE, 0644 | IPC_CREAT | IPC_EXCL);
73     EXPECT_TRUE(shmid >= 0);
74 
75     void* addr = nullptr;
76     addr = shmat(shmid, nullptr, 0);
77     EXPECT_TRUE(addr != nullptr);
78 
79     int ret = shmctl(shmid, IPC_RMID, nullptr);
80     EXPECT_TRUE(ret == 0);
81 }
82 
83 /*
84  * @tc.number : SUB_KERNEL_SYSCALL_SHMAT_0200
85  * @tc.name   : ShmatUsedInvalidShmidFailed_0002
86  * @tc.desc   : shmat attaches shared memory segment by invalid shmid failed.
87  * @tc.size   : MediumTest
88  * @tc.type   : Function
89  * @tc.level  : Level 2
90  */
HWTEST_F(ShmatApiTest, ShmatUsedInvalidShmidFailed_0002, Function | MediumTest | Level2)91 HWTEST_F(ShmatApiTest, ShmatUsedInvalidShmidFailed_0002, Function | MediumTest | Level2)
92 {
93     errno = 0;
94     void* addr = shmat(-1, nullptr, 0);
95     EXPECT_TRUE(addr == reinterpret_cast<void*>(-1));
96     EXPECT_TRUE(errno == EINVAL);
97 }