liyujie
2025-08-28 786ff4f4ca2374bdd9177f2e24b503d43e7a3b93
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
 
package bootstrap
 
import (
   "bufio"
   "flag"
   "fmt"
   "io"
   "io/ioutil"
   "os"
   "path/filepath"
   "runtime"
   "runtime/debug"
   "runtime/pprof"
   "runtime/trace"
 
   "github.com/google/blueprint"
   "github.com/google/blueprint/deptools"
)
 
var (
   outFile        string
   globFile       string
   depFile        string
   docFile        string
   cpuprofile     string
   memprofile     string
   traceFile      string
   runGoTests     bool
   noGC           bool
   moduleListFile string
   emptyNinjaFile bool
 
   BuildDir      string
   NinjaBuildDir string
   SrcDir        string
)
 
func init() {
   flag.StringVar(&outFile, "o", "build.ninja", "the Ninja file to output")
   flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
   flag.StringVar(&BuildDir, "b", ".", "the build output directory")
   flag.StringVar(&NinjaBuildDir, "n", "", "the ninja builddir directory")
   flag.StringVar(&depFile, "d", "", "the dependency file to output")
   flag.StringVar(&docFile, "docs", "", "build documentation file to output")
   flag.StringVar(&cpuprofile, "cpuprofile", "", "write cpu profile to file")
   flag.StringVar(&traceFile, "trace", "", "write trace to file")
   flag.StringVar(&memprofile, "memprofile", "", "write memory profile to file")
   flag.BoolVar(&noGC, "nogc", false, "turn off GC for debugging")
   flag.BoolVar(&runGoTests, "t", false, "build and run go tests during bootstrap")
   flag.StringVar(&moduleListFile, "l", "", "file that lists filepaths to parse")
   flag.BoolVar(&emptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
}
 
func Main(ctx *blueprint.Context, config interface{}, extraNinjaFileDeps ...string) {
   if !flag.Parsed() {
       flag.Parse()
   }
 
   runtime.GOMAXPROCS(runtime.NumCPU())
 
   if noGC {
       debug.SetGCPercent(-1)
   }
 
   if cpuprofile != "" {
       f, err := os.Create(cpuprofile)
       if err != nil {
           fatalf("error opening cpuprofile: %s", err)
       }
       pprof.StartCPUProfile(f)
       defer f.Close()
       defer pprof.StopCPUProfile()
   }
 
   if traceFile != "" {
       f, err := os.Create(traceFile)
       if err != nil {
           fatalf("error opening trace: %s", err)
       }
       trace.Start(f)
       defer f.Close()
       defer trace.Stop()
   }
 
   if flag.NArg() != 1 {
       fatalf("no Blueprints file specified")
   }
 
   SrcDir = filepath.Dir(flag.Arg(0))
   if moduleListFile != "" {
       ctx.SetModuleListFile(moduleListFile)
       extraNinjaFileDeps = append(extraNinjaFileDeps, moduleListFile)
   } else {
       fatalf("-l <moduleListFile> is required and must be nonempty")
   }
   filesToParse, err := ctx.ListModulePaths(SrcDir)
   if err != nil {
       fatalf("could not enumerate files: %v\n", err.Error())
   }
 
   if NinjaBuildDir == "" {
       NinjaBuildDir = BuildDir
   }
 
   stage := StageMain
   if c, ok := config.(ConfigInterface); ok {
       if c.GeneratingPrimaryBuilder() {
           stage = StagePrimary
       }
   }
 
   bootstrapConfig := &Config{
       stage: stage,
 
       topLevelBlueprintsFile: flag.Arg(0),
       emptyNinjaFile:         emptyNinjaFile,
       runGoTests:             runGoTests,
       moduleListFile:         moduleListFile,
   }
 
   ctx.RegisterBottomUpMutator("bootstrap_plugin_deps", pluginDeps)
   ctx.RegisterModuleType("bootstrap_go_package", newGoPackageModuleFactory(bootstrapConfig))
   ctx.RegisterModuleType("bootstrap_go_binary", newGoBinaryModuleFactory(bootstrapConfig, false))
   ctx.RegisterModuleType("blueprint_go_binary", newGoBinaryModuleFactory(bootstrapConfig, true))
   ctx.RegisterSingletonType("bootstrap", newSingletonFactory(bootstrapConfig))
 
   ctx.RegisterSingletonType("glob", globSingletonFactory(ctx))
 
   deps, errs := ctx.ParseFileList(filepath.Dir(bootstrapConfig.topLevelBlueprintsFile), filesToParse)
   if len(errs) > 0 {
       fatalErrors(errs)
   }
 
   // Add extra ninja file dependencies
   deps = append(deps, extraNinjaFileDeps...)
 
   extraDeps, errs := ctx.ResolveDependencies(config)
   if len(errs) > 0 {
       fatalErrors(errs)
   }
   deps = append(deps, extraDeps...)
 
   if docFile != "" {
       err := writeDocs(ctx, docFile)
       if err != nil {
           fatalErrors([]error{err})
       }
       return
   }
 
   if c, ok := config.(ConfigStopBefore); ok {
       if c.StopBefore() == StopBeforePrepareBuildActions {
           return
       }
   }
 
   extraDeps, errs = ctx.PrepareBuildActions(config)
   if len(errs) > 0 {
       fatalErrors(errs)
   }
   deps = append(deps, extraDeps...)
 
   const outFilePermissions = 0666
   var out io.Writer
   var f *os.File
   var buf *bufio.Writer
 
   if stage != StageMain || !emptyNinjaFile {
       f, err = os.OpenFile(outFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, outFilePermissions)
       if err != nil {
           fatalf("error opening Ninja file: %s", err)
       }
       buf = bufio.NewWriter(f)
       out = buf
   } else {
       out = ioutil.Discard
   }
 
   err = ctx.WriteBuildFile(out)
   if err != nil {
       fatalf("error writing Ninja file contents: %s", err)
   }
 
   if buf != nil {
       err = buf.Flush()
       if err != nil {
           fatalf("error flushing Ninja file contents: %s", err)
       }
   }
 
   if f != nil {
       err = f.Close()
       if err != nil {
           fatalf("error closing Ninja file: %s", err)
       }
   }
 
   if globFile != "" {
       buffer, errs := generateGlobNinjaFile(ctx.Globs)
       if len(errs) > 0 {
           fatalErrors(errs)
       }
 
       err = ioutil.WriteFile(globFile, buffer, outFilePermissions)
       if err != nil {
           fatalf("error writing %s: %s", outFile, err)
       }
   }
 
   if depFile != "" {
       err := deptools.WriteDepFile(depFile, outFile, deps)
       if err != nil {
           fatalf("error writing depfile: %s", err)
       }
   }
 
   if c, ok := config.(ConfigRemoveAbandonedFilesUnder); ok {
       under, except := c.RemoveAbandonedFilesUnder()
       err := removeAbandonedFilesUnder(ctx, bootstrapConfig, SrcDir, under, except)
       if err != nil {
           fatalf("error removing abandoned files: %s", err)
       }
   }
 
   if memprofile != "" {
       f, err := os.Create(memprofile)
       if err != nil {
           fatalf("error opening memprofile: %s", err)
       }
       defer f.Close()
       pprof.WriteHeapProfile(f)
   }
}
 
func fatalf(format string, args ...interface{}) {
   fmt.Printf(format, args...)
   fmt.Print("\n")
   os.Exit(1)
}
 
func fatalErrors(errs []error) {
   red := "\x1b[31m"
   unred := "\x1b[0m"
 
   for _, err := range errs {
       switch err := err.(type) {
       case *blueprint.BlueprintError,
           *blueprint.ModuleError,
           *blueprint.PropertyError:
           fmt.Printf("%serror:%s %s\n", red, unred, err.Error())
       default:
           fmt.Printf("%sinternal error:%s %s\n", red, unred, err)
       }
   }
   os.Exit(1)
}