blob: 1c80cff31ff5612fd8c1dea0bcb7104f2f06b777 [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"),
Ramji Jiyanif0afc952022-02-04 23:03:53 +0000174 productOut("system_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700175 productOut("system_other"),
176 productOut("vendor"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700177 productOut("vendor_dlkm"),
Jaekyun Seokf6307cc2018-05-16 12:25:41 +0900178 productOut("product"),
Justin Yund5f6c822019-06-25 16:47:17 +0900179 productOut("system_ext"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700180 productOut("oem"),
181 productOut("obj/FAKE"),
182 productOut("breakpad"),
183 productOut("cache"),
184 productOut("coverage"),
185 productOut("installer"),
186 productOut("odm"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700187 productOut("odm_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700188 productOut("sysloader"),
Colin Crossf7bcd422021-04-27 19:45:25 -0700189 productOut("testcases"),
190 productOut("symbols"))
Dan Willemsenf052f782017-05-18 15:29:04 -0700191}
192
193// Since products and build variants (unfortunately) shared the same
194// PRODUCT_OUT staging directory, things can get out of sync if different
195// build configurations are built in the same tree. This function will
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000196// notice when the configuration has changed and call installClean to
Dan Willemsenf052f782017-05-18 15:29:04 -0700197// remove the files necessary to keep things consistent.
198func installCleanIfNecessary(ctx Context, config Config) {
199 configFile := config.DevicePreviousProductConfig()
200 prefix := "PREVIOUS_BUILD_CONFIG := "
201 suffix := "\n"
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000202 currentConfig := prefix + config.TargetProduct() + "-" + config.TargetBuildVariant() + suffix
Dan Willemsenf052f782017-05-18 15:29:04 -0700203
Dan Willemsene0879fc2017-08-04 15:06:27 -0700204 ensureDirectoriesExist(ctx, filepath.Dir(configFile))
205
Dan Willemsenf052f782017-05-18 15:29:04 -0700206 writeConfig := func() {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000207 err := ioutil.WriteFile(configFile, []byte(currentConfig), 0666) // a+rw
Dan Willemsenf052f782017-05-18 15:29:04 -0700208 if err != nil {
209 ctx.Fatalln("Failed to write product config:", err)
210 }
211 }
212
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000213 previousConfigBytes, err := ioutil.ReadFile(configFile)
Dan Willemsenf052f782017-05-18 15:29:04 -0700214 if err != nil {
215 if os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000216 // Just write the new config file, no old config file to worry about.
Dan Willemsenf052f782017-05-18 15:29:04 -0700217 writeConfig()
218 return
219 } else {
220 ctx.Fatalln("Failed to read previous product config:", err)
221 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000222 }
223
224 previousConfig := string(previousConfigBytes)
225 if previousConfig == currentConfig {
226 // Same config as before - nothing to clean.
Dan Willemsenf052f782017-05-18 15:29:04 -0700227 return
228 }
229
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000230 if config.Environment().IsEnvTrue("DISABLE_AUTO_INSTALLCLEAN") {
231 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 -0700232 return
233 }
234
Nan Zhang17f27672018-12-12 16:01:49 -0800235 ctx.BeginTrace(metrics.PrimaryNinja, "installclean")
Dan Willemsenf052f782017-05-18 15:29:04 -0700236 defer ctx.EndTrace()
237
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000238 previousProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(previousConfig, suffix), prefix)
239 currentProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(currentConfig, suffix), prefix)
Dan Willemsenf052f782017-05-18 15:29:04 -0700240
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000241 ctx.Printf("Build configuration changed: %q -> %q, forcing installclean\n", previousProductAndVariant, currentProductAndVariant)
Dan Willemsenf052f782017-05-18 15:29:04 -0700242
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000243 installClean(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -0700244
245 writeConfig()
246}
Dan Willemsen1e775d72020-01-03 13:40:45 -0800247
248// cleanOldFiles takes an input file (with all paths relative to basePath), and removes files from
249// the filesystem if they were removed from the input file since the last execution.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000250func cleanOldFiles(ctx Context, basePath, newFile string) {
251 newFile = filepath.Join(basePath, newFile)
252 oldFile := newFile + ".previous"
Dan Willemsen1e775d72020-01-03 13:40:45 -0800253
Cole Faust521e9512021-09-14 15:06:23 -0700254 if _, err := os.Stat(newFile); os.IsNotExist(err) {
255 // If the file doesn't exist, assume no installed files exist either
256 return
257 } else if err != nil {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000258 ctx.Fatalf("Expected %q to be readable", newFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800259 }
260
261 if _, err := os.Stat(oldFile); os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000262 if err := os.Rename(newFile, oldFile); err != nil {
263 ctx.Fatalf("Failed to rename file list (%q->%q): %v", newFile, oldFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800264 }
265 return
266 }
267
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000268 var newData, oldData []byte
269 if data, err := ioutil.ReadFile(newFile); err == nil {
270 newData = data
Dan Willemsen1e775d72020-01-03 13:40:45 -0800271 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000272 ctx.Fatalf("Failed to read list of installable files (%q): %v", newFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800273 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000274 if data, err := ioutil.ReadFile(oldFile); err == nil {
275 oldData = data
276 } else {
277 ctx.Fatalf("Failed to read list of installable files (%q): %v", oldFile, err)
278 }
279
280 // Common case: nothing has changed
281 if bytes.Equal(newData, oldData) {
282 return
283 }
284
285 var newPaths, oldPaths []string
286 newPaths = strings.Fields(string(newData))
287 oldPaths = strings.Fields(string(oldData))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800288
289 // These should be mostly sorted by make already, but better make sure Go concurs
290 sort.Strings(newPaths)
291 sort.Strings(oldPaths)
292
293 for len(oldPaths) > 0 {
294 if len(newPaths) > 0 {
295 if oldPaths[0] == newPaths[0] {
296 // Same file; continue
297 newPaths = newPaths[1:]
298 oldPaths = oldPaths[1:]
299 continue
300 } else if oldPaths[0] > newPaths[0] {
301 // New file; ignore
302 newPaths = newPaths[1:]
303 continue
304 }
305 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000306
Dan Willemsen1e775d72020-01-03 13:40:45 -0800307 // File only exists in the old list; remove if it exists
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000308 oldPath := filepath.Join(basePath, oldPaths[0])
Dan Willemsen1e775d72020-01-03 13:40:45 -0800309 oldPaths = oldPaths[1:]
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000310
311 if oldFile, err := os.Stat(oldPath); err == nil {
312 if oldFile.IsDir() {
313 if err := os.Remove(oldPath); err == nil {
314 ctx.Println("Removed directory that is no longer installed: ", oldPath)
315 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800316 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000317 ctx.Println("Failed to remove directory that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800318 ctx.Println("It's recommended to run `m installclean`")
319 }
320 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000321 // Removing a file, not a directory.
322 if err := os.Remove(oldPath); err == nil {
323 ctx.Println("Removed file that is no longer installed: ", oldPath)
324 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800325 } else if !os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000326 ctx.Fatalf("Failed to remove file that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800327 }
328 }
329 }
330 }
331
332 // Use the new list as the base for the next build
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000333 os.Rename(newFile, oldFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800334}
Dan Willemsen46459b02020-02-13 14:37:15 -0800335
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000336// cleanEmptyDirs will delete a directory if it contains no files.
337// If a deletion occurs, then it also recurses upwards to try and delete empty parent directories.
Dan Willemsen46459b02020-02-13 14:37:15 -0800338func cleanEmptyDirs(ctx Context, dir string) {
339 files, err := ioutil.ReadDir(dir)
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000340 if err != nil {
341 ctx.Println("Could not read directory while trying to clean empty dirs: ", dir)
Dan Willemsen46459b02020-02-13 14:37:15 -0800342 return
343 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000344 if len(files) > 0 {
345 // Directory is not empty.
346 return
Dan Willemsen46459b02020-02-13 14:37:15 -0800347 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000348
349 if err := os.Remove(dir); err == nil {
350 ctx.Println("Removed empty directory (may no longer be installed?): ", dir)
351 } else {
352 ctx.Fatalf("Failed to remove empty directory (which may no longer be installed?) %q: (%v)", dir, err)
353 }
354
355 // Try and delete empty parent directories too.
Dan Willemsen46459b02020-02-13 14:37:15 -0800356 cleanEmptyDirs(ctx, filepath.Dir(dir))
357}