blob: 03e884a657d72087522dcce000c8c93a926fc9db [file] [log] [blame]
Dan Willemsenf052f782017-05-18 15:29:04 -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
17import (
Dan Willemsen1e775d72020-01-03 13:40:45 -080018 "bytes"
Dan Willemsenf052f782017-05-18 15:29:04 -070019 "fmt"
20 "io/ioutil"
21 "os"
22 "path/filepath"
Dan Willemsen1e775d72020-01-03 13:40:45 -080023 "sort"
Dan Willemsenf052f782017-05-18 15:29:04 -070024 "strings"
Nan Zhang17f27672018-12-12 16:01:49 -080025
26 "android/soong/ui/metrics"
Dan Willemsenf052f782017-05-18 15:29:04 -070027)
28
29func removeGlobs(ctx Context, globs ...string) {
30 for _, glob := range globs {
31 files, err := filepath.Glob(glob)
32 if err != nil {
33 // Only possible error is ErrBadPattern
34 panic(fmt.Errorf("%q: %s", glob, err))
35 }
36
37 for _, file := range files {
38 err = os.RemoveAll(file)
39 if err != nil {
40 ctx.Fatalf("Failed to remove file %q: %v", file, err)
41 }
42 }
43 }
44}
45
46// Remove everything under the out directory. Don't remove the out directory
47// itself in case it's a symlink.
48func clean(ctx Context, config Config, what int) {
49 removeGlobs(ctx, filepath.Join(config.OutDir(), "*"))
50 ctx.Println("Entire build directory removed.")
51}
52
53func dataClean(ctx Context, config Config, what int) {
54 removeGlobs(ctx, filepath.Join(config.ProductOut(), "data", "*"))
55}
56
57// installClean deletes all of the installed files -- the intent is to remove
58// files that may no longer be installed, either because the user previously
59// installed them, or they were previously installed by default but no longer
60// are.
61//
62// This is faster than a full clean, since we're not deleting the
63// intermediates. Instead of recompiling, we can just copy the results.
64func installClean(ctx Context, config Config, what int) {
65 dataClean(ctx, config, what)
66
67 if hostCrossOutPath := config.hostCrossOut(); hostCrossOutPath != "" {
68 hostCrossOut := func(path string) string {
69 return filepath.Join(hostCrossOutPath, path)
70 }
71 removeGlobs(ctx,
72 hostCrossOut("bin"),
73 hostCrossOut("coverage"),
74 hostCrossOut("lib*"),
75 hostCrossOut("nativetest*"))
76 }
77
78 hostOutPath := config.HostOut()
79 hostOut := func(path string) string {
80 return filepath.Join(hostOutPath, path)
81 }
82
Colin Cross3e6f67a2020-10-09 19:11:22 -070083 hostCommonOut := func(path string) string {
84 return filepath.Join(config.hostOutRoot(), "common", path)
85 }
86
Dan Willemsenf052f782017-05-18 15:29:04 -070087 productOutPath := config.ProductOut()
88 productOut := func(path string) string {
89 return filepath.Join(productOutPath, path)
90 }
91
92 // Host bin, frameworks, and lib* are intentionally omitted, since
93 // otherwise we'd have to rebuild any generated files created with
94 // those tools.
95 removeGlobs(ctx,
Roland Levillaine5f9ee52019-09-11 14:50:08 +010096 hostOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -070097 hostOut("obj/NOTICE_FILES"),
98 hostOut("obj/PACKAGING"),
99 hostOut("coverage"),
100 hostOut("cts"),
101 hostOut("nativetest*"),
102 hostOut("sdk"),
103 hostOut("sdk_addon"),
104 hostOut("testcases"),
105 hostOut("vts"),
Dan Shi984c1292020-03-18 22:42:00 -0700106 hostOut("vts10"),
Dan Shi53f1a192019-11-26 10:02:53 -0800107 hostOut("vts-core"),
Colin Cross3e6f67a2020-10-09 19:11:22 -0700108 hostCommonOut("obj/PACKAGING"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700109 productOut("*.img"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700110 productOut("*.zip"),
Dan Willemsena18660d2017-06-01 14:23:36 -0700111 productOut("android-info.txt"),
Daniel Normanb8e7f812020-05-07 16:39:36 -0700112 productOut("misc_info.txt"),
Steven Moreland0aabb112019-08-26 11:31:33 -0700113 productOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700114 productOut("kernel"),
115 productOut("data"),
116 productOut("skin"),
117 productOut("obj/NOTICE_FILES"),
118 productOut("obj/PACKAGING"),
Tom Cherry7803a012018-08-08 13:24:32 -0700119 productOut("ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800120 productOut("debug_ramdisk"),
Will McVicker4cee6252020-03-19 11:57:11 -0700121 productOut("vendor-ramdisk"),
122 productOut("vendor-ramdisk-debug.cpio.gz"),
123 productOut("vendor_debug_ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800124 productOut("test_harness_ramdisk"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700125 productOut("recovery"),
126 productOut("root"),
127 productOut("system"),
128 productOut("system_other"),
129 productOut("vendor"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700130 productOut("vendor_dlkm"),
Jaekyun Seokf6307cc2018-05-16 12:25:41 +0900131 productOut("product"),
Justin Yund5f6c822019-06-25 16:47:17 +0900132 productOut("system_ext"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700133 productOut("oem"),
134 productOut("obj/FAKE"),
135 productOut("breakpad"),
136 productOut("cache"),
137 productOut("coverage"),
138 productOut("installer"),
139 productOut("odm"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700140 productOut("odm_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700141 productOut("sysloader"),
142 productOut("testcases"))
143}
144
145// Since products and build variants (unfortunately) shared the same
146// PRODUCT_OUT staging directory, things can get out of sync if different
147// build configurations are built in the same tree. This function will
148// notice when the configuration has changed and call installclean to
149// remove the files necessary to keep things consistent.
150func installCleanIfNecessary(ctx Context, config Config) {
151 configFile := config.DevicePreviousProductConfig()
152 prefix := "PREVIOUS_BUILD_CONFIG := "
153 suffix := "\n"
154 currentProduct := prefix + config.TargetProduct() + "-" + config.TargetBuildVariant() + suffix
155
Dan Willemsene0879fc2017-08-04 15:06:27 -0700156 ensureDirectoriesExist(ctx, filepath.Dir(configFile))
157
Dan Willemsenf052f782017-05-18 15:29:04 -0700158 writeConfig := func() {
159 err := ioutil.WriteFile(configFile, []byte(currentProduct), 0666)
160 if err != nil {
161 ctx.Fatalln("Failed to write product config:", err)
162 }
163 }
164
165 prev, err := ioutil.ReadFile(configFile)
166 if err != nil {
167 if os.IsNotExist(err) {
168 writeConfig()
169 return
170 } else {
171 ctx.Fatalln("Failed to read previous product config:", err)
172 }
173 } else if string(prev) == currentProduct {
174 return
175 }
176
177 if disable, _ := config.Environment().Get("DISABLE_AUTO_INSTALLCLEAN"); disable == "true" {
178 ctx.Println("DISABLE_AUTO_INSTALLCLEAN is set; skipping auto-clean. Your tree may be in an inconsistent state.")
179 return
180 }
181
Nan Zhang17f27672018-12-12 16:01:49 -0800182 ctx.BeginTrace(metrics.PrimaryNinja, "installclean")
Dan Willemsenf052f782017-05-18 15:29:04 -0700183 defer ctx.EndTrace()
184
185 prevConfig := strings.TrimPrefix(strings.TrimSuffix(string(prev), suffix), prefix)
186 currentConfig := strings.TrimPrefix(strings.TrimSuffix(currentProduct, suffix), prefix)
187
188 ctx.Printf("Build configuration changed: %q -> %q, forcing installclean\n", prevConfig, currentConfig)
189
190 installClean(ctx, config, 0)
191
192 writeConfig()
193}
Dan Willemsen1e775d72020-01-03 13:40:45 -0800194
195// cleanOldFiles takes an input file (with all paths relative to basePath), and removes files from
196// the filesystem if they were removed from the input file since the last execution.
197func cleanOldFiles(ctx Context, basePath, file string) {
198 file = filepath.Join(basePath, file)
199 oldFile := file + ".previous"
200
201 if _, err := os.Stat(file); err != nil {
202 ctx.Fatalf("Expected %q to be readable", file)
203 }
204
205 if _, err := os.Stat(oldFile); os.IsNotExist(err) {
206 if err := os.Rename(file, oldFile); err != nil {
207 ctx.Fatalf("Failed to rename file list (%q->%q): %v", file, oldFile, err)
208 }
209 return
210 }
211
212 var newPaths, oldPaths []string
213 if newData, err := ioutil.ReadFile(file); err == nil {
214 if oldData, err := ioutil.ReadFile(oldFile); err == nil {
215 // Common case: nothing has changed
216 if bytes.Equal(newData, oldData) {
217 return
218 }
219 newPaths = strings.Fields(string(newData))
220 oldPaths = strings.Fields(string(oldData))
221 } else {
222 ctx.Fatalf("Failed to read list of installable files (%q): %v", oldFile, err)
223 }
224 } else {
225 ctx.Fatalf("Failed to read list of installable files (%q): %v", file, err)
226 }
227
228 // These should be mostly sorted by make already, but better make sure Go concurs
229 sort.Strings(newPaths)
230 sort.Strings(oldPaths)
231
232 for len(oldPaths) > 0 {
233 if len(newPaths) > 0 {
234 if oldPaths[0] == newPaths[0] {
235 // Same file; continue
236 newPaths = newPaths[1:]
237 oldPaths = oldPaths[1:]
238 continue
239 } else if oldPaths[0] > newPaths[0] {
240 // New file; ignore
241 newPaths = newPaths[1:]
242 continue
243 }
244 }
245 // File only exists in the old list; remove if it exists
246 old := filepath.Join(basePath, oldPaths[0])
247 oldPaths = oldPaths[1:]
248 if fi, err := os.Stat(old); err == nil {
249 if fi.IsDir() {
250 if err := os.Remove(old); err == nil {
251 ctx.Println("Removed directory that is no longer installed: ", old)
Dan Willemsen46459b02020-02-13 14:37:15 -0800252 cleanEmptyDirs(ctx, filepath.Dir(old))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800253 } else {
254 ctx.Println("Failed to remove directory that is no longer installed (%q): %v", old, err)
255 ctx.Println("It's recommended to run `m installclean`")
256 }
257 } else {
258 if err := os.Remove(old); err == nil {
259 ctx.Println("Removed file that is no longer installed: ", old)
Dan Willemsen46459b02020-02-13 14:37:15 -0800260 cleanEmptyDirs(ctx, filepath.Dir(old))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800261 } else if !os.IsNotExist(err) {
262 ctx.Fatalf("Failed to remove file that is no longer installed (%q): %v", old, err)
263 }
264 }
265 }
266 }
267
268 // Use the new list as the base for the next build
269 os.Rename(file, oldFile)
270}
Dan Willemsen46459b02020-02-13 14:37:15 -0800271
272func cleanEmptyDirs(ctx Context, dir string) {
273 files, err := ioutil.ReadDir(dir)
274 if err != nil || len(files) > 0 {
275 return
276 }
277 if err := os.Remove(dir); err == nil {
278 ctx.Println("Removed directory that is no longer installed: ", dir)
279 } else {
280 ctx.Fatalf("Failed to remove directory that is no longer installed (%q): %v", dir, err)
281 }
282 cleanEmptyDirs(ctx, filepath.Dir(dir))
283}