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