blob: a3a1aaf6867e75037cd86b1c1fecada123982f2f [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"
Rupert Shuttleworth755ceb02021-08-11 09:20:27 -040020 "io/fs"
Dan Willemsenf052f782017-05-18 15:29:04 -070021 "io/ioutil"
22 "os"
23 "path/filepath"
Dan Willemsen1e775d72020-01-03 13:40:45 -080024 "sort"
Dan Willemsenf052f782017-05-18 15:29:04 -070025 "strings"
Nan Zhang17f27672018-12-12 16:01:49 -080026
27 "android/soong/ui/metrics"
Dan Willemsenf052f782017-05-18 15:29:04 -070028)
29
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000030// Given a series of glob patterns, remove matching files and directories from the filesystem.
31// For example, "malware*" would remove all files and directories in the current directory that begin with "malware".
Dan Willemsenf052f782017-05-18 15:29:04 -070032func removeGlobs(ctx Context, globs ...string) {
33 for _, glob := range globs {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000034 // Find files and directories that match this glob pattern.
Dan Willemsenf052f782017-05-18 15:29:04 -070035 files, err := filepath.Glob(glob)
36 if err != nil {
37 // Only possible error is ErrBadPattern
38 panic(fmt.Errorf("%q: %s", glob, err))
39 }
40
41 for _, file := range files {
42 err = os.RemoveAll(file)
43 if err != nil {
44 ctx.Fatalf("Failed to remove file %q: %v", file, err)
45 }
46 }
47 }
48}
49
Rupert Shuttleworth755ceb02021-08-11 09:20:27 -040050// Based on https://stackoverflow.com/questions/28969455/how-to-properly-instantiate-os-filemode
51// Because Go doesn't provide a nice way to set bits on a filemode
52const (
53 FILEMODE_READ = 04
54 FILEMODE_WRITE = 02
55 FILEMODE_EXECUTE = 01
56 FILEMODE_USER_SHIFT = 6
57 FILEMODE_USER_READ = FILEMODE_READ << FILEMODE_USER_SHIFT
58 FILEMODE_USER_WRITE = FILEMODE_WRITE << FILEMODE_USER_SHIFT
59 FILEMODE_USER_EXECUTE = FILEMODE_EXECUTE << FILEMODE_USER_SHIFT
60)
61
62// Ensures that files and directories in the out dir can be deleted.
63// For example, Bazen can generate output directories where the write bit isn't set, causing 'm' clean' to fail.
64func ensureOutDirRemovable(ctx Context, config Config) {
65 err := filepath.WalkDir(config.OutDir(), func(path string, d fs.DirEntry, err error) error {
66 if err != nil {
67 return err
68 }
69 if d.IsDir() {
70 info, err := d.Info()
71 if err != nil {
72 return err
73 }
74 // Equivalent to running chmod u+rwx on each directory
75 newMode := info.Mode() | FILEMODE_USER_READ | FILEMODE_USER_WRITE | FILEMODE_USER_EXECUTE
76 if err := os.Chmod(path, newMode); err != nil {
77 return err
78 }
79 }
80 // Continue walking the out dir...
81 return nil
82 })
83 if err != nil && !os.IsNotExist(err) {
84 // Display the error, but don't crash.
85 ctx.Println(err.Error())
86 }
87}
88
Dan Willemsenf052f782017-05-18 15:29:04 -070089// Remove everything under the out directory. Don't remove the out directory
90// itself in case it's a symlink.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000091func clean(ctx Context, config Config) {
Rupert Shuttleworth755ceb02021-08-11 09:20:27 -040092 ensureOutDirRemovable(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -070093 removeGlobs(ctx, filepath.Join(config.OutDir(), "*"))
94 ctx.Println("Entire build directory removed.")
95}
96
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000097// Remove everything in the data directory.
98func dataClean(ctx Context, config Config) {
Dan Willemsenf052f782017-05-18 15:29:04 -070099 removeGlobs(ctx, filepath.Join(config.ProductOut(), "data", "*"))
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000100 ctx.Println("Entire data directory removed.")
Dan Willemsenf052f782017-05-18 15:29:04 -0700101}
102
103// installClean deletes all of the installed files -- the intent is to remove
104// files that may no longer be installed, either because the user previously
105// installed them, or they were previously installed by default but no longer
106// are.
107//
108// This is faster than a full clean, since we're not deleting the
109// intermediates. Instead of recompiling, we can just copy the results.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000110func installClean(ctx Context, config Config) {
111 dataClean(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -0700112
113 if hostCrossOutPath := config.hostCrossOut(); hostCrossOutPath != "" {
114 hostCrossOut := func(path string) string {
115 return filepath.Join(hostCrossOutPath, path)
116 }
117 removeGlobs(ctx,
118 hostCrossOut("bin"),
119 hostCrossOut("coverage"),
120 hostCrossOut("lib*"),
121 hostCrossOut("nativetest*"))
122 }
123
124 hostOutPath := config.HostOut()
125 hostOut := func(path string) string {
126 return filepath.Join(hostOutPath, path)
127 }
128
Colin Cross3e6f67a2020-10-09 19:11:22 -0700129 hostCommonOut := func(path string) string {
130 return filepath.Join(config.hostOutRoot(), "common", path)
131 }
132
Dan Willemsenf052f782017-05-18 15:29:04 -0700133 productOutPath := config.ProductOut()
134 productOut := func(path string) string {
135 return filepath.Join(productOutPath, path)
136 }
137
138 // Host bin, frameworks, and lib* are intentionally omitted, since
139 // otherwise we'd have to rebuild any generated files created with
140 // those tools.
141 removeGlobs(ctx,
Roland Levillaine5f9ee52019-09-11 14:50:08 +0100142 hostOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700143 hostOut("obj/NOTICE_FILES"),
144 hostOut("obj/PACKAGING"),
145 hostOut("coverage"),
146 hostOut("cts"),
147 hostOut("nativetest*"),
148 hostOut("sdk"),
149 hostOut("sdk_addon"),
150 hostOut("testcases"),
151 hostOut("vts"),
Dan Shi984c1292020-03-18 22:42:00 -0700152 hostOut("vts10"),
Dan Shi53f1a192019-11-26 10:02:53 -0800153 hostOut("vts-core"),
Colin Cross3e6f67a2020-10-09 19:11:22 -0700154 hostCommonOut("obj/PACKAGING"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700155 productOut("*.img"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700156 productOut("*.zip"),
Dan Willemsena18660d2017-06-01 14:23:36 -0700157 productOut("android-info.txt"),
Daniel Normanb8e7f812020-05-07 16:39:36 -0700158 productOut("misc_info.txt"),
Steven Moreland0aabb112019-08-26 11:31:33 -0700159 productOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700160 productOut("kernel"),
Yo Chiangd813f122021-01-22 00:16:47 +0800161 productOut("kernel-*"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700162 productOut("data"),
163 productOut("skin"),
164 productOut("obj/NOTICE_FILES"),
165 productOut("obj/PACKAGING"),
Tom Cherry7803a012018-08-08 13:24:32 -0700166 productOut("ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800167 productOut("debug_ramdisk"),
Petri Gyntherac229562021-03-02 23:44:02 -0800168 productOut("vendor_ramdisk"),
Will McVicker4cee6252020-03-19 11:57:11 -0700169 productOut("vendor_debug_ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800170 productOut("test_harness_ramdisk"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700171 productOut("recovery"),
172 productOut("root"),
173 productOut("system"),
174 productOut("system_other"),
175 productOut("vendor"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700176 productOut("vendor_dlkm"),
Jaekyun Seokf6307cc2018-05-16 12:25:41 +0900177 productOut("product"),
Justin Yund5f6c822019-06-25 16:47:17 +0900178 productOut("system_ext"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700179 productOut("oem"),
180 productOut("obj/FAKE"),
181 productOut("breakpad"),
182 productOut("cache"),
183 productOut("coverage"),
184 productOut("installer"),
185 productOut("odm"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700186 productOut("odm_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700187 productOut("sysloader"),
Colin Crossf7bcd422021-04-27 19:45:25 -0700188 productOut("testcases"),
189 productOut("symbols"))
Dan Willemsenf052f782017-05-18 15:29:04 -0700190}
191
192// Since products and build variants (unfortunately) shared the same
193// PRODUCT_OUT staging directory, things can get out of sync if different
194// build configurations are built in the same tree. This function will
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000195// notice when the configuration has changed and call installClean to
Dan Willemsenf052f782017-05-18 15:29:04 -0700196// remove the files necessary to keep things consistent.
197func installCleanIfNecessary(ctx Context, config Config) {
198 configFile := config.DevicePreviousProductConfig()
199 prefix := "PREVIOUS_BUILD_CONFIG := "
200 suffix := "\n"
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000201 currentConfig := prefix + config.TargetProduct() + "-" + config.TargetBuildVariant() + suffix
Dan Willemsenf052f782017-05-18 15:29:04 -0700202
Dan Willemsene0879fc2017-08-04 15:06:27 -0700203 ensureDirectoriesExist(ctx, filepath.Dir(configFile))
204
Dan Willemsenf052f782017-05-18 15:29:04 -0700205 writeConfig := func() {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000206 err := ioutil.WriteFile(configFile, []byte(currentConfig), 0666) // a+rw
Dan Willemsenf052f782017-05-18 15:29:04 -0700207 if err != nil {
208 ctx.Fatalln("Failed to write product config:", err)
209 }
210 }
211
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000212 previousConfigBytes, err := ioutil.ReadFile(configFile)
Dan Willemsenf052f782017-05-18 15:29:04 -0700213 if err != nil {
214 if os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000215 // Just write the new config file, no old config file to worry about.
Dan Willemsenf052f782017-05-18 15:29:04 -0700216 writeConfig()
217 return
218 } else {
219 ctx.Fatalln("Failed to read previous product config:", err)
220 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000221 }
222
223 previousConfig := string(previousConfigBytes)
224 if previousConfig == currentConfig {
225 // Same config as before - nothing to clean.
Dan Willemsenf052f782017-05-18 15:29:04 -0700226 return
227 }
228
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000229 if config.Environment().IsEnvTrue("DISABLE_AUTO_INSTALLCLEAN") {
230 ctx.Println("DISABLE_AUTO_INSTALLCLEAN is set and true; skipping auto-clean. Your tree may be in an inconsistent state.")
Dan Willemsenf052f782017-05-18 15:29:04 -0700231 return
232 }
233
Nan Zhang17f27672018-12-12 16:01:49 -0800234 ctx.BeginTrace(metrics.PrimaryNinja, "installclean")
Dan Willemsenf052f782017-05-18 15:29:04 -0700235 defer ctx.EndTrace()
236
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000237 previousProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(previousConfig, suffix), prefix)
238 currentProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(currentConfig, suffix), prefix)
Dan Willemsenf052f782017-05-18 15:29:04 -0700239
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000240 ctx.Printf("Build configuration changed: %q -> %q, forcing installclean\n", previousProductAndVariant, currentProductAndVariant)
Dan Willemsenf052f782017-05-18 15:29:04 -0700241
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000242 installClean(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -0700243
244 writeConfig()
245}
Dan Willemsen1e775d72020-01-03 13:40:45 -0800246
247// cleanOldFiles takes an input file (with all paths relative to basePath), and removes files from
248// the filesystem if they were removed from the input file since the last execution.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000249func cleanOldFiles(ctx Context, basePath, newFile string) {
250 newFile = filepath.Join(basePath, newFile)
251 oldFile := newFile + ".previous"
Dan Willemsen1e775d72020-01-03 13:40:45 -0800252
Cole Faust521e9512021-09-14 15:06:23 -0700253 if _, err := os.Stat(newFile); os.IsNotExist(err) {
254 // If the file doesn't exist, assume no installed files exist either
255 return
256 } else if err != nil {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000257 ctx.Fatalf("Expected %q to be readable", newFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800258 }
259
260 if _, err := os.Stat(oldFile); os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000261 if err := os.Rename(newFile, oldFile); err != nil {
262 ctx.Fatalf("Failed to rename file list (%q->%q): %v", newFile, oldFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800263 }
264 return
265 }
266
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000267 var newData, oldData []byte
268 if data, err := ioutil.ReadFile(newFile); err == nil {
269 newData = data
Dan Willemsen1e775d72020-01-03 13:40:45 -0800270 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000271 ctx.Fatalf("Failed to read list of installable files (%q): %v", newFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800272 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000273 if data, err := ioutil.ReadFile(oldFile); err == nil {
274 oldData = data
275 } else {
276 ctx.Fatalf("Failed to read list of installable files (%q): %v", oldFile, err)
277 }
278
279 // Common case: nothing has changed
280 if bytes.Equal(newData, oldData) {
281 return
282 }
283
284 var newPaths, oldPaths []string
285 newPaths = strings.Fields(string(newData))
286 oldPaths = strings.Fields(string(oldData))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800287
288 // These should be mostly sorted by make already, but better make sure Go concurs
289 sort.Strings(newPaths)
290 sort.Strings(oldPaths)
291
292 for len(oldPaths) > 0 {
293 if len(newPaths) > 0 {
294 if oldPaths[0] == newPaths[0] {
295 // Same file; continue
296 newPaths = newPaths[1:]
297 oldPaths = oldPaths[1:]
298 continue
299 } else if oldPaths[0] > newPaths[0] {
300 // New file; ignore
301 newPaths = newPaths[1:]
302 continue
303 }
304 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000305
Dan Willemsen1e775d72020-01-03 13:40:45 -0800306 // File only exists in the old list; remove if it exists
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000307 oldPath := filepath.Join(basePath, oldPaths[0])
Dan Willemsen1e775d72020-01-03 13:40:45 -0800308 oldPaths = oldPaths[1:]
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000309
310 if oldFile, err := os.Stat(oldPath); err == nil {
311 if oldFile.IsDir() {
312 if err := os.Remove(oldPath); err == nil {
313 ctx.Println("Removed directory that is no longer installed: ", oldPath)
314 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800315 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000316 ctx.Println("Failed to remove directory that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800317 ctx.Println("It's recommended to run `m installclean`")
318 }
319 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000320 // Removing a file, not a directory.
321 if err := os.Remove(oldPath); err == nil {
322 ctx.Println("Removed file that is no longer installed: ", oldPath)
323 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800324 } else if !os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000325 ctx.Fatalf("Failed to remove file that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800326 }
327 }
328 }
329 }
330
331 // Use the new list as the base for the next build
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000332 os.Rename(newFile, oldFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800333}
Dan Willemsen46459b02020-02-13 14:37:15 -0800334
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000335// cleanEmptyDirs will delete a directory if it contains no files.
336// If a deletion occurs, then it also recurses upwards to try and delete empty parent directories.
Dan Willemsen46459b02020-02-13 14:37:15 -0800337func cleanEmptyDirs(ctx Context, dir string) {
338 files, err := ioutil.ReadDir(dir)
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000339 if err != nil {
340 ctx.Println("Could not read directory while trying to clean empty dirs: ", dir)
Dan Willemsen46459b02020-02-13 14:37:15 -0800341 return
342 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000343 if len(files) > 0 {
344 // Directory is not empty.
345 return
Dan Willemsen46459b02020-02-13 14:37:15 -0800346 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000347
348 if err := os.Remove(dir); err == nil {
349 ctx.Println("Removed empty directory (may no longer be installed?): ", dir)
350 } else {
351 ctx.Fatalf("Failed to remove empty directory (which may no longer be installed?) %q: (%v)", dir, err)
352 }
353
354 // Try and delete empty parent directories too.
Dan Willemsen46459b02020-02-13 14:37:15 -0800355 cleanEmptyDirs(ctx, filepath.Dir(dir))
356}