blob: d9b4e86b7e0c6d036a674cb79507c177ed417c97 [file] [log] [blame]
Sasha Smundakb051c4e2020-11-05 20:45:07 -08001// Copyright 2021 Google LLC
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
15// The application to convert product configuration makefiles to Starlark.
16// Converts either given list of files (and optionally the dependent files
17// of the same kind), or all all product configuration makefiles in the
18// given source tree.
19// Previous version of a converted file can be backed up.
20// Optionally prints detailed statistics at the end.
21package main
22
23import (
Sasha Smundak6609ba72021-07-22 18:32:56 -070024 "bufio"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080025 "flag"
26 "fmt"
27 "io/ioutil"
28 "os"
Sasha Smundak6609ba72021-07-22 18:32:56 -070029 "os/exec"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080030 "path/filepath"
31 "regexp"
32 "runtime/debug"
Sasha Smundak38802792021-08-01 14:38:07 -070033 "runtime/pprof"
Sasha Smundakb051c4e2020-11-05 20:45:07 -080034 "sort"
35 "strings"
36 "time"
37
38 "android/soong/androidmk/parser"
39 "android/soong/mk2rbc"
40)
41
42var (
43 rootDir = flag.String("root", ".", "the value of // for load paths")
44 // TODO(asmundak): remove this option once there is a consensus on suffix
45 suffix = flag.String("suffix", ".rbc", "generated files' suffix")
46 dryRun = flag.Bool("dry_run", false, "dry run")
47 recurse = flag.Bool("convert_dependents", false, "convert all dependent files")
48 mode = flag.String("mode", "", `"backup" to back up existing files, "write" to overwrite them`)
Sasha Smundakb051c4e2020-11-05 20:45:07 -080049 errstat = flag.Bool("error_stat", false, "print error statistics")
50 traceVar = flag.String("trace", "", "comma-separated list of variables to trace")
51 // TODO(asmundak): this option is for debugging
52 allInSource = flag.Bool("all", false, "convert all product config makefiles in the tree under //")
53 outputTop = flag.String("outdir", "", "write output files into this directory hierarchy")
Cole Faust6ed7cb42021-10-07 17:08:46 -070054 launcher = flag.String("launcher", "", "generated launcher path.")
55 boardlauncher = flag.String("boardlauncher", "", "generated board configuration launcher path.")
Sasha Smundakb051c4e2020-11-05 20:45:07 -080056 printProductConfigMap = flag.Bool("print_product_config_map", false, "print product config map and exit")
Sasha Smundak38802792021-08-01 14:38:07 -070057 cpuProfile = flag.String("cpu_profile", "", "write cpu profile to file")
Sasha Smundakb051c4e2020-11-05 20:45:07 -080058 traceCalls = flag.Bool("trace_calls", false, "trace function calls")
Cole Faust6ed7cb42021-10-07 17:08:46 -070059 inputVariables = flag.String("input_variables", "", "starlark file containing product config and global variables")
Sasha Smundakb051c4e2020-11-05 20:45:07 -080060)
61
62func init() {
Joe Onoratob4638c12021-10-27 15:47:06 -070063 // Simplistic flag aliasing: works, but the usage string is ugly and
Sasha Smundakb051c4e2020-11-05 20:45:07 -080064 // both flag and its alias can be present on the command line
65 flagAlias := func(target string, alias string) {
66 if f := flag.Lookup(target); f != nil {
67 flag.Var(f.Value, alias, "alias for --"+f.Name)
68 return
69 }
70 quit("cannot alias unknown flag " + target)
71 }
72 flagAlias("suffix", "s")
73 flagAlias("root", "d")
74 flagAlias("dry_run", "n")
75 flagAlias("convert_dependents", "r")
Sasha Smundakb051c4e2020-11-05 20:45:07 -080076 flagAlias("error_stat", "e")
77}
78
79var backupSuffix string
80var tracedVariables []string
Sasha Smundak7d934b92021-11-10 12:20:01 -080081var errorLogger = errorSink{data: make(map[string]datum)}
Sasha Smundak6609ba72021-07-22 18:32:56 -070082var makefileFinder = &LinuxMakefileFinder{}
Sasha Smundakb051c4e2020-11-05 20:45:07 -080083
84func main() {
85 flag.Usage = func() {
86 cmd := filepath.Base(os.Args[0])
87 fmt.Fprintf(flag.CommandLine.Output(),
Cole Faust6ed7cb42021-10-07 17:08:46 -070088 "Usage: %[1]s flags file...\n", cmd)
Sasha Smundakb051c4e2020-11-05 20:45:07 -080089 flag.PrintDefaults()
90 }
91 flag.Parse()
92
93 // Delouse
94 if *suffix == ".mk" {
95 quit("cannot use .mk as generated file suffix")
96 }
97 if *suffix == "" {
98 quit("suffix cannot be empty")
99 }
100 if *outputTop != "" {
101 if err := os.MkdirAll(*outputTop, os.ModeDir+os.ModePerm); err != nil {
102 quit(err)
103 }
104 s, err := filepath.Abs(*outputTop)
105 if err != nil {
106 quit(err)
107 }
108 *outputTop = s
109 }
110 if *allInSource && len(flag.Args()) > 0 {
111 quit("file list cannot be specified when -all is present")
112 }
113 if *allInSource && *launcher != "" {
114 quit("--all and --launcher are mutually exclusive")
115 }
116
117 // Flag-driven adjustments
118 if (*suffix)[0] != '.' {
119 *suffix = "." + *suffix
120 }
121 if *mode == "backup" {
122 backupSuffix = time.Now().Format("20060102150405")
123 }
124 if *traceVar != "" {
125 tracedVariables = strings.Split(*traceVar, ",")
126 }
127
Sasha Smundak38802792021-08-01 14:38:07 -0700128 if *cpuProfile != "" {
129 f, err := os.Create(*cpuProfile)
130 if err != nil {
131 quit(err)
132 }
133 pprof.StartCPUProfile(f)
134 defer pprof.StopCPUProfile()
135 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800136 // Find out global variables
137 getConfigVariables()
138 getSoongVariables()
139
140 if *printProductConfigMap {
141 productConfigMap := buildProductConfigMap()
142 var products []string
143 for p := range productConfigMap {
144 products = append(products, p)
145 }
146 sort.Strings(products)
147 for _, p := range products {
148 fmt.Println(p, productConfigMap[p])
149 }
150 os.Exit(0)
151 }
Sasha Smundakb2ac8592021-07-26 09:27:22 -0700152
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800153 // Convert!
Cole Faust07ea5032021-09-30 16:11:16 -0700154 files := flag.Args()
Cole Faust07ea5032021-09-30 16:11:16 -0700155 if *allInSource {
Cole Faustebf79bf2021-10-05 11:05:02 -0700156 productConfigMap := buildProductConfigMap()
Cole Faust07ea5032021-09-30 16:11:16 -0700157 for _, path := range productConfigMap {
158 files = append(files, path)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800159 }
Cole Faust07ea5032021-09-30 16:11:16 -0700160 }
Cole Faust07ea5032021-09-30 16:11:16 -0700161 ok := true
162 for _, mkFile := range files {
163 ok = convertOne(mkFile) && ok
164 }
165
166 if *launcher != "" {
167 if len(files) != 1 {
168 quit(fmt.Errorf("a launcher can be generated only for a single product"))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800169 }
Cole Faust864028a2021-12-01 13:43:17 -0800170 if *inputVariables == "" {
171 quit(fmt.Errorf("the product launcher requires an input variables file"))
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700172 }
Cole Faust864028a2021-12-01 13:43:17 -0800173 if !convertOne(*inputVariables) {
174 quit(fmt.Errorf("the product launcher input variables file failed to convert"))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800175 }
176
Cole Faust864028a2021-12-01 13:43:17 -0800177 err := writeGenerated(*launcher, mk2rbc.Launcher(outputFilePath(files[0]), outputFilePath(*inputVariables),
Cole Faust07ea5032021-09-30 16:11:16 -0700178 mk2rbc.MakePath2ModuleName(files[0])))
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700179 if err != nil {
Cole Faust6ed7cb42021-10-07 17:08:46 -0700180 fmt.Fprintf(os.Stderr, "%s: %s", files[0], err)
181 ok = false
182 }
183 }
184 if *boardlauncher != "" {
185 if len(files) != 1 {
186 quit(fmt.Errorf("a launcher can be generated only for a single product"))
187 }
188 if *inputVariables == "" {
189 quit(fmt.Errorf("the board launcher requires an input variables file"))
190 }
191 if !convertOne(*inputVariables) {
192 quit(fmt.Errorf("the board launcher input variables file failed to convert"))
193 }
194 err := writeGenerated(*boardlauncher, mk2rbc.BoardLauncher(
195 outputFilePath(files[0]), outputFilePath(*inputVariables)))
196 if err != nil {
197 fmt.Fprintf(os.Stderr, "%s: %s", files[0], err)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700198 ok = false
199 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800200 }
201
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800202 if *errstat {
203 errorLogger.printStatistics()
Sasha Smundak422b6142021-11-11 18:31:59 -0800204 printStats()
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800205 }
206 if !ok {
207 os.Exit(1)
208 }
209}
210
211func quit(s interface{}) {
212 fmt.Fprintln(os.Stderr, s)
213 os.Exit(2)
214}
215
216func buildProductConfigMap() map[string]string {
217 const androidProductsMk = "AndroidProducts.mk"
218 // Build the list of AndroidProducts.mk files: it's
Sasha Smundak70f17452021-09-01 19:14:24 -0700219 // build/make/target/product/AndroidProducts.mk + device/**/AndroidProducts.mk plus + vendor/**/AndroidProducts.mk
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800220 targetAndroidProductsFile := filepath.Join(*rootDir, "build", "make", "target", "product", androidProductsMk)
221 if _, err := os.Stat(targetAndroidProductsFile); err != nil {
222 fmt.Fprintf(os.Stderr, "%s: %s\n(hint: %s is not a source tree root)\n",
223 targetAndroidProductsFile, err, *rootDir)
224 }
225 productConfigMap := make(map[string]string)
226 if err := mk2rbc.UpdateProductConfigMap(productConfigMap, targetAndroidProductsFile); err != nil {
227 fmt.Fprintf(os.Stderr, "%s: %s\n", targetAndroidProductsFile, err)
228 }
Sasha Smundak70f17452021-09-01 19:14:24 -0700229 for _, t := range []string{"device", "vendor"} {
230 _ = filepath.WalkDir(filepath.Join(*rootDir, t),
231 func(path string, d os.DirEntry, err error) error {
232 if err != nil || d.IsDir() || filepath.Base(path) != androidProductsMk {
233 return nil
234 }
235 if err2 := mk2rbc.UpdateProductConfigMap(productConfigMap, path); err2 != nil {
236 fmt.Fprintf(os.Stderr, "%s: %s\n", path, err)
237 // Keep going, we want to find all such errors in a single run
238 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800239 return nil
Sasha Smundak70f17452021-09-01 19:14:24 -0700240 })
241 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800242 return productConfigMap
243}
244
245func getConfigVariables() {
246 path := filepath.Join(*rootDir, "build", "make", "core", "product.mk")
247 if err := mk2rbc.FindConfigVariables(path, mk2rbc.KnownVariables); err != nil {
248 quit(fmt.Errorf("%s\n(check --root[=%s], it should point to the source root)",
249 err, *rootDir))
250 }
251}
252
253// Implements mkparser.Scope, to be used by mkparser.Value.Value()
254type fileNameScope struct {
255 mk2rbc.ScopeBase
256}
257
258func (s fileNameScope) Get(name string) string {
259 if name != "BUILD_SYSTEM" {
260 return fmt.Sprintf("$(%s)", name)
261 }
262 return filepath.Join(*rootDir, "build", "make", "core")
263}
264
265func getSoongVariables() {
266 path := filepath.Join(*rootDir, "build", "make", "core", "soong_config.mk")
267 err := mk2rbc.FindSoongVariables(path, fileNameScope{}, mk2rbc.KnownVariables)
268 if err != nil {
269 quit(err)
270 }
271}
272
273var converted = make(map[string]*mk2rbc.StarlarkScript)
274
275//goland:noinspection RegExpRepeatedSpace
276var cpNormalizer = regexp.MustCompile(
277 "# Copyright \\(C\\) 20.. The Android Open Source Project")
278
279const cpNormalizedCopyright = "# Copyright (C) 20xx The Android Open Source Project"
280const copyright = `#
281# Copyright (C) 20xx The Android Open Source Project
282#
283# Licensed under the Apache License, Version 2.0 (the "License");
284# you may not use this file except in compliance with the License.
285# You may obtain a copy of the License at
286#
287# http://www.apache.org/licenses/LICENSE-2.0
288#
289# Unless required by applicable law or agreed to in writing, software
290# distributed under the License is distributed on an "AS IS" BASIS,
291# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
292# See the License for the specific language governing permissions and
293# limitations under the License.
294#
295`
296
297// Convert a single file.
298// Write the result either to the same directory, to the same place in
299// the output hierarchy, or to the stdout.
300// Optionally, recursively convert the files this one includes by
301// $(call inherit-product) or an include statement.
302func convertOne(mkFile string) (ok bool) {
303 if v, ok := converted[mkFile]; ok {
304 return v != nil
305 }
306 converted[mkFile] = nil
307 defer func() {
308 if r := recover(); r != nil {
309 ok = false
310 fmt.Fprintf(os.Stderr, "%s: panic while converting: %s\n%s\n", mkFile, r, debug.Stack())
311 }
312 }()
313
314 mk2starRequest := mk2rbc.Request{
Sasha Smundak422b6142021-11-11 18:31:59 -0800315 MkFile: mkFile,
316 Reader: nil,
317 RootDir: *rootDir,
318 OutputDir: *outputTop,
319 OutputSuffix: *suffix,
320 TracedVariables: tracedVariables,
321 TraceCalls: *traceCalls,
322 SourceFS: os.DirFS(*rootDir),
323 MakefileFinder: makefileFinder,
324 ErrorLogger: errorLogger,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800325 }
326 ss, err := mk2rbc.Convert(mk2starRequest)
327 if err != nil {
328 fmt.Fprintln(os.Stderr, mkFile, ": ", err)
329 return false
330 }
331 script := ss.String()
332 outputPath := outputFilePath(mkFile)
333
334 if *dryRun {
335 fmt.Printf("==== %s ====\n", outputPath)
336 // Print generated script after removing the copyright header
337 outText := cpNormalizer.ReplaceAllString(script, cpNormalizedCopyright)
338 fmt.Println(strings.TrimPrefix(outText, copyright))
339 } else {
340 if err := maybeBackup(outputPath); err != nil {
341 fmt.Fprintln(os.Stderr, err)
342 return false
343 }
344 if err := writeGenerated(outputPath, script); err != nil {
345 fmt.Fprintln(os.Stderr, err)
346 return false
347 }
348 }
349 ok = true
350 if *recurse {
351 for _, sub := range ss.SubConfigFiles() {
352 // File may be absent if it is a conditional load
353 if _, err := os.Stat(sub); os.IsNotExist(err) {
354 continue
355 }
356 ok = convertOne(sub) && ok
357 }
358 }
359 converted[mkFile] = ss
360 return ok
361}
362
363// Optionally saves the previous version of the generated file
364func maybeBackup(filename string) error {
365 stat, err := os.Stat(filename)
366 if os.IsNotExist(err) {
367 return nil
368 }
369 if !stat.Mode().IsRegular() {
370 return fmt.Errorf("%s exists and is not a regular file", filename)
371 }
372 switch *mode {
373 case "backup":
374 return os.Rename(filename, filename+backupSuffix)
375 case "write":
376 return os.Remove(filename)
377 default:
378 return fmt.Errorf("%s already exists, use --mode option", filename)
379 }
380}
381
382func outputFilePath(mkFile string) string {
383 path := strings.TrimSuffix(mkFile, filepath.Ext(mkFile)) + *suffix
384 if *outputTop != "" {
385 path = filepath.Join(*outputTop, path)
386 }
387 return path
388}
389
390func writeGenerated(path string, contents string) error {
391 if err := os.MkdirAll(filepath.Dir(path), os.ModeDir|os.ModePerm); err != nil {
392 return err
393 }
394 if err := ioutil.WriteFile(path, []byte(contents), 0644); err != nil {
395 return err
396 }
397 return nil
398}
399
400func printStats() {
401 var sortedFiles []string
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800402 for p := range converted {
403 sortedFiles = append(sortedFiles, p)
404 }
405 sort.Strings(sortedFiles)
406
407 nOk, nPartial, nFailed := 0, 0, 0
408 for _, f := range sortedFiles {
409 if converted[f] == nil {
410 nFailed++
411 } else if converted[f].HasErrors() {
412 nPartial++
413 } else {
414 nOk++
415 }
416 }
Sasha Smundak422b6142021-11-11 18:31:59 -0800417 if nPartial > 0 {
418 fmt.Fprintf(os.Stderr, "Conversion was partially successful for:\n")
419 for _, f := range sortedFiles {
420 if ss := converted[f]; ss != nil && ss.HasErrors() {
421 fmt.Fprintln(os.Stderr, " ", f)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800422 }
423 }
424 }
Sasha Smundak422b6142021-11-11 18:31:59 -0800425
426 if nFailed > 0 {
427 fmt.Fprintf(os.Stderr, "Conversion failed for files:\n")
428 for _, f := range sortedFiles {
429 if converted[f] == nil {
430 fmt.Fprintln(os.Stderr, " ", f)
431 }
432 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800433 }
434}
435
436type datum struct {
437 count int
438 formattingArgs []string
439}
440
Sasha Smundak7d934b92021-11-10 12:20:01 -0800441type errorSink struct {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800442 data map[string]datum
443}
444
Sasha Smundak422b6142021-11-11 18:31:59 -0800445func (ebt errorSink) NewError(el mk2rbc.ErrorLocation, node parser.Node, message string, args ...interface{}) {
446 fmt.Fprint(os.Stderr, el, ": ")
Sasha Smundak7d934b92021-11-10 12:20:01 -0800447 fmt.Fprintf(os.Stderr, message, args...)
448 fmt.Fprintln(os.Stderr)
449 if !*errstat {
450 return
451 }
452
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800453 v, exists := ebt.data[message]
454 if exists {
455 v.count++
456 } else {
457 v = datum{1, nil}
458 }
459 if strings.Contains(message, "%s") {
460 var newArg1 string
461 if len(args) == 0 {
462 panic(fmt.Errorf(`%s has %%s but args are missing`, message))
463 }
464 newArg1 = fmt.Sprint(args[0])
465 if message == "unsupported line" {
466 newArg1 = node.Dump()
467 } else if message == "unsupported directive %s" {
468 if newArg1 == "include" || newArg1 == "-include" {
469 newArg1 = node.Dump()
470 }
471 }
472 v.formattingArgs = append(v.formattingArgs, newArg1)
473 }
474 ebt.data[message] = v
475}
476
Sasha Smundak7d934b92021-11-10 12:20:01 -0800477func (ebt errorSink) printStatistics() {
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800478 if len(ebt.data) > 0 {
479 fmt.Fprintln(os.Stderr, "Error counts:")
480 }
481 for message, data := range ebt.data {
482 if len(data.formattingArgs) == 0 {
483 fmt.Fprintf(os.Stderr, "%4d %s\n", data.count, message)
484 continue
485 }
486 itemsByFreq, count := stringsWithFreq(data.formattingArgs, 30)
487 fmt.Fprintf(os.Stderr, "%4d %s [%d unique items]:\n", data.count, message, count)
488 fmt.Fprintln(os.Stderr, " ", itemsByFreq)
489 }
490}
491
492func stringsWithFreq(items []string, topN int) (string, int) {
493 freq := make(map[string]int)
494 for _, item := range items {
495 freq[strings.TrimPrefix(strings.TrimSuffix(item, "]"), "[")]++
496 }
497 var sorted []string
498 for item := range freq {
499 sorted = append(sorted, item)
500 }
501 sort.Slice(sorted, func(i int, j int) bool {
502 return freq[sorted[i]] > freq[sorted[j]]
503 })
504 sep := ""
505 res := ""
506 for i, item := range sorted {
507 if i >= topN {
508 res += " ..."
509 break
510 }
511 count := freq[item]
512 if count > 1 {
513 res += fmt.Sprintf("%s%s(%d)", sep, item, count)
514 } else {
515 res += fmt.Sprintf("%s%s", sep, item)
516 }
517 sep = ", "
518 }
519 return res, len(sorted)
520}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700521
522type LinuxMakefileFinder struct {
523 cachedRoot string
524 cachedMakefiles []string
525}
526
527func (l *LinuxMakefileFinder) Find(root string) []string {
528 if l.cachedMakefiles != nil && l.cachedRoot == root {
529 return l.cachedMakefiles
530 }
531 l.cachedRoot = root
532 l.cachedMakefiles = make([]string, 0)
533
534 // Return all *.mk files but not in hidden directories.
535
536 // NOTE(asmundak): as it turns out, even the WalkDir (which is an _optimized_ directory tree walker)
537 // is about twice slower than running `find` command (14s vs 6s on the internal Android source tree).
538 common_args := []string{"!", "-type", "d", "-name", "*.mk", "!", "-path", "*/.*/*"}
539 if root != "" {
540 common_args = append([]string{root}, common_args...)
541 }
542 cmd := exec.Command("/usr/bin/find", common_args...)
543 stdout, err := cmd.StdoutPipe()
544 if err == nil {
545 err = cmd.Start()
546 }
547 if err != nil {
548 panic(fmt.Errorf("cannot get the output from %s: %s", cmd, err))
549 }
550 scanner := bufio.NewScanner(stdout)
551 for scanner.Scan() {
552 l.cachedMakefiles = append(l.cachedMakefiles, strings.TrimPrefix(scanner.Text(), "./"))
553 }
554 stdout.Close()
555 return l.cachedMakefiles
556}