blob: 7b5f298e27af938a7fd00d75c33fcfdb5cb215de [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!
157 ok := true
158 if *launcher != "" {
159 if len(flag.Args()) != 1 {
160 quit(fmt.Errorf("a launcher can be generated only for a single product"))
161 }
162 product := flag.Args()[0]
163 productConfigMap := buildProductConfigMap()
164 path, found := productConfigMap[product]
165 if !found {
166 quit(fmt.Errorf("cannot generate configuration launcher for %s, it is not a known product",
167 product))
168 }
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700169 versionDefaults, err := generateVersionDefaults()
170 if err != nil {
171 quit(err)
172 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800173 ok = convertOne(path) && ok
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700174 versionDefaultsPath := outputFilePath(versionDefaultsMk)
175 err = writeGenerated(versionDefaultsPath, versionDefaults)
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800176 if err != nil {
177 fmt.Fprintf(os.Stderr, "%s:%s", path, err)
178 ok = false
179 }
180
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700181 err = writeGenerated(*launcher, mk2rbc.Launcher(outputFilePath(path), versionDefaultsPath,
182 mk2rbc.MakePath2ModuleName(path)))
183 if err != nil {
184 fmt.Fprintf(os.Stderr, "%s:%s", path, err)
185 ok = false
186 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800187 } else {
188 files := flag.Args()
189 if *allInSource {
190 productConfigMap := buildProductConfigMap()
191 for _, path := range productConfigMap {
192 files = append(files, path)
193 }
194 }
195 for _, mkFile := range files {
196 ok = convertOne(mkFile) && ok
197 }
198 }
199
200 printStats()
201 if *errstat {
202 errorLogger.printStatistics()
203 }
204 if !ok {
205 os.Exit(1)
206 }
207}
208
Sasha Smundakd7d07ad2021-09-10 15:42:34 -0700209func generateVersionDefaults() (string, error) {
210 versionSettings, err := mk2rbc.ParseVersionDefaults(filepath.Join(*rootDir, versionDefaultsMk))
211 if err != nil {
212 return "", err
213 }
214 return mk2rbc.VersionDefaults(versionSettings), nil
215
216}
217
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800218func quit(s interface{}) {
219 fmt.Fprintln(os.Stderr, s)
220 os.Exit(2)
221}
222
223func buildProductConfigMap() map[string]string {
224 const androidProductsMk = "AndroidProducts.mk"
225 // Build the list of AndroidProducts.mk files: it's
Sasha Smundak70f17452021-09-01 19:14:24 -0700226 // build/make/target/product/AndroidProducts.mk + device/**/AndroidProducts.mk plus + vendor/**/AndroidProducts.mk
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800227 targetAndroidProductsFile := filepath.Join(*rootDir, "build", "make", "target", "product", androidProductsMk)
228 if _, err := os.Stat(targetAndroidProductsFile); err != nil {
229 fmt.Fprintf(os.Stderr, "%s: %s\n(hint: %s is not a source tree root)\n",
230 targetAndroidProductsFile, err, *rootDir)
231 }
232 productConfigMap := make(map[string]string)
233 if err := mk2rbc.UpdateProductConfigMap(productConfigMap, targetAndroidProductsFile); err != nil {
234 fmt.Fprintf(os.Stderr, "%s: %s\n", targetAndroidProductsFile, err)
235 }
Sasha Smundak70f17452021-09-01 19:14:24 -0700236 for _, t := range []string{"device", "vendor"} {
237 _ = filepath.WalkDir(filepath.Join(*rootDir, t),
238 func(path string, d os.DirEntry, err error) error {
239 if err != nil || d.IsDir() || filepath.Base(path) != androidProductsMk {
240 return nil
241 }
242 if err2 := mk2rbc.UpdateProductConfigMap(productConfigMap, path); err2 != nil {
243 fmt.Fprintf(os.Stderr, "%s: %s\n", path, err)
244 // Keep going, we want to find all such errors in a single run
245 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800246 return nil
Sasha Smundak70f17452021-09-01 19:14:24 -0700247 })
248 }
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800249 return productConfigMap
250}
251
252func getConfigVariables() {
253 path := filepath.Join(*rootDir, "build", "make", "core", "product.mk")
254 if err := mk2rbc.FindConfigVariables(path, mk2rbc.KnownVariables); err != nil {
255 quit(fmt.Errorf("%s\n(check --root[=%s], it should point to the source root)",
256 err, *rootDir))
257 }
258}
259
260// Implements mkparser.Scope, to be used by mkparser.Value.Value()
261type fileNameScope struct {
262 mk2rbc.ScopeBase
263}
264
265func (s fileNameScope) Get(name string) string {
266 if name != "BUILD_SYSTEM" {
267 return fmt.Sprintf("$(%s)", name)
268 }
269 return filepath.Join(*rootDir, "build", "make", "core")
270}
271
272func getSoongVariables() {
273 path := filepath.Join(*rootDir, "build", "make", "core", "soong_config.mk")
274 err := mk2rbc.FindSoongVariables(path, fileNameScope{}, mk2rbc.KnownVariables)
275 if err != nil {
276 quit(err)
277 }
278}
279
280var converted = make(map[string]*mk2rbc.StarlarkScript)
281
282//goland:noinspection RegExpRepeatedSpace
283var cpNormalizer = regexp.MustCompile(
284 "# Copyright \\(C\\) 20.. The Android Open Source Project")
285
286const cpNormalizedCopyright = "# Copyright (C) 20xx The Android Open Source Project"
287const copyright = `#
288# Copyright (C) 20xx The Android Open Source Project
289#
290# Licensed under the Apache License, Version 2.0 (the "License");
291# you may not use this file except in compliance with the License.
292# You may obtain a copy of the License at
293#
294# http://www.apache.org/licenses/LICENSE-2.0
295#
296# Unless required by applicable law or agreed to in writing, software
297# distributed under the License is distributed on an "AS IS" BASIS,
298# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
299# See the License for the specific language governing permissions and
300# limitations under the License.
301#
302`
303
304// Convert a single file.
305// Write the result either to the same directory, to the same place in
306// the output hierarchy, or to the stdout.
307// Optionally, recursively convert the files this one includes by
308// $(call inherit-product) or an include statement.
309func convertOne(mkFile string) (ok bool) {
310 if v, ok := converted[mkFile]; ok {
311 return v != nil
312 }
313 converted[mkFile] = nil
314 defer func() {
315 if r := recover(); r != nil {
316 ok = false
317 fmt.Fprintf(os.Stderr, "%s: panic while converting: %s\n%s\n", mkFile, r, debug.Stack())
318 }
319 }()
320
321 mk2starRequest := mk2rbc.Request{
322 MkFile: mkFile,
323 Reader: nil,
324 RootDir: *rootDir,
325 OutputDir: *outputTop,
326 OutputSuffix: *suffix,
327 TracedVariables: tracedVariables,
328 TraceCalls: *traceCalls,
329 WarnPartialSuccess: *warn,
Sasha Smundak6609ba72021-07-22 18:32:56 -0700330 SourceFS: os.DirFS(*rootDir),
331 MakefileFinder: makefileFinder,
Sasha Smundakb051c4e2020-11-05 20:45:07 -0800332 }
333 if *errstat {
334 mk2starRequest.ErrorLogger = errorLogger
335 }
336 ss, err := mk2rbc.Convert(mk2starRequest)
337 if err != nil {
338 fmt.Fprintln(os.Stderr, mkFile, ": ", err)
339 return false
340 }
341 script := ss.String()
342 outputPath := outputFilePath(mkFile)
343
344 if *dryRun {
345 fmt.Printf("==== %s ====\n", outputPath)
346 // Print generated script after removing the copyright header
347 outText := cpNormalizer.ReplaceAllString(script, cpNormalizedCopyright)
348 fmt.Println(strings.TrimPrefix(outText, copyright))
349 } else {
350 if err := maybeBackup(outputPath); err != nil {
351 fmt.Fprintln(os.Stderr, err)
352 return false
353 }
354 if err := writeGenerated(outputPath, script); err != nil {
355 fmt.Fprintln(os.Stderr, err)
356 return false
357 }
358 }
359 ok = true
360 if *recurse {
361 for _, sub := range ss.SubConfigFiles() {
362 // File may be absent if it is a conditional load
363 if _, err := os.Stat(sub); os.IsNotExist(err) {
364 continue
365 }
366 ok = convertOne(sub) && ok
367 }
368 }
369 converted[mkFile] = ss
370 return ok
371}
372
373// Optionally saves the previous version of the generated file
374func maybeBackup(filename string) error {
375 stat, err := os.Stat(filename)
376 if os.IsNotExist(err) {
377 return nil
378 }
379 if !stat.Mode().IsRegular() {
380 return fmt.Errorf("%s exists and is not a regular file", filename)
381 }
382 switch *mode {
383 case "backup":
384 return os.Rename(filename, filename+backupSuffix)
385 case "write":
386 return os.Remove(filename)
387 default:
388 return fmt.Errorf("%s already exists, use --mode option", filename)
389 }
390}
391
392func outputFilePath(mkFile string) string {
393 path := strings.TrimSuffix(mkFile, filepath.Ext(mkFile)) + *suffix
394 if *outputTop != "" {
395 path = filepath.Join(*outputTop, path)
396 }
397 return path
398}
399
400func writeGenerated(path string, contents string) error {
401 if err := os.MkdirAll(filepath.Dir(path), os.ModeDir|os.ModePerm); err != nil {
402 return err
403 }
404 if err := ioutil.WriteFile(path, []byte(contents), 0644); err != nil {
405 return err
406 }
407 return nil
408}
409
410func printStats() {
411 var sortedFiles []string
412 if !*warn && !*verbose {
413 return
414 }
415 for p := range converted {
416 sortedFiles = append(sortedFiles, p)
417 }
418 sort.Strings(sortedFiles)
419
420 nOk, nPartial, nFailed := 0, 0, 0
421 for _, f := range sortedFiles {
422 if converted[f] == nil {
423 nFailed++
424 } else if converted[f].HasErrors() {
425 nPartial++
426 } else {
427 nOk++
428 }
429 }
430 if *warn {
431 if nPartial > 0 {
432 fmt.Fprintf(os.Stderr, "Conversion was partially successful for:\n")
433 for _, f := range sortedFiles {
434 if ss := converted[f]; ss != nil && ss.HasErrors() {
435 fmt.Fprintln(os.Stderr, " ", f)
436 }
437 }
438 }
439
440 if nFailed > 0 {
441 fmt.Fprintf(os.Stderr, "Conversion failed for files:\n")
442 for _, f := range sortedFiles {
443 if converted[f] == nil {
444 fmt.Fprintln(os.Stderr, " ", f)
445 }
446 }
447 }
448 }
449 if *verbose {
450 fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Succeeded:", nOk)
451 fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Partial:", nPartial)
452 fmt.Fprintf(os.Stderr, "%-16s%5d\n", "Failed:", nFailed)
453 }
454}
455
456type datum struct {
457 count int
458 formattingArgs []string
459}
460
461type errorsByType struct {
462 data map[string]datum
463}
464
465func (ebt errorsByType) NewError(message string, node parser.Node, args ...interface{}) {
466 v, exists := ebt.data[message]
467 if exists {
468 v.count++
469 } else {
470 v = datum{1, nil}
471 }
472 if strings.Contains(message, "%s") {
473 var newArg1 string
474 if len(args) == 0 {
475 panic(fmt.Errorf(`%s has %%s but args are missing`, message))
476 }
477 newArg1 = fmt.Sprint(args[0])
478 if message == "unsupported line" {
479 newArg1 = node.Dump()
480 } else if message == "unsupported directive %s" {
481 if newArg1 == "include" || newArg1 == "-include" {
482 newArg1 = node.Dump()
483 }
484 }
485 v.formattingArgs = append(v.formattingArgs, newArg1)
486 }
487 ebt.data[message] = v
488}
489
490func (ebt errorsByType) printStatistics() {
491 if len(ebt.data) > 0 {
492 fmt.Fprintln(os.Stderr, "Error counts:")
493 }
494 for message, data := range ebt.data {
495 if len(data.formattingArgs) == 0 {
496 fmt.Fprintf(os.Stderr, "%4d %s\n", data.count, message)
497 continue
498 }
499 itemsByFreq, count := stringsWithFreq(data.formattingArgs, 30)
500 fmt.Fprintf(os.Stderr, "%4d %s [%d unique items]:\n", data.count, message, count)
501 fmt.Fprintln(os.Stderr, " ", itemsByFreq)
502 }
503}
504
505func stringsWithFreq(items []string, topN int) (string, int) {
506 freq := make(map[string]int)
507 for _, item := range items {
508 freq[strings.TrimPrefix(strings.TrimSuffix(item, "]"), "[")]++
509 }
510 var sorted []string
511 for item := range freq {
512 sorted = append(sorted, item)
513 }
514 sort.Slice(sorted, func(i int, j int) bool {
515 return freq[sorted[i]] > freq[sorted[j]]
516 })
517 sep := ""
518 res := ""
519 for i, item := range sorted {
520 if i >= topN {
521 res += " ..."
522 break
523 }
524 count := freq[item]
525 if count > 1 {
526 res += fmt.Sprintf("%s%s(%d)", sep, item, count)
527 } else {
528 res += fmt.Sprintf("%s%s", sep, item)
529 }
530 sep = ", "
531 }
532 return res, len(sorted)
533}
Sasha Smundak6609ba72021-07-22 18:32:56 -0700534
535type LinuxMakefileFinder struct {
536 cachedRoot string
537 cachedMakefiles []string
538}
539
540func (l *LinuxMakefileFinder) Find(root string) []string {
541 if l.cachedMakefiles != nil && l.cachedRoot == root {
542 return l.cachedMakefiles
543 }
544 l.cachedRoot = root
545 l.cachedMakefiles = make([]string, 0)
546
547 // Return all *.mk files but not in hidden directories.
548
549 // NOTE(asmundak): as it turns out, even the WalkDir (which is an _optimized_ directory tree walker)
550 // is about twice slower than running `find` command (14s vs 6s on the internal Android source tree).
551 common_args := []string{"!", "-type", "d", "-name", "*.mk", "!", "-path", "*/.*/*"}
552 if root != "" {
553 common_args = append([]string{root}, common_args...)
554 }
555 cmd := exec.Command("/usr/bin/find", common_args...)
556 stdout, err := cmd.StdoutPipe()
557 if err == nil {
558 err = cmd.Start()
559 }
560 if err != nil {
561 panic(fmt.Errorf("cannot get the output from %s: %s", cmd, err))
562 }
563 scanner := bufio.NewScanner(stdout)
564 for scanner.Scan() {
565 l.cachedMakefiles = append(l.cachedMakefiles, strings.TrimPrefix(scanner.Text(), "./"))
566 }
567 stdout.Close()
568 return l.cachedMakefiles
569}