blob: 2de772b00a2ea1dae9e0a656a16817de67ac43cf [file] [log] [blame]
Dan Willemsen269a8c72017-05-03 17:15:47 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package build
16
Dan Willemsen63663c62019-01-02 12:24:44 -080017import (
18 "bytes"
19 "os"
20 "os/exec"
21 "os/user"
22 "strings"
23 "sync"
Dan Willemsen269a8c72017-05-03 17:15:47 -070024)
25
Dan Willemsen63663c62019-01-02 12:24:44 -080026type Sandbox struct {
27 Enabled bool
28 DisableWhenUsingGoma bool
Dan Willemsen25e6f092019-04-09 10:22:43 -070029
30 AllowBuildBrokenUsesNetwork bool
Dan Willemsen63663c62019-01-02 12:24:44 -080031}
32
33var (
34 noSandbox = Sandbox{}
35 basicSandbox = Sandbox{
36 Enabled: true,
37 }
38
39 dumpvarsSandbox = basicSandbox
40 katiSandbox = basicSandbox
41 soongSandbox = basicSandbox
42 ninjaSandbox = Sandbox{
43 Enabled: true,
44 DisableWhenUsingGoma: true,
Dan Willemsen25e6f092019-04-09 10:22:43 -070045
46 AllowBuildBrokenUsesNetwork: true,
Dan Willemsen63663c62019-01-02 12:24:44 -080047 }
48)
49
50const nsjailPath = "prebuilts/build-tools/linux-x86/bin/nsjail"
51
52var sandboxConfig struct {
53 once sync.Once
54
55 working bool
56 group string
57}
58
Dan Willemsen269a8c72017-05-03 17:15:47 -070059func (c *Cmd) sandboxSupported() bool {
Dan Willemsen63663c62019-01-02 12:24:44 -080060 if !c.Sandbox.Enabled {
61 return false
62 }
63
64 // Goma is incompatible with PID namespaces and Mount namespaces. b/122767582
65 if c.Sandbox.DisableWhenUsingGoma && c.config.UseGoma() {
66 return false
67 }
68
69 sandboxConfig.once.Do(func() {
70 sandboxConfig.group = "nogroup"
71 if _, err := user.LookupGroup(sandboxConfig.group); err != nil {
72 sandboxConfig.group = "nobody"
73 }
74
75 cmd := exec.CommandContext(c.ctx.Context, nsjailPath,
76 "-H", "android-build",
77 "-e",
78 "-u", "nobody",
79 "-g", sandboxConfig.group,
80 "-B", "/",
81 "--disable_clone_newcgroup",
82 "--",
83 "/bin/bash", "-c", `if [ $(hostname) == "android-build" ]; then echo "Android" "Success"; else echo Failure; fi`)
84 cmd.Env = c.config.Environment().Environ()
85
86 c.ctx.Verboseln(cmd.Args)
87 data, err := cmd.CombinedOutput()
88 if err == nil && bytes.Contains(data, []byte("Android Success")) {
89 sandboxConfig.working = true
90 return
91 }
92
Dan Willemsen1871d882020-03-02 20:36:04 +000093 c.ctx.Println("Build sandboxing disabled due to nsjail error.")
Dan Willemsen63663c62019-01-02 12:24:44 -080094
95 for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
96 c.ctx.Verboseln(line)
97 }
98
99 if err == nil {
100 c.ctx.Verboseln("nsjail exited successfully, but without the correct output")
101 } else if e, ok := err.(*exec.ExitError); ok {
102 c.ctx.Verbosef("nsjail failed with %v", e.ProcessState.String())
103 } else {
104 c.ctx.Verbosef("nsjail failed with %v", err)
105 }
106 })
107
108 return sandboxConfig.working
Dan Willemsen269a8c72017-05-03 17:15:47 -0700109}
110
111func (c *Cmd) wrapSandbox() {
Dan Willemsen63663c62019-01-02 12:24:44 -0800112 wd, _ := os.Getwd()
113
114 sandboxArgs := []string{
115 // The executable to run
116 "-x", c.Path,
117
118 // Set the hostname to something consistent
119 "-H", "android-build",
120
121 // Use the current working dir
122 "--cwd", wd,
123
124 // No time limit
125 "-t", "0",
126
127 // Keep all environment variables, we already filter them out
128 // in soong_ui
129 "-e",
130
Dan Willemsen3a4dbd62019-01-16 23:02:24 -0800131 // Mount /proc read-write, necessary to run a nested nsjail or minijail0
132 "--proc_rw",
133
Dan Willemsen63663c62019-01-02 12:24:44 -0800134 // Use a consistent user & group.
135 // Note that these are mapped back to the real UID/GID when
136 // doing filesystem operations, so they're rather arbitrary.
137 "-u", "nobody",
138 "-g", sandboxConfig.group,
139
140 // Set high values, as nsjail uses low defaults.
141 "--rlimit_as", "soft",
142 "--rlimit_core", "soft",
143 "--rlimit_cpu", "soft",
144 "--rlimit_fsize", "soft",
145 "--rlimit_nofile", "soft",
146
147 // For now, just map everything. Eventually we should limit this, especially to make most things readonly.
148 "-B", "/",
149
Dan Willemsen63663c62019-01-02 12:24:44 -0800150 // Disable newcgroup for now, since it may require newer kernels
151 // TODO: try out cgroups
152 "--disable_clone_newcgroup",
153
154 // Only log important warnings / errors
155 "-q",
Dan Willemsen63663c62019-01-02 12:24:44 -0800156 }
Dan Willemsen25e6f092019-04-09 10:22:43 -0700157
158 if c.Sandbox.AllowBuildBrokenUsesNetwork && c.config.BuildBrokenUsesNetwork() {
159 c.ctx.Printf("AllowBuildBrokenUsesNetwork: %v", c.Sandbox.AllowBuildBrokenUsesNetwork)
160 c.ctx.Printf("BuildBrokenUsesNetwork: %v", c.config.BuildBrokenUsesNetwork())
161 sandboxArgs = append(sandboxArgs, "-N")
Colin Crossaa812d12019-06-19 13:33:24 -0700162 } else if dlv, _ := c.config.Environment().Get("SOONG_DELVE"); dlv != "" {
163 // The debugger is enabled and soong_build will pause until a remote delve process connects, allow
164 // network connections.
165 sandboxArgs = append(sandboxArgs, "-N")
Dan Willemsen25e6f092019-04-09 10:22:43 -0700166 }
167
168 // Stop nsjail from parsing arguments
169 sandboxArgs = append(sandboxArgs, "--")
170
Dan Willemsen63663c62019-01-02 12:24:44 -0800171 c.Args = append(sandboxArgs, c.Args[1:]...)
172 c.Path = nsjailPath
173
174 env := Environment(c.Env)
175 if _, hasUser := env.Get("USER"); hasUser {
176 env.Set("USER", "nobody")
177 }
178 c.Env = []string(env)
Dan Willemsen269a8c72017-05-03 17:15:47 -0700179}