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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
|
// Copyright 2015 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 main
import (
"bytes"
"flag"
"fmt"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"strings"
"text/template"
"time"
"github.com/google/kati"
)
const shellDateTimeformat = time.RFC3339
var (
makefileFlag string
jobsFlag int
loadJSON string
saveJSON string
loadGOB string
saveGOB string
useCache bool
cpuprofile string
heapprofile string
memstats string
traceEventFile string
syntaxCheckOnlyFlag bool
queryFlag string
eagerCmdEvalFlag bool
generateNinja bool
gomaDir string
usePara bool
findCachePrunes string
findCacheLeafNames string
shellDate string
)
func init() {
// TODO: Make this default and replace this by -d flag.
flag.StringVar(&makefileFlag, "f", "", "Use it as a makefile")
flag.IntVar(&jobsFlag, "j", 1, "Allow N jobs at once.")
flag.StringVar(&loadGOB, "load", "", "")
flag.StringVar(&saveGOB, "save", "", "")
flag.StringVar(&loadJSON, "load_json", "", "")
flag.StringVar(&saveJSON, "save_json", "", "")
flag.BoolVar(&useCache, "use_cache", false, "Use cache.")
flag.StringVar(&cpuprofile, "kati_cpuprofile", "", "write cpu profile to `file`")
flag.StringVar(&heapprofile, "kati_heapprofile", "", "write heap profile to `file`")
flag.StringVar(&memstats, "kati_memstats", "", "Show memstats with given templates")
flag.StringVar(&traceEventFile, "kati_trace_event", "", "write trace event to `file`")
flag.BoolVar(&syntaxCheckOnlyFlag, "c", false, "Syntax check only.")
flag.StringVar(&queryFlag, "query", "", "Show the target info")
flag.BoolVar(&eagerCmdEvalFlag, "eager_cmd_eval", false, "Eval commands first.")
flag.BoolVar(&generateNinja, "ninja", false, "Generate build.ninja.")
flag.StringVar(&gomaDir, "goma_dir", "", "If specified, use goma to build C/C++ files.")
flag.BoolVar(&usePara, "use_para", false, "Use para.")
flag.StringVar(&findCachePrunes, "find_cache_prunes", "",
"space separated prune directories for find cache.")
flag.StringVar(&findCacheLeafNames, "find_cache_leaf_names", "",
"space separated leaf names for find cache.")
flag.StringVar(&shellDate, "shell_date", "", "specify $(shell date) time as "+shellDateTimeformat)
flag.BoolVar(&kati.LogFlag, "kati_log", false, "Verbose kati specific log")
flag.BoolVar(&kati.StatsFlag, "kati_stats", false, "Show a bunch of statistics")
flag.BoolVar(&kati.PeriodicStatsFlag, "kati_periodic_stats", false, "Show a bunch of periodic statistics")
flag.BoolVar(&kati.EvalStatsFlag, "kati_eval_stats", false, "Show eval statistics")
flag.BoolVar(&kati.DryRunFlag, "n", false, "Only print the commands that would be executed")
// TODO: Make this default.
flag.BoolVar(&kati.UseFindCache, "use_find_cache", false, "Use find cache.")
flag.BoolVar(&kati.UseWildcardCache, "use_wildcard_cache", true, "Use wildcard cache.")
flag.BoolVar(&kati.UseShellBuiltins, "use_shell_builtins", true, "Use shell builtins")
flag.StringVar(&kati.IgnoreOptionalInclude, "ignore_optional_include", "", "If specified, skip reading -include directives start with the specified path.")
}
func writeHeapProfile() {
f, err := os.Create(heapprofile)
if err != nil {
panic(err)
}
pprof.WriteHeapProfile(f)
f.Close()
}
type memStatsDumper struct {
*template.Template
}
func (t memStatsDumper) dump() {
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
var buf bytes.Buffer
err := t.Template.Execute(&buf, ms)
fmt.Println(buf.String())
if err != nil {
panic(err)
}
}
func findPara() string {
switch runtime.GOOS {
case "linux":
katicmd, err := os.Readlink("/proc/self/exe")
if err != nil {
panic(err)
}
return filepath.Join(filepath.Dir(katicmd), "para")
default:
panic(fmt.Sprintf("unknown OS: %s", runtime.GOOS))
}
}
func load(makefile string, opt kati.LoadOpt) (*kati.DepGraph, error) {
startTime := time.Now()
if loadGOB != "" {
g := kati.LoadDepGraph(loadGOB)
kati.LogStats("deserialize time: %q", time.Since(startTime))
return g, nil
}
if loadJSON != "" {
g := kati.LoadDepGraphFromJSON(loadJSON)
kati.LogStats("deserialize time: %q", time.Since(startTime))
return g, nil
}
return kati.Load(makefile, opt)
}
func save(g *kati.DepGraph, targets []string) {
startTime := time.Now()
if saveGOB != "" {
kati.DumpDepGraph(g, saveGOB, targets)
kati.LogStats("serialize time: %q", time.Since(startTime))
}
if saveJSON != "" {
kati.DumpDepGraphAsJSON(g, saveJSON, targets)
kati.LogStats("serialize time: %q", time.Since(startTime))
}
if useCache && !g.IsCached() {
kati.DumpDepGraphCache(g, targets)
kati.LogStats("serialize time: %q", time.Since(startTime))
}
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Parse()
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
panic(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
kati.AtError(pprof.StopCPUProfile)
}
if heapprofile != "" {
defer writeHeapProfile()
kati.AtError(writeHeapProfile)
}
defer kati.DumpStats()
kati.AtError(kati.DumpStats)
if memstats != "" {
ms := memStatsDumper{
Template: template.Must(template.New("memstats").Parse(memstats)),
}
ms.dump()
defer ms.dump()
kati.AtError(ms.dump)
}
if traceEventFile != "" {
f, err := os.Create(traceEventFile)
if err != nil {
panic(err)
}
kati.TraceEventStart(f)
defer kati.TraceEventStop()
kati.AtError(kati.TraceEventStop)
}
if shellDate != "" {
if shellDate == "ref" {
shellDate = shellDateTimeformat[:20] // until Z, drop 07:00
}
t, err := time.Parse(shellDateTimeformat, shellDate)
if err != nil {
panic(err)
}
kati.ShellDateTimestamp = t
}
var leafNames []string
if findCacheLeafNames != "" {
leafNames = strings.Fields(findCacheLeafNames)
}
if findCachePrunes != "" {
kati.UseFindCache = true
kati.AndroidFindCacheInit(strings.Fields(findCachePrunes), leafNames)
}
clvars, targets := kati.ParseCommandLine(flag.Args())
g, err := load(makefileFlag, kati.LoadOpt{
Targets: targets,
CommandLineVars: clvars,
EnvironmentVars: os.Environ(),
UseCache: useCache,
})
if err != nil {
panic(err)
}
nodes := g.Nodes()
vars := g.Vars()
if eagerCmdEvalFlag {
startTime := time.Now()
kati.EvalCommands(nodes, vars)
kati.LogStats("eager eval command time: %q", time.Since(startTime))
}
save(g, targets)
if generateNinja {
startTime := time.Now()
kati.GenerateNinja(g, gomaDir)
kati.LogStats("generate ninja time: %q", time.Since(startTime))
return
}
if syntaxCheckOnlyFlag {
return
}
if queryFlag != "" {
kati.HandleQuery(queryFlag, g)
return
}
// TODO: Handle target specific variables.
ev := kati.NewEvaluator(vars)
for name, export := range g.Exports() {
if export {
os.Setenv(name, ev.EvaluateVar(name))
} else {
os.Unsetenv(name)
}
}
startTime := time.Now()
execOpt := &kati.ExecutorOpt{
NumJobs: jobsFlag,
}
if usePara {
execOpt.ParaPath = findPara()
}
ex := kati.NewExecutor(vars, execOpt)
err = ex.Exec(nodes)
if err != nil {
panic(err)
}
kati.LogStats("exec time: %q", time.Since(startTime))
}
|