blob: d8e701886c042bcf2dfbabf8c25977a5d0d060f2 [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`)
49 warn = flag.Bool("warnings", false, "warn about partially failed conversions")
50 verbose = flag.Bool("v", false, "print summary")
51 errstat = flag.Bool("error_stat", false, "print error statistics")
52 traceVar = flag.String("trace", "", "comma-separated list of variables to trace")
53 // TODO(asmundak): this option is for debugging
54 allInSource = flag.Bool("all", false, "convert all product config makefiles in the tree under //")
55 outputTop = flag.String("outdir", "", "write output files into this directory hierarchy")
56 launcher = flag.String("launcher", "", "generated launcher path. If set, the non-flag argument is _product_name_")
57 printProductConfigMap = flag.Bool("print_product_config_map", false, "print product config map and exit")
Sasha Smundak38802792021-08-01 14:38:07 -070058 cpuProfile = flag.String("cpu_profile", "", "write cpu profile to file")
Sasha Smundakb051c4e2020-11-05 20:45:07 -080059 traceCalls = flag.Bool("trace_calls", false, "trace function calls")
60)
61
62func init() {
63 // Poor man's flag aliasing: works, but the usage string is ugly and
64 // 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")
76 flagAlias("warnings", "w")
77 flagAlias("error_stat", "e")
78}
79
80var backupSuffix string
81var tracedVariables []string
82var errorLogger = errorsByType{data: make(map[string]datum)}
Sasha Smundak6609ba72021-07-22 18:32:56 -070083var makefileFinder = &LinuxMakefileFinder{}
Sasha Smundakd7d07ad2021-09-10 15:42:34 -070084var versionDefaultsMk = filepath.Join("build", "make", "core", "version_defaults.mk")
Sasha Smundakb051c4e2020-11-05 20:45:07 -080085
86func main() {
87 flag.Usage = func() {
88 cmd := filepath.Base(os.Args[0])
89 fmt.Fprintf(flag.CommandLine.Output(),
90 "Usage: %[1]s flags file...\n"+
91 "or: %[1]s flags --launcher=PATH PRODUCT\n", cmd)
92 flag.PrintDefaults()
93 }
94 flag.Parse()
95
96 // Delouse
97 if *suffix == ".mk" {
98 quit("cannot use .mk as generated file suffix")
99 }
100 if *suffix == "" {
101 quit("suffix cannot be empty")
102 }
103 if *outputTop != "" {
104 if err := os.MkdirAll(*outputTop, os.ModeDir+os.ModePerm); err != nil {
105 quit(err)
106 }
107 s, err := filepath.Abs(*outputTop)
108 if err != nil {
109 quit(err)
110 }
111 *outputTop = s
112 }
113 if *allInSource && len(flag.Args()) > 0 {
114 quit("file list cannot be specified when -all is present")
115 }
116 if *allInSource && *launcher != "" {
117 quit("--all and --launcher are mutually exclusive")
118 }
119
120 // Flag-driven adjustments
121 if (*suffix)[0] != '.' {
122 *suffix = "." + *suffix
123 }
124 if *mode == "backup" {
125 backupSuffix = time.Now().Format("20060102150405")
126 }
127 if *traceVar != "" {
128 tracedVariables = strings.Split(*traceVar, ",")
129 }
130
Sasha Smundak38802792021-08-01 14:38:07 -0700131 if *cpuProfile != "" {
132 f, err := os.Create(*cpuProfile)
133 if err != nil {
134 quit(err)
135 }
136 pprof.StartCPUProfile(f)
137 defer pprof.StopCPUProfile()
138 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800139 // Find out global variables
140 getConfigVariables()
141 getSoongVariables()
142
143 if *printProductConfigMap {
144 productConfigMap := buildProductConfigMap()
145 var products []string
146 for p := range productConfigMap {
147 products = append(products, p)
148 }
149 sort.Strings(products)
150 for _, p := range products {
151 fmt.Println(p, productConfigMap[p])
152 }
153 os.Exit(0)
154 }
Sasha Smundakb2ac8592021-07-26 09:27:22 -0700155
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800156 // Convert!
Cole Faust07ea5032021-09-30 16:11:16 -0700157 files := flag.Args()
Cole Faust07ea5032021-09-30 16:11:16 -0700158 if *allInSource {
Cole Faustebf79bf2021-10-05 11:05:02 -0700159 productConfigMap := buildProductConfigMap()
Cole Faust07ea5032021-09-30 16:11:16 -0700160 for _, path := range productConfigMap {
161 files = append(files, path)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800162 }
Cole Faust07ea5032021-09-30 16:11:16 -0700163 }
Cole Faust07ea5032021-09-30 16:11:16 -0700164 ok := true
165 for _, mkFile := range files {
166 ok = convertOne(mkFile) && ok
167 }
168
169 if *launcher != "" {
170 if len(files) != 1 {
171 quit(fmt.Errorf("a launcher can be generated only for a single product"))
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800172 }
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700173 versionDefaults, err := generateVersionDefaults()
174 if err != nil {
175 quit(err)
176 }
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700177 versionDefaultsPath := outputFilePath(versionDefaultsMk)
178 err = writeGenerated(versionDefaultsPath, versionDefaults)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800179 if err != nil {
Cole Faust07ea5032021-09-30 16:11:16 -0700180 fmt.Fprintf(os.Stderr, "%s:%s", files[0], err)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800181 ok = false
182 }
183
Cole Faust07ea5032021-09-30 16:11:16 -0700184 err = writeGenerated(*launcher, mk2rbc.Launcher(outputFilePath(files[0]), versionDefaultsPath,
185 mk2rbc.MakePath2ModuleName(files[0])))
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700186 if err != nil {
Cole Faust07ea5032021-09-30 16:11:16 -0700187 fmt.Fprintf(os.Stderr, "%s:%s", files[0], err)
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700188 ok = false
189 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800190 }
191
192 printStats()
193 if *errstat {
194 errorLogger.printStatistics()
195 }
196 if !ok {
197 os.Exit(1)
198 }
199}
200
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700201func generateVersionDefaults() (string, error) {
202 versionSettings, err := mk2rbc.ParseVersionDefaults(filepath.Join(*rootDir, versionDefaultsMk))
203 if err != nil {
204 return "", err
205 }
206 return mk2rbc.VersionDefaults(versionSettings), nil
207
208}
209
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800210func quit(s interface{}) {
211 fmt.Fprintln(os.Stderr, s)
212 os.Exit(2)
213}
214
215func buildProductConfigMap() map[string]string {
216 const androidProductsMk = "AndroidProducts.mk"
217 // Build the list of AndroidProducts.mk files: it's
Sasha Smundak70f17452021-09-01 19:14:24 -0700218 // build/make/target/product/AndroidProducts.mk + device/**/AndroidProducts.mk plus + vendor/**/AndroidProducts.mk
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800219 targetAndroidProductsFile := filepath.Join(*rootDir, "build", "make", "target", "product", androidProductsMk)
220 if _, err := os.Stat(targetAndroidProductsFile); err != nil {
221 fmt.Fprintf(os.Stderr, "%s: %s\n(hint: %s is not a source tree root)\n",
222 targetAndroidProductsFile, err, *rootDir)
223 }
224 productConfigMap := make(map[string]string)
225 if err := mk2rbc.UpdateProductConfigMap(productConfigMap, targetAndroidProductsFile); err != nil {
226 fmt.Fprintf(os.Stderr, "%s: %s\n", targetAndroidProductsFile, err)
227 }
Sasha Smundak70f17452021-09-01 19:14:24 -0700228 for _, t := range []string{"device", "vendor"} {
229 _ = filepath.WalkDir(filepath.Join(*rootDir, t),
230 func(path string, d os.DirEntry, err error) error {
231 if err != nil || d.IsDir() || filepath.Base(path) != androidProductsMk {
232 return nil
233 }
234 if err2 := mk2rbc.UpdateProductConfigMap(productConfigMap, path); err2 != nil {
235 fmt.Fprintf(os.Stderr, "%s: %s\n", path, err)
236 // Keep going, we want to find all such errors in a single run
237 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800238 return nil
Sasha Smundak70f17452021-09-01 19:14:24 -0700239 })
240 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800241 return productConfigMap
242}
243
244func getConfigVariables() {
245 path := filepath.Join(*rootDir, "build", "make", "core", "product.mk")
246 if err := mk2rbc.FindConfigVariables(path, mk2rbc.KnownVariables); err != nil {
247 quit(fmt.Errorf("%s\n(check --root[=%s], it should point to the source root)",
248 err, *rootDir))
249 }
250}
251
252// Implements mkparser.Scope, to be used by mkparser.Value.Value()
253type fileNameScope struct {
254 mk2rbc.ScopeBase
255}
256
257func (s fileNameScope) Get(name string) string {
258 if name != "BUILD_SYSTEM" {
259 return fmt.Sprintf("$(%s)", name)
260 }
261 return filepath.Join(*rootDir, "build", "make", "core")
262}
263
264func getSoongVariables() {
265 path := filepath.Join(*rootDir, "build", "make", "core", "soong_config.mk")
266 err := mk2rbc.FindSoongVariables(path, fileNameScope{}, mk2rbc.KnownVariables)
267 if err != nil {
268 quit(err)
269 }
270}
271
272var converted = make(map[string]*mk2rbc.StarlarkScript)
273
274//goland:noinspection RegExpRepeatedSpace
275var cpNormalizer = regexp.MustCompile(
276 "# Copyright \\(C\\) 20.. The Android Open Source Project")
277
278const cpNormalizedCopyright = "# Copyright (C) 20xx The Android Open Source Project"
279const copyright = `#
280# Copyright (C) 20xx The Android Open Source Project
281#
282# Licensed under the Apache License, Version 2.0 (the "License");
283# you may not use this file except in compliance with the License.
284# You may obtain a copy of the License at
285#
286# http://www.apache.org/licenses/LICENSE-2.0
287#
288# Unless required by applicable law or agreed to in writing, software
289# distributed under the License is distributed on an "AS IS" BASIS,
290# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
291# See the License for the specific language governing permissions and
292# limitations under the License.
293#
294`
295
296// Convert a single file.
297// Write the result either to the same directory, to the same place in
298// the output hierarchy, or to the stdout.
299// Optionally, recursively convert the files this one includes by
300// $(call inherit-product) or an include statement.
301func convertOne(mkFile string) (ok bool) {
302 if v, ok := converted[mkFile]; ok {
303 return v != nil
304 }
305 converted[mkFile] = nil
306 defer func() {
307 if r := recover(); r != nil {
308 ok = false
309 fmt.Fprintf(os.Stderr, "%s: panic while converting: %s\n%s\n", mkFile, r, debug.Stack())
310 }
311 }()
312
313 mk2starRequest := mk2rbc.Request{
314 MkFile: mkFile,
315 Reader: nil,
316 RootDir: *rootDir,
317 OutputDir: *outputTop,
318 OutputSuffix: *suffix,
319 TracedVariables: tracedVariables,
320 TraceCalls: *traceCalls,
321 WarnPartialSuccess: *warn,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700322 SourceFS: os.DirFS(*rootDir),
323 MakefileFinder: makefileFinder,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800324 }
325 if *errstat {
326 mk2starRequest.ErrorLogger = errorLogger
327 }
328 ss, err := mk2rbc.Convert(mk2starRequest)
329 if err != nil {
330 fmt.Fprintln(os.Stderr, mkFile, ": ", err)
331 return false
332 }
333 script := ss.String()
334 outputPath := outputFilePath(mkFile)
335
336 if *dryRun {
337 fmt.Printf("==== %s ====\n", outputPath)
338 // Print generated script after removing the copyright header
339 outText := cpNormalizer.ReplaceAllString(script, cpNormalizedCopyright)
340 fmt.Println(strings.TrimPrefix(outText, copyright))
341 } else {
342 if err := maybeBackup(outputPath); err != nil {
343 fmt.Fprintln(os.Stderr, err)
344 return false
345 }
346 if err := writeGenerated(outputPath, script); err != nil {
347 fmt.Fprintln(os.Stderr, err)
348 return false
349 }
350 }
351 ok = true
352 if *recurse {
353 for _, sub := range ss.SubConfigFiles() {
354 // File may be absent if it is a conditional load
355 if _, err := os.Stat(sub); os.IsNotExist(err) {
356 continue
357 }
358 ok = convertOne(sub) && ok
359 }
360 }
361 converted[mkFile] = ss
362 return ok
363}
364
365// Optionally saves the previous version of the generated file
366func maybeBackup(filename string) error {
367 stat, err := os.Stat(filename)
368 if os.IsNotExist(err) {
369 return nil
370 }
371 if !stat.Mode().IsRegular() {
372 return fmt.Errorf("%s exists and is not a regular file", filename)
373 }
374 switch *mode {
375 case "backup":
376 return os.Rename(filename, filename+backupSuffix)
377 case "write":
378 return os.Remove(filename)
379 default:
380 return fmt.Errorf("%s already exists, use --mode option", filename)
381 }
382}
383
384func outputFilePath(mkFile string) string {
385 path := strings.TrimSuffix(mkFile, filepath.Ext(mkFile)) + *suffix
386 if *outputTop != "" {
387 path = filepath.Join(*outputTop, path)
388 }
389 return path
390}
391
392func writeGenerated(path string, contents string) error {
393 if err := os.MkdirAll(filepath.Dir(path), os.ModeDir|os.ModePerm); err != nil {
394 return err
395 }
396 if err := ioutil.WriteFile(path, []byte(contents), 0644); err != nil {
397 return err
398 }
399 return nil
400}
401
402func printStats() {
403 var sortedFiles []string
404 if !*warn && !*verbose {
405 return
406 }
407 for p := range converted {
408 sortedFiles = append(sortedFiles, p)
409 }
410 sort.Strings(sortedFiles)
411
412 nOk, nPartial, nFailed := 0, 0, 0
413 for _, f := range sortedFiles {
414 if converted[f] == nil {
415 nFailed++
416 } else if converted[f].HasErrors() {
417 nPartial++
418 } else {
419 nOk++
420 }
421 }
422 if *warn {
423 if nPartial > 0 {
424 fmt.Fprintf(os.Stderr, "Conversion was partially successful for:\n")
425 for _, f := range sortedFiles {
426 if ss := converted[f]; ss != nil && ss.HasErrors() {
427 fmt.Fprintln(os.Stderr, " ", f)
428 }
429 }
430 }
431
432 if nFailed > 0 {
433 fmt.Fprintf(os.Stderr, "Conversion failed for files:\n")
434 for _, f := range sortedFiles {
435 if converted[f] == nil {
436 fmt.Fprintln(os.Stderr, " ", f)
437 }
438 }
439 }
440 }
441 if *verbose {
442 fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Succeeded:", nOk)
443 fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Partial:", nPartial)
444 fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Failed:", nFailed)
445 }
446}
447
448type datum struct {
449 count int
450 formattingArgs []string
451}
452
453type errorsByType struct {
454 data map[string]datum
455}
456
457func (ebt errorsByType) NewError(message string, node parser.Node, args ...interface{}) {
458 v, exists := ebt.data[message]
459 if exists {
460 v.count++
461 } else {
462 v = datum{1, nil}
463 }
464 if strings.Contains(message, "%s") {
465 var newArg1 string
466 if len(args) == 0 {
467 panic(fmt.Errorf(`%s has %%s but args are missing`, message))
468 }
469 newArg1 = fmt.Sprint(args[0])
470 if message == "unsupported line" {
471 newArg1 = node.Dump()
472 } else if message == "unsupported directive %s" {
473 if newArg1 == "include" || newArg1 == "-include" {
474 newArg1 = node.Dump()
475 }
476 }
477 v.formattingArgs = append(v.formattingArgs, newArg1)
478 }
479 ebt.data[message] = v
480}
481
482func (ebt errorsByType) printStatistics() {
483 if len(ebt.data) > 0 {
484 fmt.Fprintln(os.Stderr, "Error counts:")
485 }
486 for message, data := range ebt.data {
487 if len(data.formattingArgs) == 0 {
488 fmt.Fprintf(os.Stderr, "%4d %s\n", data.count, message)
489 continue
490 }
491 itemsByFreq, count := stringsWithFreq(data.formattingArgs, 30)
492 fmt.Fprintf(os.Stderr, "%4d %s [%d unique items]:\n", data.count, message, count)
493 fmt.Fprintln(os.Stderr, " ", itemsByFreq)
494 }
495}
496
497func stringsWithFreq(items []string, topN int) (string, int) {
498 freq := make(map[string]int)
499 for _, item := range items {
500 freq[strings.TrimPrefix(strings.TrimSuffix(item, "]"), "[")]++
501 }
502 var sorted []string
503 for item := range freq {
504 sorted = append(sorted, item)
505 }
506 sort.Slice(sorted, func(i int, j int) bool {
507 return freq[sorted[i]] > freq[sorted[j]]
508 })
509 sep := ""
510 res := ""
511 for i, item := range sorted {
512 if i >= topN {
513 res += " ..."
514 break
515 }
516 count := freq[item]
517 if count > 1 {
518 res += fmt.Sprintf("%s%s(%d)", sep, item, count)
519 } else {
520 res += fmt.Sprintf("%s%s", sep, item)
521 }
522 sep = ", "
523 }
524 return res, len(sorted)
525}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700526
527type LinuxMakefileFinder struct {
528 cachedRoot string
529 cachedMakefiles []string
530}
531
532func (l *LinuxMakefileFinder) Find(root string) []string {
533 if l.cachedMakefiles != nil && l.cachedRoot == root {
534 return l.cachedMakefiles
535 }
536 l.cachedRoot = root
537 l.cachedMakefiles = make([]string, 0)
538
539 // Return all *.mk files but not in hidden directories.
540
541 // NOTE(asmundak): as it turns out, even the WalkDir (which is an _optimized_ directory tree walker)
542 // is about twice slower than running `find` command (14s vs 6s on the internal Android source tree).
543 common_args := []string{"!", "-type", "d", "-name", "*.mk", "!", "-path", "*/.*/*"}
544 if root != "" {
545 common_args = append([]string{root}, common_args...)
546 }
547 cmd := exec.Command("/usr/bin/find", common_args...)
548 stdout, err := cmd.StdoutPipe()
549 if err == nil {
550 err = cmd.Start()
551 }
552 if err != nil {
553 panic(fmt.Errorf("cannot get the output from %s: %s", cmd, err))
554 }
555 scanner := bufio.NewScanner(stdout)
556 for scanner.Scan() {
557 l.cachedMakefiles = append(l.cachedMakefiles, strings.TrimPrefix(scanner.Text(), "./"))
558 }
559 stdout.Close()
560 return l.cachedMakefiles
561}