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 #include "tst_safe_stdio.h"
25 #include "tst_safe_sysv_ipc.h"
26 #include "tst_clocks.h"
27
28 #define BUFSIZE 1024
29
getipckey(const char * file,const int lineno)30 key_t getipckey(const char *file, const int lineno)
31 {
32 char buf[BUFSIZE];
33 key_t key;
34 int id;
35 static int count;
36
37 safe_getcwd(file, lineno, NULL, buf, BUFSIZE);
38
39 id = count % 26 + (int) 'a';
40 count++;
41
42 key = ftok(buf, id);
43 if (key == -1) {
44 tst_brk(TBROK | TERRNO,
45 "ftok() failed at %s:%d", file, lineno);
46 }
47
48 return key;
49 }
50
get_used_queues(const char * file,const int lineno)51 int get_used_queues(const char *file, const int lineno)
52 {
53 FILE *fp;
54 int used_queues = -1;
55 char buf[BUFSIZE];
56
57 fp = safe_fopen(file, lineno, NULL, "/proc/sysvipc/msg", "r");
58
59 while (fgets(buf, BUFSIZE, fp) != NULL)
60 used_queues++;
61
62 fclose(fp);
63
64 if (used_queues < 0) {
65 tst_brk(TBROK, "can't read /proc/sysvipc/msg to get "
66 "used message queues at %s:%d", file, lineno);
67 }
68
69 return used_queues;
70 }
71
probe_free_addr(const char * file,const int lineno)72 void *probe_free_addr(const char *file, const int lineno)
73 {
74 void *addr;
75 int shm_id = -1;
76 key_t probe_key = 0;
77
78 probe_key = GETIPCKEY();
79
80 shm_id = safe_shmget(file, lineno, probe_key, SHMLBA * 2,
81 SHM_RW | IPC_CREAT | IPC_EXCL);
82 addr = safe_shmat(file, lineno, shm_id, NULL, 0);
83 safe_shmdt(file, lineno, addr);
84 safe_shmctl(file, lineno, shm_id, IPC_RMID, NULL);
85
86 addr = (void *)(((unsigned long)(addr) + (SHMLBA - 1)) & ~(SHMLBA - 1));
87
88 return addr;
89 }
90
get_ipc_timestamp(void)91 time_t get_ipc_timestamp(void)
92 {
93 struct timespec ts;
94 int ret;
95
96 ret = tst_clock_gettime(CLOCK_REALTIME_COARSE, &ts);
97 if (ret < 0)
98 tst_brk(TBROK | TERRNO, "clock_gettime(CLOCK_REALTIME_COARSE)");
99
100 return ts.tv_sec;
101 }
102