blob: 7792333e637999b26d5b9b041bb60cc385df362f [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
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000029// Given a series of glob patterns, remove matching files and directories from the filesystem.
30// For example, "malware*" would remove all files and directories in the current directory that begin with "malware".
Dan Willemsenf052f782017-05-18 15:29:04 -070031func removeGlobs(ctx Context, globs ...string) {
32 for _, glob := range globs {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000033 // Find files and directories that match this glob pattern.
Dan Willemsenf052f782017-05-18 15:29:04 -070034 files, err := filepath.Glob(glob)
35 if err != nil {
36 // Only possible error is ErrBadPattern
37 panic(fmt.Errorf("%q: %s", glob, err))
38 }
39
40 for _, file := range files {
41 err = os.RemoveAll(file)
42 if err != nil {
43 ctx.Fatalf("Failed to remove file %q: %v", file, err)
44 }
45 }
46 }
47}
48
49// Remove everything under the out directory. Don't remove the out directory
50// itself in case it's a symlink.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000051func clean(ctx Context, config Config) {
Dan Willemsenf052f782017-05-18 15:29:04 -070052 removeGlobs(ctx, filepath.Join(config.OutDir(), "*"))
53 ctx.Println("Entire build directory removed.")
54}
55
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000056// Remove everything in the data directory.
57func dataClean(ctx Context, config Config) {
Dan Willemsenf052f782017-05-18 15:29:04 -070058 removeGlobs(ctx, filepath.Join(config.ProductOut(), "data", "*"))
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000059 ctx.Println("Entire data directory removed.")
Dan Willemsenf052f782017-05-18 15:29:04 -070060}
61
62// installClean deletes all of the installed files -- the intent is to remove
63// files that may no longer be installed, either because the user previously
64// installed them, or they were previously installed by default but no longer
65// are.
66//
67// This is faster than a full clean, since we're not deleting the
68// intermediates. Instead of recompiling, we can just copy the results.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000069func installClean(ctx Context, config Config) {
70 dataClean(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -070071
72 if hostCrossOutPath := config.hostCrossOut(); hostCrossOutPath != "" {
73 hostCrossOut := func(path string) string {
74 return filepath.Join(hostCrossOutPath, path)
75 }
76 removeGlobs(ctx,
77 hostCrossOut("bin"),
78 hostCrossOut("coverage"),
79 hostCrossOut("lib*"),
80 hostCrossOut("nativetest*"))
81 }
82
83 hostOutPath := config.HostOut()
84 hostOut := func(path string) string {
85 return filepath.Join(hostOutPath, path)
86 }
87
Colin Cross3e6f67a2020-10-09 19:11:22 -070088 hostCommonOut := func(path string) string {
89 return filepath.Join(config.hostOutRoot(), "common", path)
90 }
91
Dan Willemsenf052f782017-05-18 15:29:04 -070092 productOutPath := config.ProductOut()
93 productOut := func(path string) string {
94 return filepath.Join(productOutPath, path)
95 }
96
97 // Host bin, frameworks, and lib* are intentionally omitted, since
98 // otherwise we'd have to rebuild any generated files created with
99 // those tools.
100 removeGlobs(ctx,
Roland Levillaine5f9ee52019-09-11 14:50:08 +0100101 hostOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700102 hostOut("obj/NOTICE_FILES"),
103 hostOut("obj/PACKAGING"),
104 hostOut("coverage"),
105 hostOut("cts"),
106 hostOut("nativetest*"),
107 hostOut("sdk"),
108 hostOut("sdk_addon"),
109 hostOut("testcases"),
110 hostOut("vts"),
Dan Shi984c1292020-03-18 22:42:00 -0700111 hostOut("vts10"),
Dan Shi53f1a192019-11-26 10:02:53 -0800112 hostOut("vts-core"),
Colin Cross3e6f67a2020-10-09 19:11:22 -0700113 hostCommonOut("obj/PACKAGING"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700114 productOut("*.img"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700115 productOut("*.zip"),
Michael Bestas775e5022017-12-21 04:03:01 +0200116 productOut("*.zip.md5sum"),
Dan Willemsena18660d2017-06-01 14:23:36 -0700117 productOut("android-info.txt"),
Daniel Normanb8e7f812020-05-07 16:39:36 -0700118 productOut("misc_info.txt"),
Steven Moreland0aabb112019-08-26 11:31:33 -0700119 productOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700120 productOut("kernel"),
Yo Chiangd813f122021-01-22 00:16:47 +0800121 productOut("kernel-*"),
Jarl-Penguin10691de2021-07-20 15:31:28 +0300122 productOut("recovery_kernel"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700123 productOut("data"),
124 productOut("skin"),
125 productOut("obj/NOTICE_FILES"),
126 productOut("obj/PACKAGING"),
Tom Cherry7803a012018-08-08 13:24:32 -0700127 productOut("ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800128 productOut("debug_ramdisk"),
Petri Gyntherac229562021-03-02 23:44:02 -0800129 productOut("vendor_ramdisk"),
Will McVicker4cee6252020-03-19 11:57:11 -0700130 productOut("vendor_debug_ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800131 productOut("test_harness_ramdisk"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700132 productOut("recovery"),
133 productOut("root"),
134 productOut("system"),
135 productOut("system_other"),
136 productOut("vendor"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700137 productOut("vendor_dlkm"),
Jaekyun Seokf6307cc2018-05-16 12:25:41 +0900138 productOut("product"),
Justin Yund5f6c822019-06-25 16:47:17 +0900139 productOut("system_ext"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700140 productOut("oem"),
141 productOut("obj/FAKE"),
142 productOut("breakpad"),
143 productOut("cache"),
144 productOut("coverage"),
145 productOut("installer"),
146 productOut("odm"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700147 productOut("odm_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700148 productOut("sysloader"),
Colin Crossf7bcd422021-04-27 19:45:25 -0700149 productOut("testcases"),
LuK1337c5a1a8a2020-11-13 15:11:27 +0100150 productOut("symbols"),
151 productOut("install"))
Dan Willemsenf052f782017-05-18 15:29:04 -0700152}
153
154// Since products and build variants (unfortunately) shared the same
155// PRODUCT_OUT staging directory, things can get out of sync if different
156// build configurations are built in the same tree. This function will
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000157// notice when the configuration has changed and call installClean to
Dan Willemsenf052f782017-05-18 15:29:04 -0700158// remove the files necessary to keep things consistent.
159func installCleanIfNecessary(ctx Context, config Config) {
160 configFile := config.DevicePreviousProductConfig()
161 prefix := "PREVIOUS_BUILD_CONFIG := "
162 suffix := "\n"
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000163 currentConfig := prefix + config.TargetProduct() + "-" + config.TargetBuildVariant() + suffix
Dan Willemsenf052f782017-05-18 15:29:04 -0700164
Dan Willemsene0879fc2017-08-04 15:06:27 -0700165 ensureDirectoriesExist(ctx, filepath.Dir(configFile))
166
Dan Willemsenf052f782017-05-18 15:29:04 -0700167 writeConfig := func() {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000168 err := ioutil.WriteFile(configFile, []byte(currentConfig), 0666) // a+rw
Dan Willemsenf052f782017-05-18 15:29:04 -0700169 if err != nil {
170 ctx.Fatalln("Failed to write product config:", err)
171 }
172 }
173
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000174 previousConfigBytes, err := ioutil.ReadFile(configFile)
Dan Willemsenf052f782017-05-18 15:29:04 -0700175 if err != nil {
176 if os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000177 // Just write the new config file, no old config file to worry about.
Dan Willemsenf052f782017-05-18 15:29:04 -0700178 writeConfig()
179 return
180 } else {
181 ctx.Fatalln("Failed to read previous product config:", err)
182 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000183 }
184
185 previousConfig := string(previousConfigBytes)
186 if previousConfig == currentConfig {
187 // Same config as before - nothing to clean.
Dan Willemsenf052f782017-05-18 15:29:04 -0700188 return
189 }
190
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000191 if config.Environment().IsEnvTrue("DISABLE_AUTO_INSTALLCLEAN") {
192 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 -0700193 return
194 }
195
Nan Zhang17f27672018-12-12 16:01:49 -0800196 ctx.BeginTrace(metrics.PrimaryNinja, "installclean")
Dan Willemsenf052f782017-05-18 15:29:04 -0700197 defer ctx.EndTrace()
198
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000199 previousProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(previousConfig, suffix), prefix)
200 currentProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(currentConfig, suffix), prefix)
Dan Willemsenf052f782017-05-18 15:29:04 -0700201
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000202 ctx.Printf("Build configuration changed: %q -> %q, forcing installclean\n", previousProductAndVariant, currentProductAndVariant)
Dan Willemsenf052f782017-05-18 15:29:04 -0700203
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000204 installClean(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -0700205
206 writeConfig()
207}
Dan Willemsen1e775d72020-01-03 13:40:45 -0800208
209// cleanOldFiles takes an input file (with all paths relative to basePath), and removes files from
210// the filesystem if they were removed from the input file since the last execution.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000211func cleanOldFiles(ctx Context, basePath, newFile string) {
212 newFile = filepath.Join(basePath, newFile)
213 oldFile := newFile + ".previous"
Dan Willemsen1e775d72020-01-03 13:40:45 -0800214
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000215 if _, err := os.Stat(newFile); err != nil {
216 ctx.Fatalf("Expected %q to be readable", newFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800217 }
218
219 if _, err := os.Stat(oldFile); os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000220 if err := os.Rename(newFile, oldFile); err != nil {
221 ctx.Fatalf("Failed to rename file list (%q->%q): %v", newFile, oldFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800222 }
223 return
224 }
225
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000226 var newData, oldData []byte
227 if data, err := ioutil.ReadFile(newFile); err == nil {
228 newData = data
Dan Willemsen1e775d72020-01-03 13:40:45 -0800229 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000230 ctx.Fatalf("Failed to read list of installable files (%q): %v", newFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800231 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000232 if data, err := ioutil.ReadFile(oldFile); err == nil {
233 oldData = data
234 } else {
235 ctx.Fatalf("Failed to read list of installable files (%q): %v", oldFile, err)
236 }
237
238 // Common case: nothing has changed
239 if bytes.Equal(newData, oldData) {
240 return
241 }
242
243 var newPaths, oldPaths []string
244 newPaths = strings.Fields(string(newData))
245 oldPaths = strings.Fields(string(oldData))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800246
247 // These should be mostly sorted by make already, but better make sure Go concurs
248 sort.Strings(newPaths)
249 sort.Strings(oldPaths)
250
251 for len(oldPaths) > 0 {
252 if len(newPaths) > 0 {
253 if oldPaths[0] == newPaths[0] {
254 // Same file; continue
255 newPaths = newPaths[1:]
256 oldPaths = oldPaths[1:]
257 continue
258 } else if oldPaths[0] > newPaths[0] {
259 // New file; ignore
260 newPaths = newPaths[1:]
261 continue
262 }
263 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000264
Dan Willemsen1e775d72020-01-03 13:40:45 -0800265 // File only exists in the old list; remove if it exists
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000266 oldPath := filepath.Join(basePath, oldPaths[0])
Dan Willemsen1e775d72020-01-03 13:40:45 -0800267 oldPaths = oldPaths[1:]
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000268
269 if oldFile, err := os.Stat(oldPath); err == nil {
270 if oldFile.IsDir() {
271 if err := os.Remove(oldPath); err == nil {
272 ctx.Println("Removed directory that is no longer installed: ", oldPath)
273 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800274 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000275 ctx.Println("Failed to remove directory that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800276 ctx.Println("It's recommended to run `m installclean`")
277 }
278 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000279 // Removing a file, not a directory.
280 if err := os.Remove(oldPath); err == nil {
281 ctx.Println("Removed file that is no longer installed: ", oldPath)
282 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800283 } else if !os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000284 ctx.Fatalf("Failed to remove file that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800285 }
286 }
287 }
288 }
289
290 // Use the new list as the base for the next build
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000291 os.Rename(newFile, oldFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800292}
Dan Willemsen46459b02020-02-13 14:37:15 -0800293
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000294// cleanEmptyDirs will delete a directory if it contains no files.
295// If a deletion occurs, then it also recurses upwards to try and delete empty parent directories.
Dan Willemsen46459b02020-02-13 14:37:15 -0800296func cleanEmptyDirs(ctx Context, dir string) {
297 files, err := ioutil.ReadDir(dir)
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000298 if err != nil {
299 ctx.Println("Could not read directory while trying to clean empty dirs: ", dir)
Dan Willemsen46459b02020-02-13 14:37:15 -0800300 return
301 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000302 if len(files) > 0 {
303 // Directory is not empty.
304 return
Dan Willemsen46459b02020-02-13 14:37:15 -0800305 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000306
307 if err := os.Remove(dir); err == nil {
308 ctx.Println("Removed empty directory (may no longer be installed?): ", dir)
309 } else {
310 ctx.Fatalf("Failed to remove empty directory (which may no longer be installed?) %q: (%v)", dir, err)
311 }
312
313 // Try and delete empty parent directories too.
Dan Willemsen46459b02020-02-13 14:37:15 -0800314 cleanEmptyDirs(ctx, filepath.Dir(dir))
315}
Alberto97e3a44232018-05-05 22:01:02 +0200316
317// Remove everything relevant for a clean ota package
318func deviceClean(ctx Context, config Config, what int) {
Harsh Shandilya6a2a5132019-05-12 05:48:29 +0530319 removeGlobs(ctx, config.ProductOut())
Alberto97e3a44232018-05-05 22:01:02 +0200320}