1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2016 Xiao Yang <yangx.jy@cn.fujitsu.com>
4 */
5
6 /*
7 * DESCRIPTION
8 * common routines for the IPC system call tests.
9 */
10
11 #include <errno.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <sys/types.h>
16 #include <sys/ipc.h>
17 #include <sys/msg.h>
18 #include <sys/shm.h>
19
20 #define TST_NO_DEFAULT_MAIN
21
22 #include "tst_test.h"
23 #include "libnewipc.h"
24
25 #define BUFSIZE 1024
26
getipckey(const char * file,const int lineno)27 key_t getipckey(const char *file, const int lineno)
28 {
29 char buf[BUFSIZE];
30 key_t key;
31 int id;
32 static int count;
33
34 SAFE_GETCWD(buf, BUFSIZE);
35
36 id = count % 26 + (int) 'a';
37 count++;
38
39 key = ftok(buf, id);
40 if (key == -1) {
41 tst_brk(TBROK | TERRNO,
42 "ftok() failed at %s:%d", file, lineno);
43 }
44
45 return key;
46 }
47
get_used_queues(const char * file,const int lineno)48 int get_used_queues(const char *file, const int lineno)
49 {
50 FILE *fp;
51 int used_queues = -1;
52 char buf[BUFSIZE];
53
54 fp = fopen("/proc/sysvipc/msg", "r");
55 if (fp == NULL) {
56 tst_brk(TBROK | TERRNO,
57 "fopen() failed at %s:%d", file, lineno);
58 }
59
60 while (fgets(buf, BUFSIZE, fp) != NULL)
61 used_queues++;
62
63 fclose(fp);
64
65 if (used_queues < 0) {
66 tst_brk(TBROK, "can't read /proc/sysvipc/msg to get "
67 "used message queues at %s:%d", file, lineno);
68 }
69
70 return used_queues;
71 }
72
probe_free_addr(const char * file,const int lineno)73 void *probe_free_addr(const char *file, const int lineno)
74 {
75 void *addr;
76 int shm_id = -1;
77 key_t probe_key = 0;
78
79 probe_key = GETIPCKEY();
80
81 shm_id = shmget(probe_key, SHMLBA * 2, SHM_RW | IPC_CREAT | IPC_EXCL);
82 if (shm_id == -1)
83 tst_brk(TBROK, "probe: shmget() failed at %s:%d", file, lineno);
84
85 addr = shmat(shm_id, NULL, 0);
86 if (addr == (void *) -1)
87 tst_brk(TBROK, "probe: shmat() failed at %s:%d", file, lineno);
88
89 if (shmdt(addr) == -1)
90 tst_brk(TBROK, "probe: shmdt() failed at %s:%d", file, lineno);
91
92 if (shmctl(shm_id, IPC_RMID, NULL) == -1)
93 tst_brk(TBROK, "probe: shmctl() failed at %s:%d", file, lineno);
94
95 addr = (void *)(((unsigned long)(addr) + (SHMLBA - 1)) & ~(SHMLBA - 1));
96
97 return addr;
98 }
99