blob: 5ca83cce6b70f656cdd3916cc1a722f11e32936e [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
Diego Wilsona22240b2020-04-02 18:11:28 +000057 srcDir string
58 outDir string
59 distDir string
Dan Willemsen63663c62019-01-02 12:24:44 -080060}
61
Dan Willemsen269a8c72017-05-03 17:15:47 -070062func (c *Cmd) sandboxSupported() bool {
Dan Willemsen63663c62019-01-02 12:24:44 -080063 if !c.Sandbox.Enabled {
64 return false
65 }
66
67 // Goma is incompatible with PID namespaces and Mount namespaces. b/122767582
68 if c.Sandbox.DisableWhenUsingGoma && c.config.UseGoma() {
69 return false
70 }
71
72 sandboxConfig.once.Do(func() {
73 sandboxConfig.group = "nogroup"
74 if _, err := user.LookupGroup(sandboxConfig.group); err != nil {
75 sandboxConfig.group = "nobody"
76 }
77
Diego Wilsona22240b2020-04-02 18:11:28 +000078 sandboxConfig.srcDir = absPath(c.ctx, ".")
79 sandboxConfig.outDir = absPath(c.ctx, c.config.OutDir())
80 sandboxConfig.distDir = absPath(c.ctx, c.config.DistDir())
81
Dan Willemsen63663c62019-01-02 12:24:44 -080082 cmd := exec.CommandContext(c.ctx.Context, nsjailPath,
83 "-H", "android-build",
84 "-e",
85 "-u", "nobody",
86 "-g", sandboxConfig.group,
Diego Wilsona22240b2020-04-02 18:11:28 +000087 "-R", "/",
88 "-B", sandboxConfig.srcDir,
89 "-B", "/tmp",
90 "-B", sandboxConfig.outDir,
91 "-B", sandboxConfig.distDir,
Dan Willemsen63663c62019-01-02 12:24:44 -080092 "--disable_clone_newcgroup",
93 "--",
94 "/bin/bash", "-c", `if [ $(hostname) == "android-build" ]; then echo "Android" "Success"; else echo Failure; fi`)
95 cmd.Env = c.config.Environment().Environ()
96
97 c.ctx.Verboseln(cmd.Args)
98 data, err := cmd.CombinedOutput()
99 if err == nil && bytes.Contains(data, []byte("Android Success")) {
100 sandboxConfig.working = true
101 return
102 }
103
Dan Willemsen1871d882020-03-02 20:36:04 +0000104 c.ctx.Println("Build sandboxing disabled due to nsjail error.")
Dan Willemsen63663c62019-01-02 12:24:44 -0800105
106 for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
107 c.ctx.Verboseln(line)
108 }
109
110 if err == nil {
111 c.ctx.Verboseln("nsjail exited successfully, but without the correct output")
112 } else if e, ok := err.(*exec.ExitError); ok {
113 c.ctx.Verbosef("nsjail failed with %v", e.ProcessState.String())
114 } else {
115 c.ctx.Verbosef("nsjail failed with %v", err)
116 }
117 })
118
119 return sandboxConfig.working
Dan Willemsen269a8c72017-05-03 17:15:47 -0700120}
121
122func (c *Cmd) wrapSandbox() {
Dan Willemsen63663c62019-01-02 12:24:44 -0800123 wd, _ := os.Getwd()
124
125 sandboxArgs := []string{
126 // The executable to run
127 "-x", c.Path,
128
129 // Set the hostname to something consistent
130 "-H", "android-build",
131
132 // Use the current working dir
133 "--cwd", wd,
134
135 // No time limit
136 "-t", "0",
137
138 // Keep all environment variables, we already filter them out
139 // in soong_ui
140 "-e",
141
Dan Willemsen3a4dbd62019-01-16 23:02:24 -0800142 // Mount /proc read-write, necessary to run a nested nsjail or minijail0
143 "--proc_rw",
144
Dan Willemsen63663c62019-01-02 12:24:44 -0800145 // Use a consistent user & group.
146 // Note that these are mapped back to the real UID/GID when
147 // doing filesystem operations, so they're rather arbitrary.
148 "-u", "nobody",
149 "-g", sandboxConfig.group,
150
151 // Set high values, as nsjail uses low defaults.
152 "--rlimit_as", "soft",
153 "--rlimit_core", "soft",
154 "--rlimit_cpu", "soft",
155 "--rlimit_fsize", "soft",
156 "--rlimit_nofile", "soft",
157
Diego Wilsona22240b2020-04-02 18:11:28 +0000158 // For now, just map everything. Make most things readonly.
159 "-R", "/",
160
161 // Mount source are read-write
162 "-B", sandboxConfig.srcDir,
163
164 //Mount out dir as read-write
165 "-B", sandboxConfig.outDir,
166
167 //Mount dist dir as read-write
168 "-B", sandboxConfig.distDir,
169
170 // Mount a writable tmp dir
171 "-B", "/tmp",
Dan Willemsen63663c62019-01-02 12:24:44 -0800172
Dan Willemsen63663c62019-01-02 12:24:44 -0800173 // Disable newcgroup for now, since it may require newer kernels
174 // TODO: try out cgroups
175 "--disable_clone_newcgroup",
176
177 // Only log important warnings / errors
178 "-q",
Dan Willemsen63663c62019-01-02 12:24:44 -0800179 }
Dan Willemsen25e6f092019-04-09 10:22:43 -0700180
181 if c.Sandbox.AllowBuildBrokenUsesNetwork && c.config.BuildBrokenUsesNetwork() {
182 c.ctx.Printf("AllowBuildBrokenUsesNetwork: %v", c.Sandbox.AllowBuildBrokenUsesNetwork)
183 c.ctx.Printf("BuildBrokenUsesNetwork: %v", c.config.BuildBrokenUsesNetwork())
184 sandboxArgs = append(sandboxArgs, "-N")
Colin Crossaa812d12019-06-19 13:33:24 -0700185 } else if dlv, _ := c.config.Environment().Get("SOONG_DELVE"); dlv != "" {
186 // The debugger is enabled and soong_build will pause until a remote delve process connects, allow
187 // network connections.
188 sandboxArgs = append(sandboxArgs, "-N")
Dan Willemsen25e6f092019-04-09 10:22:43 -0700189 }
190
191 // Stop nsjail from parsing arguments
192 sandboxArgs = append(sandboxArgs, "--")
193
Dan Willemsen63663c62019-01-02 12:24:44 -0800194 c.Args = append(sandboxArgs, c.Args[1:]...)
195 c.Path = nsjailPath
196
197 env := Environment(c.Env)
198 if _, hasUser := env.Get("USER"); hasUser {
199 env.Set("USER", "nobody")
200 }
201 c.Env = []string(env)
Dan Willemsen269a8c72017-05-03 17:15:47 -0700202}