xref: /linux/tools/testing/selftests/exec/recursion-depth.c (revision f14aa5ea415b8add245e976bfab96a12986c6843)
1 /*
2  * Copyright (c) 2019 Alexey Dobriyan <adobriyan@gmail.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 /* Test that pointing #! script interpreter to self doesn't recurse. */
17 #include <errno.h>
18 #include <sched.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <sys/mount.h>
25 #include <unistd.h>
26 #include "../kselftest.h"
27 
28 int main(void)
29 {
30 	int fd, rv;
31 
32 	ksft_print_header();
33 	ksft_set_plan(1);
34 
35 	if (unshare(CLONE_NEWNS) == -1) {
36 		if (errno == ENOSYS || errno == EPERM) {
37 			ksft_test_result_skip("error: unshare, errno %d\n", errno);
38 			ksft_finished();
39 		}
40 		ksft_exit_fail_perror("error: unshare");
41 	}
42 
43 	if (mount(NULL, "/", NULL, MS_PRIVATE | MS_REC, NULL) == -1)
44 		ksft_exit_fail_perror("error: mount '/'");
45 
46 	/* Require "exec" filesystem. */
47 	if (mount(NULL, "/tmp", "ramfs", 0, NULL) == -1)
48 		ksft_exit_fail_perror("error: mount ramfs");
49 
50 #define FILENAME "/tmp/1"
51 
52 	fd = creat(FILENAME, 0700);
53 	if (fd == -1)
54 		ksft_exit_fail_perror("error: creat");
55 
56 #define S "#!" FILENAME "\n"
57 	if (write(fd, S, strlen(S)) != strlen(S))
58 		ksft_exit_fail_perror("error: write");
59 
60 	close(fd);
61 
62 	rv = execve(FILENAME, NULL, NULL);
63 	ksft_test_result(rv == -1 && errno == ELOOP,
64 			 "execve failed as expected (ret %d, errno %d)\n", rv, errno);
65 	ksft_finished();
66 }
67