xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/mlock/mlock03.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2010  Red Hat, Inc.
4  */
5 
6 /*\
7  * [Description]
8  *
9  * This case is a regression test on old RHEL5.
10  *
11  * Stack size mapping is decreased through mlock/munlock call.
12  * See the following url:
13  * https://bugzilla.redhat.com/show_bug.cgi?id=643426
14  *
15  * This is to test kernel if it has a problem with shortening [stack]
16  * mapping through several loops of mlock/munlock of /proc/self/maps.
17  *
18  * From:
19  * munlock     76KiB bfef2000-bff05000 rw-p 00000000 00:00 0          [stack]
20  *
21  * To:
22  * munlock     44KiB bfefa000-bff05000 rw-p 00000000 00:00 0          [stack]
23  *
24  * with more iterations - could drop to 0KiB.
25  */
26 
27 #include <sys/mman.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <pwd.h>
31 #include "tst_test.h"
32 #include "tst_safe_stdio.h"
33 
34 #define KB 1024
35 
verify_mlock(void)36 static void verify_mlock(void)
37 {
38 	long from, to;
39 	long first = -1, last = -1;
40 	char b[KB];
41 	FILE *fp;
42 
43 	fp = SAFE_FOPEN("/proc/self/maps", "r");
44 	while (!feof(fp)) {
45 		if (!fgets(b, KB - 1, fp))
46 			break;
47 		b[strlen(b) - 1] = '\0';
48 		if (sscanf(b, "%lx-%lx", &from, &to) != 2) {
49 			tst_brk(TBROK, "parse %s start and end address failed",
50 					b);
51 			continue;
52 		}
53 
54 		/* Record the initial stack size. */
55 		if (strstr(b, "[stack]") != NULL)
56 			first = (to - from) / KB;
57 
58 		tst_res(TINFO, "mlock [%lx,%lx]", from, to);
59 		if (mlock((const void *)from, to - from) == -1)
60 			tst_res(TINFO | TERRNO, "mlock failed");
61 
62 		tst_res(TINFO, "munlock [%lx,%lx]", from, to);
63 		if (munlock((void *)from, to - from) == -1)
64 			tst_res(TINFO | TERRNO, "munlock failed");
65 
66 		/* Record the final stack size. */
67 		if (strstr(b, "[stack]") != NULL)
68 			last = (to - from) / KB;
69 	}
70 	SAFE_FCLOSE(fp);
71 
72 	tst_res(TINFO, "starting stack size is %ld", first);
73 	tst_res(TINFO, "final stack size is %ld", last);
74 	if (last < first)
75 		tst_res(TFAIL, "stack size is decreased.");
76 	else
77 		tst_res(TPASS, "stack size is not decreased.");
78 }
79 
80 static struct tst_test test = {
81 	.test_all = verify_mlock,
82 };
83