blob: c477e923fccc7566fe2b593628ce6a07dccc0869 [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
83 productOutPath := config.ProductOut()
84 productOut := func(path string) string {
85 return filepath.Join(productOutPath, path)
86 }
87
88 // Host bin, frameworks, and lib* are intentionally omitted, since
89 // otherwise we'd have to rebuild any generated files created with
90 // those tools.
91 removeGlobs(ctx,
Roland Levillaine5f9ee52019-09-11 14:50:08 +010092 hostOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -070093 hostOut("obj/NOTICE_FILES"),
94 hostOut("obj/PACKAGING"),
95 hostOut("coverage"),
96 hostOut("cts"),
97 hostOut("nativetest*"),
98 hostOut("sdk"),
99 hostOut("sdk_addon"),
100 hostOut("testcases"),
101 hostOut("vts"),
Dan Shi1a9a9122020-03-31 20:34:10 +0000102 hostOut("vts10"),
Dan Shi53f1a192019-11-26 10:02:53 -0800103 hostOut("vts-core"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700104 productOut("*.img"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700105 productOut("*.zip"),
Michael Bestasb27b5502017-12-21 04:03:01 +0200106 productOut("*.zip.md5sum"),
Dan Willemsena18660d2017-06-01 14:23:36 -0700107 productOut("android-info.txt"),
Steven Moreland0aabb112019-08-26 11:31:33 -0700108 productOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700109 productOut("kernel"),
110 productOut("data"),
111 productOut("skin"),
112 productOut("obj/NOTICE_FILES"),
113 productOut("obj/PACKAGING"),
Tom Cherry7803a012018-08-08 13:24:32 -0700114 productOut("ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800115 productOut("debug_ramdisk"),
Will McVicker92326a92020-03-19 11:57:11 -0700116 productOut("vendor-ramdisk"),
117 productOut("vendor-ramdisk-debug.cpio.gz"),
118 productOut("vendor_debug_ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800119 productOut("test_harness_ramdisk"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700120 productOut("recovery"),
121 productOut("root"),
122 productOut("system"),
123 productOut("system_other"),
124 productOut("vendor"),
Jaekyun Seokf6307cc2018-05-16 12:25:41 +0900125 productOut("product"),
Justin Yund5f6c822019-06-25 16:47:17 +0900126 productOut("system_ext"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700127 productOut("oem"),
128 productOut("obj/FAKE"),
129 productOut("breakpad"),
130 productOut("cache"),
131 productOut("coverage"),
132 productOut("installer"),
133 productOut("odm"),
134 productOut("sysloader"),
LuK1337b1902012020-11-13 15:11:27 +0100135 productOut("testcases"),
136 productOut("install"))
Dan Willemsenf052f782017-05-18 15:29:04 -0700137}
138
139// Since products and build variants (unfortunately) shared the same
140// PRODUCT_OUT staging directory, things can get out of sync if different
141// build configurations are built in the same tree. This function will
142// notice when the configuration has changed and call installclean to
143// remove the files necessary to keep things consistent.
144func installCleanIfNecessary(ctx Context, config Config) {
145 configFile := config.DevicePreviousProductConfig()
146 prefix := "PREVIOUS_BUILD_CONFIG := "
147 suffix := "\n"
148 currentProduct := prefix + config.TargetProduct() + "-" + config.TargetBuildVariant() + suffix
149
Dan Willemsene0879fc2017-08-04 15:06:27 -0700150 ensureDirectoriesExist(ctx, filepath.Dir(configFile))
151
Dan Willemsenf052f782017-05-18 15:29:04 -0700152 writeConfig := func() {
153 err := ioutil.WriteFile(configFile, []byte(currentProduct), 0666)
154 if err != nil {
155 ctx.Fatalln("Failed to write product config:", err)
156 }
157 }
158
159 prev, err := ioutil.ReadFile(configFile)
160 if err != nil {
161 if os.IsNotExist(err) {
162 writeConfig()
163 return
164 } else {
165 ctx.Fatalln("Failed to read previous product config:", err)
166 }
167 } else if string(prev) == currentProduct {
168 return
169 }
170
171 if disable, _ := config.Environment().Get("DISABLE_AUTO_INSTALLCLEAN"); disable == "true" {
172 ctx.Println("DISABLE_AUTO_INSTALLCLEAN is set; skipping auto-clean. Your tree may be in an inconsistent state.")
173 return
174 }
175
Nan Zhang17f27672018-12-12 16:01:49 -0800176 ctx.BeginTrace(metrics.PrimaryNinja, "installclean")
Dan Willemsenf052f782017-05-18 15:29:04 -0700177 defer ctx.EndTrace()
178
179 prevConfig := strings.TrimPrefix(strings.TrimSuffix(string(prev), suffix), prefix)
180 currentConfig := strings.TrimPrefix(strings.TrimSuffix(currentProduct, suffix), prefix)
181
182 ctx.Printf("Build configuration changed: %q -> %q, forcing installclean\n", prevConfig, currentConfig)
183
184 installClean(ctx, config, 0)
185
186 writeConfig()
187}
Dan Willemsen1e775d72020-01-03 13:40:45 -0800188
189// cleanOldFiles takes an input file (with all paths relative to basePath), and removes files from
190// the filesystem if they were removed from the input file since the last execution.
191func cleanOldFiles(ctx Context, basePath, file string) {
192 file = filepath.Join(basePath, file)
193 oldFile := file + ".previous"
194
195 if _, err := os.Stat(file); err != nil {
196 ctx.Fatalf("Expected %q to be readable", file)
197 }
198
199 if _, err := os.Stat(oldFile); os.IsNotExist(err) {
200 if err := os.Rename(file, oldFile); err != nil {
201 ctx.Fatalf("Failed to rename file list (%q->%q): %v", file, oldFile, err)
202 }
203 return
204 }
205
206 var newPaths, oldPaths []string
207 if newData, err := ioutil.ReadFile(file); err == nil {
208 if oldData, err := ioutil.ReadFile(oldFile); err == nil {
209 // Common case: nothing has changed
210 if bytes.Equal(newData, oldData) {
211 return
212 }
213 newPaths = strings.Fields(string(newData))
214 oldPaths = strings.Fields(string(oldData))
215 } else {
216 ctx.Fatalf("Failed to read list of installable files (%q): %v", oldFile, err)
217 }
218 } else {
219 ctx.Fatalf("Failed to read list of installable files (%q): %v", file, err)
220 }
221
222 // These should be mostly sorted by make already, but better make sure Go concurs
223 sort.Strings(newPaths)
224 sort.Strings(oldPaths)
225
226 for len(oldPaths) > 0 {
227 if len(newPaths) > 0 {
228 if oldPaths[0] == newPaths[0] {
229 // Same file; continue
230 newPaths = newPaths[1:]
231 oldPaths = oldPaths[1:]
232 continue
233 } else if oldPaths[0] > newPaths[0] {
234 // New file; ignore
235 newPaths = newPaths[1:]
236 continue
237 }
238 }
239 // File only exists in the old list; remove if it exists
240 old := filepath.Join(basePath, oldPaths[0])
241 oldPaths = oldPaths[1:]
242 if fi, err := os.Stat(old); err == nil {
243 if fi.IsDir() {
244 if err := os.Remove(old); err == nil {
245 ctx.Println("Removed directory that is no longer installed: ", old)
Dan Willemsen46459b02020-02-13 14:37:15 -0800246 cleanEmptyDirs(ctx, filepath.Dir(old))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800247 } else {
248 ctx.Println("Failed to remove directory that is no longer installed (%q): %v", old, err)
249 ctx.Println("It's recommended to run `m installclean`")
250 }
251 } else {
252 if err := os.Remove(old); err == nil {
253 ctx.Println("Removed file that is no longer installed: ", old)
Dan Willemsen46459b02020-02-13 14:37:15 -0800254 cleanEmptyDirs(ctx, filepath.Dir(old))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800255 } else if !os.IsNotExist(err) {
256 ctx.Fatalf("Failed to remove file that is no longer installed (%q): %v", old, err)
257 }
258 }
259 }
260 }
261
262 // Use the new list as the base for the next build
263 os.Rename(file, oldFile)
264}
Dan Willemsen46459b02020-02-13 14:37:15 -0800265
266func cleanEmptyDirs(ctx Context, dir string) {
267 files, err := ioutil.ReadDir(dir)
268 if err != nil || len(files) > 0 {
269 return
270 }
271 if err := os.Remove(dir); err == nil {
272 ctx.Println("Removed directory that is no longer installed: ", dir)
273 } else {
274 ctx.Fatalf("Failed to remove directory that is no longer installed (%q): %v", dir, err)
275 }
276 cleanEmptyDirs(ctx, filepath.Dir(dir))
277}
Alberto97ead67922018-05-05 22:01:02 +0200278
279// Remove everything relevant for a clean ota package
280func deviceClean(ctx Context, config Config, what int) {
Harsh Shandilyabf1b9ae2019-05-12 05:48:29 +0530281 removeGlobs(ctx, config.ProductOut())
Alberto97ead67922018-05-05 22:01:02 +0200282}