1 /* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 #include <dlfcn.h>
7 #include <errno.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11 
12 #include "libminijail.h"
13 
14 #include "elfparse.h"
15 #include "minijail0_cli.h"
16 #include "util.h"
17 
main(int argc,char * argv[])18 int main(int argc, char *argv[])
19 {
20 	struct minijail *j = minijail_new();
21 	const char *dl_mesg = NULL;
22 	int exit_immediately = 0;
23 	ElfType elftype = ELFERROR;
24 	int consumed = parse_args(j, argc, argv, &exit_immediately, &elftype);
25 	argc -= consumed;
26 	argv += consumed;
27 
28 	/*
29 	 * Make the process group ID of this process equal to its PID.
30 	 * In the non-interactive case (e.g. when minijail0 is started from
31 	 * init) this ensures the parent process and the jailed process
32 	 * can be killed together.
33 	 *
34 	 * Don't fail on EPERM, since setpgid(0, 0) can only EPERM when
35 	 * the process is already a process group leader.
36 	 */
37 	if (setpgid(0 /* use calling PID */, 0 /* make PGID = PID */)) {
38 		if (errno != EPERM) {
39 			fprintf(stderr, "setpgid(0, 0) failed\n");
40 			exit(1);
41 		}
42 	}
43 
44 	if (elftype == ELFSTATIC) {
45 		/*
46 		 * Target binary is statically linked so we cannot use
47 		 * libminijailpreload.so.
48 		 */
49 		minijail_run_no_preload(j, argv[0], argv);
50 	} else if (elftype == ELFDYNAMIC) {
51 		/*
52 		 * Target binary is dynamically linked so we can
53 		 * inject libminijailpreload.so into it.
54 		 */
55 
56 		/* Check that we can dlopen() libminijailpreload.so. */
57 		if (!dlopen(PRELOADPATH, RTLD_LAZY | RTLD_LOCAL)) {
58 			dl_mesg = dlerror();
59 			fprintf(stderr, "dlopen(): %s\n", dl_mesg);
60 			return 1;
61 		}
62 		minijail_run(j, argv[0], argv);
63 	} else {
64 		fprintf(stderr,
65 			"Target program '%s' is not a valid ELF file.\n",
66 			argv[0]);
67 		return 1;
68 	}
69 
70 	if (exit_immediately) {
71 		info("not running init loop, exiting immediately\n");
72 		return 0;
73 	}
74 	int ret = minijail_wait(j);
75 #if defined(__SANITIZE_ADDRESS__)
76 	minijail_destroy(j);
77 #endif /* __SANITIZE_ADDRESS__ */
78 	return ret;
79 }
80