blob: fd601772cc00623c6f48851e7cb92a68b44b65d2 [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"),
Yi-Yo Chiangda447952022-07-20 19:17:38 +0800170 productOut("vendor_kernel_ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800171 productOut("test_harness_ramdisk"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700172 productOut("recovery"),
173 productOut("root"),
174 productOut("system"),
Ramji Jiyanif0afc952022-02-04 23:03:53 +0000175 productOut("system_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700176 productOut("system_other"),
177 productOut("vendor"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700178 productOut("vendor_dlkm"),
Jaekyun Seokf6307cc2018-05-16 12:25:41 +0900179 productOut("product"),
Justin Yund5f6c822019-06-25 16:47:17 +0900180 productOut("system_ext"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700181 productOut("oem"),
182 productOut("obj/FAKE"),
183 productOut("breakpad"),
184 productOut("cache"),
185 productOut("coverage"),
186 productOut("installer"),
187 productOut("odm"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700188 productOut("odm_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700189 productOut("sysloader"),
Colin Crossf7bcd422021-04-27 19:45:25 -0700190 productOut("testcases"),
191 productOut("symbols"))
Dan Willemsenf052f782017-05-18 15:29:04 -0700192}
193
194// Since products and build variants (unfortunately) shared the same
195// PRODUCT_OUT staging directory, things can get out of sync if different
196// build configurations are built in the same tree. This function will
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000197// notice when the configuration has changed and call installClean to
Dan Willemsenf052f782017-05-18 15:29:04 -0700198// remove the files necessary to keep things consistent.
199func installCleanIfNecessary(ctx Context, config Config) {
200 configFile := config.DevicePreviousProductConfig()
201 prefix := "PREVIOUS_BUILD_CONFIG := "
202 suffix := "\n"
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000203 currentConfig := prefix + config.TargetProduct() + "-" + config.TargetBuildVariant() + suffix
Dan Willemsenf052f782017-05-18 15:29:04 -0700204
Dan Willemsene0879fc2017-08-04 15:06:27 -0700205 ensureDirectoriesExist(ctx, filepath.Dir(configFile))
206
Dan Willemsenf052f782017-05-18 15:29:04 -0700207 writeConfig := func() {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000208 err := ioutil.WriteFile(configFile, []byte(currentConfig), 0666) // a+rw
Dan Willemsenf052f782017-05-18 15:29:04 -0700209 if err != nil {
210 ctx.Fatalln("Failed to write product config:", err)
211 }
212 }
213
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000214 previousConfigBytes, err := ioutil.ReadFile(configFile)
Dan Willemsenf052f782017-05-18 15:29:04 -0700215 if err != nil {
216 if os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000217 // Just write the new config file, no old config file to worry about.
Dan Willemsenf052f782017-05-18 15:29:04 -0700218 writeConfig()
219 return
220 } else {
221 ctx.Fatalln("Failed to read previous product config:", err)
222 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000223 }
224
225 previousConfig := string(previousConfigBytes)
226 if previousConfig == currentConfig {
227 // Same config as before - nothing to clean.
Dan Willemsenf052f782017-05-18 15:29:04 -0700228 return
229 }
230
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000231 if config.Environment().IsEnvTrue("DISABLE_AUTO_INSTALLCLEAN") {
232 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 -0700233 return
234 }
235
Nan Zhang17f27672018-12-12 16:01:49 -0800236 ctx.BeginTrace(metrics.PrimaryNinja, "installclean")
Dan Willemsenf052f782017-05-18 15:29:04 -0700237 defer ctx.EndTrace()
238
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000239 previousProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(previousConfig, suffix), prefix)
240 currentProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(currentConfig, suffix), prefix)
Dan Willemsenf052f782017-05-18 15:29:04 -0700241
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000242 ctx.Printf("Build configuration changed: %q -> %q, forcing installclean\n", previousProductAndVariant, currentProductAndVariant)
Dan Willemsenf052f782017-05-18 15:29:04 -0700243
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000244 installClean(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -0700245
246 writeConfig()
247}
Dan Willemsen1e775d72020-01-03 13:40:45 -0800248
249// cleanOldFiles takes an input file (with all paths relative to basePath), and removes files from
250// the filesystem if they were removed from the input file since the last execution.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000251func cleanOldFiles(ctx Context, basePath, newFile string) {
252 newFile = filepath.Join(basePath, newFile)
253 oldFile := newFile + ".previous"
Dan Willemsen1e775d72020-01-03 13:40:45 -0800254
Cole Faust521e9512021-09-14 15:06:23 -0700255 if _, err := os.Stat(newFile); os.IsNotExist(err) {
256 // If the file doesn't exist, assume no installed files exist either
257 return
258 } else if err != nil {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000259 ctx.Fatalf("Expected %q to be readable", newFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800260 }
261
262 if _, err := os.Stat(oldFile); os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000263 if err := os.Rename(newFile, oldFile); err != nil {
264 ctx.Fatalf("Failed to rename file list (%q->%q): %v", newFile, oldFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800265 }
266 return
267 }
268
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000269 var newData, oldData []byte
270 if data, err := ioutil.ReadFile(newFile); err == nil {
271 newData = data
Dan Willemsen1e775d72020-01-03 13:40:45 -0800272 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000273 ctx.Fatalf("Failed to read list of installable files (%q): %v", newFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800274 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000275 if data, err := ioutil.ReadFile(oldFile); err == nil {
276 oldData = data
277 } else {
278 ctx.Fatalf("Failed to read list of installable files (%q): %v", oldFile, err)
279 }
280
281 // Common case: nothing has changed
282 if bytes.Equal(newData, oldData) {
283 return
284 }
285
286 var newPaths, oldPaths []string
287 newPaths = strings.Fields(string(newData))
288 oldPaths = strings.Fields(string(oldData))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800289
290 // These should be mostly sorted by make already, but better make sure Go concurs
291 sort.Strings(newPaths)
292 sort.Strings(oldPaths)
293
294 for len(oldPaths) > 0 {
295 if len(newPaths) > 0 {
296 if oldPaths[0] == newPaths[0] {
297 // Same file; continue
298 newPaths = newPaths[1:]
299 oldPaths = oldPaths[1:]
300 continue
301 } else if oldPaths[0] > newPaths[0] {
302 // New file; ignore
303 newPaths = newPaths[1:]
304 continue
305 }
306 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000307
Dan Willemsen1e775d72020-01-03 13:40:45 -0800308 // File only exists in the old list; remove if it exists
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000309 oldPath := filepath.Join(basePath, oldPaths[0])
Dan Willemsen1e775d72020-01-03 13:40:45 -0800310 oldPaths = oldPaths[1:]
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000311
312 if oldFile, err := os.Stat(oldPath); err == nil {
313 if oldFile.IsDir() {
314 if err := os.Remove(oldPath); err == nil {
315 ctx.Println("Removed directory that is no longer installed: ", oldPath)
316 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800317 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000318 ctx.Println("Failed to remove directory that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800319 ctx.Println("It's recommended to run `m installclean`")
320 }
321 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000322 // Removing a file, not a directory.
323 if err := os.Remove(oldPath); err == nil {
324 ctx.Println("Removed file that is no longer installed: ", oldPath)
325 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800326 } else if !os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000327 ctx.Fatalf("Failed to remove file that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800328 }
329 }
330 }
331 }
332
333 // Use the new list as the base for the next build
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000334 os.Rename(newFile, oldFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800335}
Dan Willemsen46459b02020-02-13 14:37:15 -0800336
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000337// cleanEmptyDirs will delete a directory if it contains no files.
338// If a deletion occurs, then it also recurses upwards to try and delete empty parent directories.
Dan Willemsen46459b02020-02-13 14:37:15 -0800339func cleanEmptyDirs(ctx Context, dir string) {
340 files, err := ioutil.ReadDir(dir)
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000341 if err != nil {
342 ctx.Println("Could not read directory while trying to clean empty dirs: ", dir)
Dan Willemsen46459b02020-02-13 14:37:15 -0800343 return
344 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000345 if len(files) > 0 {
346 // Directory is not empty.
347 return
Dan Willemsen46459b02020-02-13 14:37:15 -0800348 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000349
350 if err := os.Remove(dir); err == nil {
351 ctx.Println("Removed empty directory (may no longer be installed?): ", dir)
352 } else {
353 ctx.Fatalf("Failed to remove empty directory (which may no longer be installed?) %q: (%v)", dir, err)
354 }
355
356 // Try and delete empty parent directories too.
Dan Willemsen46459b02020-02-13 14:37:15 -0800357 cleanEmptyDirs(ctx, filepath.Dir(dir))
358}