blob: 532cb538ed4786c9466366b735a60ae99dbef4a1 [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
Rupert Shuttleworth755ceb02021-08-11 09:20:27 -040049// Based on https://stackoverflow.com/questions/28969455/how-to-properly-instantiate-os-filemode
50// Because Go doesn't provide a nice way to set bits on a filemode
51const (
52 FILEMODE_READ = 04
53 FILEMODE_WRITE = 02
54 FILEMODE_EXECUTE = 01
55 FILEMODE_USER_SHIFT = 6
56 FILEMODE_USER_READ = FILEMODE_READ << FILEMODE_USER_SHIFT
57 FILEMODE_USER_WRITE = FILEMODE_WRITE << FILEMODE_USER_SHIFT
58 FILEMODE_USER_EXECUTE = FILEMODE_EXECUTE << FILEMODE_USER_SHIFT
59)
60
Dan Willemsenf052f782017-05-18 15:29:04 -070061// Remove everything under the out directory. Don't remove the out directory
62// itself in case it's a symlink.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000063func clean(ctx Context, config Config) {
Dan Willemsenf052f782017-05-18 15:29:04 -070064 removeGlobs(ctx, filepath.Join(config.OutDir(), "*"))
65 ctx.Println("Entire build directory removed.")
66}
67
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000068// Remove everything in the data directory.
69func dataClean(ctx Context, config Config) {
Dan Willemsenf052f782017-05-18 15:29:04 -070070 removeGlobs(ctx, filepath.Join(config.ProductOut(), "data", "*"))
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000071 ctx.Println("Entire data directory removed.")
Dan Willemsenf052f782017-05-18 15:29:04 -070072}
73
74// installClean deletes all of the installed files -- the intent is to remove
75// files that may no longer be installed, either because the user previously
76// installed them, or they were previously installed by default but no longer
77// are.
78//
79// This is faster than a full clean, since we're not deleting the
80// intermediates. Instead of recompiling, we can just copy the results.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +000081func installClean(ctx Context, config Config) {
82 dataClean(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -070083
84 if hostCrossOutPath := config.hostCrossOut(); hostCrossOutPath != "" {
85 hostCrossOut := func(path string) string {
86 return filepath.Join(hostCrossOutPath, path)
87 }
88 removeGlobs(ctx,
89 hostCrossOut("bin"),
90 hostCrossOut("coverage"),
91 hostCrossOut("lib*"),
92 hostCrossOut("nativetest*"))
93 }
94
95 hostOutPath := config.HostOut()
96 hostOut := func(path string) string {
97 return filepath.Join(hostOutPath, path)
98 }
99
Colin Cross3e6f67a2020-10-09 19:11:22 -0700100 hostCommonOut := func(path string) string {
101 return filepath.Join(config.hostOutRoot(), "common", path)
102 }
103
Dan Willemsenf052f782017-05-18 15:29:04 -0700104 productOutPath := config.ProductOut()
105 productOut := func(path string) string {
106 return filepath.Join(productOutPath, path)
107 }
108
109 // Host bin, frameworks, and lib* are intentionally omitted, since
110 // otherwise we'd have to rebuild any generated files created with
111 // those tools.
112 removeGlobs(ctx,
Roland Levillaine5f9ee52019-09-11 14:50:08 +0100113 hostOut("apex"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700114 hostOut("obj/NOTICE_FILES"),
115 hostOut("obj/PACKAGING"),
116 hostOut("coverage"),
117 hostOut("cts"),
118 hostOut("nativetest*"),
119 hostOut("sdk"),
120 hostOut("sdk_addon"),
121 hostOut("testcases"),
122 hostOut("vts"),
Dan Shi984c1292020-03-18 22:42:00 -0700123 hostOut("vts10"),
Dan Shi53f1a192019-11-26 10:02:53 -0800124 hostOut("vts-core"),
Colin Cross3e6f67a2020-10-09 19:11:22 -0700125 hostCommonOut("obj/PACKAGING"),
OdSazib9f24f752021-10-22 13:20:04 +0530126 productOut("*.cpio"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700127 productOut("*.img"),
OdSazib9f24f752021-10-22 13:20:04 +0530128 productOut("*.json"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700129 productOut("*.zip"),
Michael Bestasb42e2922017-12-21 04:03:01 +0200130 productOut("*.zip.md5sum"),
Dan Willemsena18660d2017-06-01 14:23:36 -0700131 productOut("android-info.txt"),
Daniel Normanb8e7f812020-05-07 16:39:36 -0700132 productOut("misc_info.txt"),
Steven Moreland0aabb112019-08-26 11:31:33 -0700133 productOut("apex"),
OdSazib9f24f752021-10-22 13:20:04 +0530134 productOut("build_fingerprint.txt"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700135 productOut("kernel"),
Yo Chiangd813f122021-01-22 00:16:47 +0800136 productOut("kernel-*"),
Jarl-Penguinaa068b82021-07-20 15:31:28 +0300137 productOut("recovery_kernel"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700138 productOut("data"),
139 productOut("skin"),
140 productOut("obj/NOTICE_FILES"),
141 productOut("obj/PACKAGING"),
Tom Cherry7803a012018-08-08 13:24:32 -0700142 productOut("ramdisk"),
Kelvin Zhangdc14fbb2023-06-02 15:54:59 -0700143 productOut("ramdisk_16k"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800144 productOut("debug_ramdisk"),
Petri Gyntherac229562021-03-02 23:44:02 -0800145 productOut("vendor_ramdisk"),
Will McVicker4cee6252020-03-19 11:57:11 -0700146 productOut("vendor_debug_ramdisk"),
Yi-Yo Chiangda447952022-07-20 19:17:38 +0800147 productOut("vendor_kernel_ramdisk"),
Bowgo Tsai5145c2c2019-10-08 18:12:37 +0800148 productOut("test_harness_ramdisk"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700149 productOut("recovery"),
150 productOut("root"),
151 productOut("system"),
Ramji Jiyanif0afc952022-02-04 23:03:53 +0000152 productOut("system_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700153 productOut("system_other"),
154 productOut("vendor"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700155 productOut("vendor_dlkm"),
Jaekyun Seokf6307cc2018-05-16 12:25:41 +0900156 productOut("product"),
Justin Yund5f6c822019-06-25 16:47:17 +0900157 productOut("system_ext"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700158 productOut("oem"),
159 productOut("obj/FAKE"),
160 productOut("breakpad"),
161 productOut("cache"),
162 productOut("coverage"),
163 productOut("installer"),
164 productOut("odm"),
Colin Crossce4c7cd2020-10-14 11:29:16 -0700165 productOut("odm_dlkm"),
Dan Willemsenf052f782017-05-18 15:29:04 -0700166 productOut("sysloader"),
Colin Crossf7bcd422021-04-27 19:45:25 -0700167 productOut("testcases"),
LuK1337413e36c2020-11-13 15:11:27 +0100168 productOut("symbols"),
169 productOut("install"))
Dan Willemsenf052f782017-05-18 15:29:04 -0700170}
171
172// Since products and build variants (unfortunately) shared the same
173// PRODUCT_OUT staging directory, things can get out of sync if different
174// build configurations are built in the same tree. This function will
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000175// notice when the configuration has changed and call installClean to
Dan Willemsenf052f782017-05-18 15:29:04 -0700176// remove the files necessary to keep things consistent.
177func installCleanIfNecessary(ctx Context, config Config) {
178 configFile := config.DevicePreviousProductConfig()
179 prefix := "PREVIOUS_BUILD_CONFIG := "
180 suffix := "\n"
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000181 currentConfig := prefix + config.TargetProduct() + "-" + config.TargetBuildVariant() + suffix
Dan Willemsenf052f782017-05-18 15:29:04 -0700182
Dan Willemsene0879fc2017-08-04 15:06:27 -0700183 ensureDirectoriesExist(ctx, filepath.Dir(configFile))
184
Dan Willemsenf052f782017-05-18 15:29:04 -0700185 writeConfig := func() {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000186 err := ioutil.WriteFile(configFile, []byte(currentConfig), 0666) // a+rw
Dan Willemsenf052f782017-05-18 15:29:04 -0700187 if err != nil {
188 ctx.Fatalln("Failed to write product config:", err)
189 }
190 }
191
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000192 previousConfigBytes, err := ioutil.ReadFile(configFile)
Dan Willemsenf052f782017-05-18 15:29:04 -0700193 if err != nil {
194 if os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000195 // Just write the new config file, no old config file to worry about.
Dan Willemsenf052f782017-05-18 15:29:04 -0700196 writeConfig()
197 return
198 } else {
199 ctx.Fatalln("Failed to read previous product config:", err)
200 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000201 }
202
203 previousConfig := string(previousConfigBytes)
204 if previousConfig == currentConfig {
205 // Same config as before - nothing to clean.
Dan Willemsenf052f782017-05-18 15:29:04 -0700206 return
207 }
208
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000209 if config.Environment().IsEnvTrue("DISABLE_AUTO_INSTALLCLEAN") {
210 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 -0700211 return
212 }
213
Nan Zhang17f27672018-12-12 16:01:49 -0800214 ctx.BeginTrace(metrics.PrimaryNinja, "installclean")
Dan Willemsenf052f782017-05-18 15:29:04 -0700215 defer ctx.EndTrace()
216
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000217 previousProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(previousConfig, suffix), prefix)
218 currentProductAndVariant := strings.TrimPrefix(strings.TrimSuffix(currentConfig, suffix), prefix)
Dan Willemsenf052f782017-05-18 15:29:04 -0700219
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000220 ctx.Printf("Build configuration changed: %q -> %q, forcing installclean\n", previousProductAndVariant, currentProductAndVariant)
Dan Willemsenf052f782017-05-18 15:29:04 -0700221
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000222 installClean(ctx, config)
Dan Willemsenf052f782017-05-18 15:29:04 -0700223
224 writeConfig()
225}
Dan Willemsen1e775d72020-01-03 13:40:45 -0800226
227// cleanOldFiles takes an input file (with all paths relative to basePath), and removes files from
228// the filesystem if they were removed from the input file since the last execution.
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000229func cleanOldFiles(ctx Context, basePath, newFile string) {
230 newFile = filepath.Join(basePath, newFile)
231 oldFile := newFile + ".previous"
Dan Willemsen1e775d72020-01-03 13:40:45 -0800232
Cole Faust521e9512021-09-14 15:06:23 -0700233 if _, err := os.Stat(newFile); os.IsNotExist(err) {
234 // If the file doesn't exist, assume no installed files exist either
235 return
236 } else if err != nil {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000237 ctx.Fatalf("Expected %q to be readable", newFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800238 }
239
240 if _, err := os.Stat(oldFile); os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000241 if err := os.Rename(newFile, oldFile); err != nil {
242 ctx.Fatalf("Failed to rename file list (%q->%q): %v", newFile, oldFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800243 }
244 return
245 }
246
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000247 var newData, oldData []byte
248 if data, err := ioutil.ReadFile(newFile); err == nil {
249 newData = data
Dan Willemsen1e775d72020-01-03 13:40:45 -0800250 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000251 ctx.Fatalf("Failed to read list of installable files (%q): %v", newFile, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800252 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000253 if data, err := ioutil.ReadFile(oldFile); err == nil {
254 oldData = data
255 } else {
256 ctx.Fatalf("Failed to read list of installable files (%q): %v", oldFile, err)
257 }
258
259 // Common case: nothing has changed
260 if bytes.Equal(newData, oldData) {
261 return
262 }
263
264 var newPaths, oldPaths []string
265 newPaths = strings.Fields(string(newData))
266 oldPaths = strings.Fields(string(oldData))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800267
268 // These should be mostly sorted by make already, but better make sure Go concurs
269 sort.Strings(newPaths)
270 sort.Strings(oldPaths)
271
272 for len(oldPaths) > 0 {
273 if len(newPaths) > 0 {
274 if oldPaths[0] == newPaths[0] {
275 // Same file; continue
276 newPaths = newPaths[1:]
277 oldPaths = oldPaths[1:]
278 continue
279 } else if oldPaths[0] > newPaths[0] {
280 // New file; ignore
281 newPaths = newPaths[1:]
282 continue
283 }
284 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000285
Dan Willemsen1e775d72020-01-03 13:40:45 -0800286 // File only exists in the old list; remove if it exists
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000287 oldPath := filepath.Join(basePath, oldPaths[0])
Dan Willemsen1e775d72020-01-03 13:40:45 -0800288 oldPaths = oldPaths[1:]
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000289
290 if oldFile, err := os.Stat(oldPath); err == nil {
291 if oldFile.IsDir() {
292 if err := os.Remove(oldPath); err == nil {
293 ctx.Println("Removed directory that is no longer installed: ", oldPath)
294 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800295 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000296 ctx.Println("Failed to remove directory that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800297 ctx.Println("It's recommended to run `m installclean`")
298 }
299 } else {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000300 // Removing a file, not a directory.
301 if err := os.Remove(oldPath); err == nil {
302 ctx.Println("Removed file that is no longer installed: ", oldPath)
303 cleanEmptyDirs(ctx, filepath.Dir(oldPath))
Dan Willemsen1e775d72020-01-03 13:40:45 -0800304 } else if !os.IsNotExist(err) {
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000305 ctx.Fatalf("Failed to remove file that is no longer installed (%q): %v", oldPath, err)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800306 }
307 }
308 }
309 }
310
311 // Use the new list as the base for the next build
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000312 os.Rename(newFile, oldFile)
Dan Willemsen1e775d72020-01-03 13:40:45 -0800313}
Dan Willemsen46459b02020-02-13 14:37:15 -0800314
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000315// cleanEmptyDirs will delete a directory if it contains no files.
316// If a deletion occurs, then it also recurses upwards to try and delete empty parent directories.
Dan Willemsen46459b02020-02-13 14:37:15 -0800317func cleanEmptyDirs(ctx Context, dir string) {
318 files, err := ioutil.ReadDir(dir)
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000319 if err != nil {
320 ctx.Println("Could not read directory while trying to clean empty dirs: ", dir)
Dan Willemsen46459b02020-02-13 14:37:15 -0800321 return
322 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000323 if len(files) > 0 {
324 // Directory is not empty.
325 return
Dan Willemsen46459b02020-02-13 14:37:15 -0800326 }
Rupert Shuttleworth1f304e62020-11-24 14:13:41 +0000327
328 if err := os.Remove(dir); err == nil {
329 ctx.Println("Removed empty directory (may no longer be installed?): ", dir)
330 } else {
331 ctx.Fatalf("Failed to remove empty directory (which may no longer be installed?) %q: (%v)", dir, err)
332 }
333
334 // Try and delete empty parent directories too.
Dan Willemsen46459b02020-02-13 14:37:15 -0800335 cleanEmptyDirs(ctx, filepath.Dir(dir))
336}
Alberto97b1a15ad2018-05-05 22:01:02 +0200337
338// Remove everything relevant for a clean ota package
339func deviceClean(ctx Context, config Config, what int) {
Harsh Shandilya260a3bf2019-05-12 05:48:29 +0530340 removeGlobs(ctx, config.ProductOut())
Alberto97b1a15ad2018-05-05 22:01:02 +0200341}