blob: 4a49d556a743e8e74a7bc38a198b58fed75de952 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
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
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross6a745c62015-06-16 16:38:10 -070019 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070020 "reflect"
21 "strings"
22
23 "github.com/google/blueprint"
24 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080025)
26
Dan Willemsen34cc69e2015-09-23 15:26:20 -070027// PathContext is the subset of a (Module|Singleton)Context required by the
28// Path methods.
29type PathContext interface {
Colin Cross294941b2017-02-01 14:10:36 -080030 Fs() pathtools.FileSystem
Dan Willemsen34cc69e2015-09-23 15:26:20 -070031 Config() interface{}
Dan Willemsen7b310ee2015-12-18 15:11:17 -080032 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080033}
34
Colin Cross7f19f372016-11-01 11:10:25 -070035type PathGlobContext interface {
36 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
37}
38
Dan Willemsen34cc69e2015-09-23 15:26:20 -070039var _ PathContext = blueprint.SingletonContext(nil)
40var _ PathContext = blueprint.ModuleContext(nil)
41
Dan Willemsen00269f22017-07-06 16:59:48 -070042type ModuleInstallPathContext interface {
43 PathContext
44
45 androidBaseContext
46
47 InstallInData() bool
48 InstallInSanitizerDir() bool
49}
50
51var _ ModuleInstallPathContext = ModuleContext(nil)
52
Dan Willemsen34cc69e2015-09-23 15:26:20 -070053// errorfContext is the interface containing the Errorf method matching the
54// Errorf method in blueprint.SingletonContext.
55type errorfContext interface {
56 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080057}
58
Dan Willemsen34cc69e2015-09-23 15:26:20 -070059var _ errorfContext = blueprint.SingletonContext(nil)
60
61// moduleErrorf is the interface containing the ModuleErrorf method matching
62// the ModuleErrorf method in blueprint.ModuleContext.
63type moduleErrorf interface {
64 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080065}
66
Dan Willemsen34cc69e2015-09-23 15:26:20 -070067var _ moduleErrorf = blueprint.ModuleContext(nil)
68
69// pathConfig returns the android Config interface associated to the context.
70// Panics if the context isn't affiliated with an android build.
71func pathConfig(ctx PathContext) Config {
72 if ret, ok := ctx.Config().(Config); ok {
73 return ret
74 }
75 panic("Paths may only be used on Soong builds")
Colin Cross3f40fa42015-01-30 17:27:36 -080076}
77
Dan Willemsen34cc69e2015-09-23 15:26:20 -070078// reportPathError will register an error with the attached context. It
79// attempts ctx.ModuleErrorf for a better error message first, then falls
80// back to ctx.Errorf.
81func reportPathError(ctx PathContext, format string, args ...interface{}) {
82 if mctx, ok := ctx.(moduleErrorf); ok {
83 mctx.ModuleErrorf(format, args...)
84 } else if ectx, ok := ctx.(errorfContext); ok {
85 ectx.Errorf(format, args...)
86 } else {
87 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070088 }
89}
90
Dan Willemsen34cc69e2015-09-23 15:26:20 -070091type Path interface {
92 // Returns the path in string form
93 String() string
94
Colin Cross4f6fc9c2016-10-26 10:05:25 -070095 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -070096 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -070097
98 // Base returns the last element of the path
99 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800100
101 // Rel returns the portion of the path relative to the directory it was created from. For
102 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
103 // directory.
104 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700105}
106
107// WritablePath is a type of path that can be used as an output for build rules.
108type WritablePath interface {
109 Path
110
Jeff Gaston734e3802017-04-10 15:47:24 -0700111 // the writablePath method doesn't directly do anything,
112 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700113 writablePath()
114}
115
116type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700117 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700118}
119type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700120 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700121}
122type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700123 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700124}
125
126// GenPathWithExt derives a new file path in ctx's generated sources directory
127// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700128func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700129 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700130 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131 }
132 reportPathError(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
133 return PathForModuleGen(ctx)
134}
135
136// ObjPathWithExt derives a new file path in ctx's object directory from the
137// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700138func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700139 if path, ok := p.(objPathProvider); ok {
140 return path.objPathWithExt(ctx, subdir, ext)
141 }
142 reportPathError(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
143 return PathForModuleObj(ctx)
144}
145
146// ResPathWithName derives a new path in ctx's output resource directory, using
147// the current path to create the directory name, and the `name` argument for
148// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700149func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700150 if path, ok := p.(resPathProvider); ok {
151 return path.resPathWithName(ctx, name)
152 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700153 reportPathError(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700154 return PathForModuleRes(ctx)
155}
156
157// OptionalPath is a container that may or may not contain a valid Path.
158type OptionalPath struct {
159 valid bool
160 path Path
161}
162
163// OptionalPathForPath returns an OptionalPath containing the path.
164func OptionalPathForPath(path Path) OptionalPath {
165 if path == nil {
166 return OptionalPath{}
167 }
168 return OptionalPath{valid: true, path: path}
169}
170
171// Valid returns whether there is a valid path
172func (p OptionalPath) Valid() bool {
173 return p.valid
174}
175
176// Path returns the Path embedded in this OptionalPath. You must be sure that
177// there is a valid path, since this method will panic if there is not.
178func (p OptionalPath) Path() Path {
179 if !p.valid {
180 panic("Requesting an invalid path")
181 }
182 return p.path
183}
184
185// String returns the string version of the Path, or "" if it isn't valid.
186func (p OptionalPath) String() string {
187 if p.valid {
188 return p.path.String()
189 } else {
190 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700191 }
192}
Colin Cross6e18ca42015-07-14 18:55:36 -0700193
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700194// Paths is a slice of Path objects, with helpers to operate on the collection.
195type Paths []Path
196
197// PathsForSource returns Paths rooted from SrcDir
198func PathsForSource(ctx PathContext, paths []string) Paths {
Dan Willemsene23dfb72016-03-11 15:02:46 -0800199 if pathConfig(ctx).AllowMissingDependencies() {
Colin Cross635c3b02016-05-18 15:37:25 -0700200 if modCtx, ok := ctx.(ModuleContext); ok {
Dan Willemsene23dfb72016-03-11 15:02:46 -0800201 ret := make(Paths, 0, len(paths))
Dan Willemsen0f6042e2016-03-11 17:01:03 -0800202 intermediates := filepath.Join(modCtx.ModuleDir(), modCtx.ModuleName(), modCtx.ModuleSubDir(), "missing")
Dan Willemsene23dfb72016-03-11 15:02:46 -0800203 for _, path := range paths {
Jeff Gaston734e3802017-04-10 15:47:24 -0700204 p := ExistentPathForSource(ctx, intermediates, path)
Dan Willemsene23dfb72016-03-11 15:02:46 -0800205 if p.Valid() {
206 ret = append(ret, p.Path())
207 } else {
208 modCtx.AddMissingDependencies([]string{path})
209 }
210 }
211 return ret
212 }
213 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700214 ret := make(Paths, len(paths))
215 for i, path := range paths {
216 ret[i] = PathForSource(ctx, path)
217 }
218 return ret
219}
220
Jeff Gaston734e3802017-04-10 15:47:24 -0700221// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800222// found in the tree. If any are not found, they are omitted from the list,
223// and dependencies are added so that we're re-run when they are added.
Jeff Gaston734e3802017-04-10 15:47:24 -0700224func ExistentPathsForSources(ctx PathContext, intermediates string, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800225 ret := make(Paths, 0, len(paths))
226 for _, path := range paths {
Jeff Gaston734e3802017-04-10 15:47:24 -0700227 p := ExistentPathForSource(ctx, intermediates, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800228 if p.Valid() {
229 ret = append(ret, p.Path())
230 }
231 }
232 return ret
233}
234
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700235// PathsForModuleSrc returns Paths rooted from the module's local source
236// directory
Colin Cross635c3b02016-05-18 15:37:25 -0700237func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700238 ret := make(Paths, len(paths))
239 for i, path := range paths {
240 ret[i] = PathForModuleSrc(ctx, path)
241 }
242 return ret
243}
244
245// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
246// source directory, but strip the local source directory from the beginning of
247// each string.
Colin Cross635c3b02016-05-18 15:37:25 -0700248func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700249 prefix := filepath.Join(ctx.AConfig().srcDir, ctx.ModuleDir()) + "/"
250 ret := make(Paths, 0, len(paths))
251 for _, p := range paths {
252 path := filepath.Clean(p)
253 if !strings.HasPrefix(path, prefix) {
254 reportPathError(ctx, "Path '%s' is not in module source directory '%s'", p, prefix)
255 continue
256 }
257 ret = append(ret, PathForModuleSrc(ctx, path[len(prefix):]))
258 }
259 return ret
260}
261
262// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
263// local source directory. If none are provided, use the default if it exists.
Colin Cross635c3b02016-05-18 15:37:25 -0700264func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700265 if len(input) > 0 {
266 return PathsForModuleSrc(ctx, input)
267 }
268 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
269 // is created, we're run again.
270 path := filepath.Join(ctx.AConfig().srcDir, ctx.ModuleDir(), def)
Colin Cross7f19f372016-11-01 11:10:25 -0700271 return ctx.Glob(path, []string{})
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700272}
273
274// Strings returns the Paths in string form
275func (p Paths) Strings() []string {
276 if p == nil {
277 return nil
278 }
279 ret := make([]string, len(p))
280 for i, path := range p {
281 ret[i] = path.String()
282 }
283 return ret
284}
285
Dan Willemsenfe92c962017-08-29 12:28:37 -0700286// FirstUniqueElements returns all unique elements of a slice, keeping the first copy of each
287// modifies the slice contents in place, and returns a subslice of the original slice
288func FirstUniquePaths(list Paths) Paths {
289 k := 0
290outer:
291 for i := 0; i < len(list); i++ {
292 for j := 0; j < k; j++ {
293 if list[i] == list[j] {
294 continue outer
295 }
296 }
297 list[k] = list[i]
298 k++
299 }
300 return list[:k]
301}
302
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700303// WritablePaths is a slice of WritablePaths, used for multiple outputs.
304type WritablePaths []WritablePath
305
306// Strings returns the string forms of the writable paths.
307func (p WritablePaths) Strings() []string {
308 if p == nil {
309 return nil
310 }
311 ret := make([]string, len(p))
312 for i, path := range p {
313 ret[i] = path.String()
314 }
315 return ret
316}
317
318type basePath struct {
319 path string
320 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800321 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700322}
323
324func (p basePath) Ext() string {
325 return filepath.Ext(p.path)
326}
327
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700328func (p basePath) Base() string {
329 return filepath.Base(p.path)
330}
331
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800332func (p basePath) Rel() string {
333 if p.rel != "" {
334 return p.rel
335 }
336 return p.path
337}
338
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700339// SourcePath is a Path representing a file path rooted from SrcDir
340type SourcePath struct {
341 basePath
342}
343
344var _ Path = SourcePath{}
345
346// safePathForSource is for paths that we expect are safe -- only for use by go
347// code that is embedding ninja variables in paths
348func safePathForSource(ctx PathContext, path string) SourcePath {
349 p := validateSafePath(ctx, path)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800350 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700351
352 abs, err := filepath.Abs(ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700353 if err != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700354 reportPathError(ctx, "%s", err.Error())
355 return ret
356 }
357 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
358 if err != nil {
359 reportPathError(ctx, "%s", err.Error())
360 return ret
361 }
362 if strings.HasPrefix(abs, buildroot) {
363 reportPathError(ctx, "source path %s is in output", abs)
364 return ret
Colin Cross6e18ca42015-07-14 18:55:36 -0700365 }
366
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700367 return ret
368}
369
Jeff Gaston734e3802017-04-10 15:47:24 -0700370// PathForSource joins the provided path components and validates that the result
371// neither escapes the source dir nor is in the out dir.
372// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
373func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
374 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800375 ret := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700376
377 abs, err := filepath.Abs(ret.String())
378 if err != nil {
379 reportPathError(ctx, "%s", err.Error())
380 return ret
381 }
382 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
383 if err != nil {
384 reportPathError(ctx, "%s", err.Error())
385 return ret
386 }
387 if strings.HasPrefix(abs, buildroot) {
388 reportPathError(ctx, "source path %s is in output", abs)
389 return ret
390 }
391
Colin Cross294941b2017-02-01 14:10:36 -0800392 if exists, _, err := ctx.Fs().Exists(ret.String()); err != nil {
393 reportPathError(ctx, "%s: %s", ret, err.Error())
394 } else if !exists {
395 reportPathError(ctx, "source path %s does not exist", ret)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700396 }
397 return ret
398}
399
Jeff Gaston734e3802017-04-10 15:47:24 -0700400// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700401// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
402// so that the ninja file will be regenerated if the state of the path changes.
Jeff Gaston734e3802017-04-10 15:47:24 -0700403func ExistentPathForSource(ctx PathContext, intermediates string, pathComponents ...string) OptionalPath {
404 if len(pathComponents) == 0 {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800405 // For when someone forgets the 'intermediates' argument
406 panic("Missing path(s)")
407 }
408
Jeff Gaston734e3802017-04-10 15:47:24 -0700409 p := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800410 path := SourcePath{basePath{p, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700411
412 abs, err := filepath.Abs(path.String())
413 if err != nil {
414 reportPathError(ctx, "%s", err.Error())
415 return OptionalPath{}
416 }
417 buildroot, err := filepath.Abs(pathConfig(ctx).buildDir)
418 if err != nil {
419 reportPathError(ctx, "%s", err.Error())
420 return OptionalPath{}
421 }
422 if strings.HasPrefix(abs, buildroot) {
423 reportPathError(ctx, "source path %s is in output", abs)
424 return OptionalPath{}
425 }
426
Colin Cross7f19f372016-11-01 11:10:25 -0700427 if pathtools.IsGlob(path.String()) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800428 reportPathError(ctx, "path may not contain a glob: %s", path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700429 return OptionalPath{}
430 }
431
Colin Cross7f19f372016-11-01 11:10:25 -0700432 if gctx, ok := ctx.(PathGlobContext); ok {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800433 // Use glob to produce proper dependencies, even though we only want
434 // a single file.
Colin Cross7f19f372016-11-01 11:10:25 -0700435 files, err := gctx.GlobWithDeps(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800436 if err != nil {
437 reportPathError(ctx, "glob: %s", err.Error())
438 return OptionalPath{}
439 }
440
441 if len(files) == 0 {
442 return OptionalPath{}
443 }
444 } else {
445 // We cannot add build statements in this context, so we fall back to
446 // AddNinjaFileDeps
Colin Cross294941b2017-02-01 14:10:36 -0800447 files, dirs, err := pathtools.Glob(path.String(), nil)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800448 if err != nil {
449 reportPathError(ctx, "glob: %s", err.Error())
450 return OptionalPath{}
451 }
452
453 ctx.AddNinjaFileDeps(dirs...)
454
455 if len(files) == 0 {
456 return OptionalPath{}
457 }
458
459 ctx.AddNinjaFileDeps(path.String())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700460 }
461 return OptionalPathForPath(path)
462}
463
464func (p SourcePath) String() string {
465 return filepath.Join(p.config.srcDir, p.path)
466}
467
468// Join creates a new SourcePath with paths... joined with the current path. The
469// provided paths... may not use '..' to escape from the current path.
470func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
471 path := validatePath(ctx, paths...)
472 return PathForSource(ctx, p.path, path)
473}
474
475// OverlayPath returns the overlay for `path' if it exists. This assumes that the
476// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700477func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700478 var relDir string
479 if moduleSrcPath, ok := path.(ModuleSrcPath); ok {
Colin Cross7fc17db2017-02-01 14:07:55 -0800480 relDir = moduleSrcPath.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700481 } else if srcPath, ok := path.(SourcePath); ok {
482 relDir = srcPath.path
483 } else {
484 reportPathError(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
485 return OptionalPath{}
486 }
487 dir := filepath.Join(p.config.srcDir, p.path, relDir)
488 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700489 if pathtools.IsGlob(dir) {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800490 reportPathError(ctx, "Path may not contain a glob: %s", dir)
491 }
Colin Cross7f19f372016-11-01 11:10:25 -0700492 paths, err := ctx.GlobWithDeps(dir, []string{})
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700493 if err != nil {
494 reportPathError(ctx, "glob: %s", err.Error())
495 return OptionalPath{}
496 }
497 if len(paths) == 0 {
498 return OptionalPath{}
499 }
500 relPath, err := filepath.Rel(p.config.srcDir, paths[0])
501 if err != nil {
502 reportPathError(ctx, "%s", err.Error())
503 return OptionalPath{}
504 }
505 return OptionalPathForPath(PathForSource(ctx, relPath))
506}
507
508// OutputPath is a Path representing a file path rooted from the build directory
509type OutputPath struct {
510 basePath
511}
512
513var _ Path = OutputPath{}
514
Jeff Gaston734e3802017-04-10 15:47:24 -0700515// PathForOutput joins the provided paths and returns an OutputPath that is
516// validated to not escape the build dir.
517// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
518func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
519 path := validatePath(ctx, pathComponents...)
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800520 return OutputPath{basePath{path, pathConfig(ctx), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700521}
522
523func (p OutputPath) writablePath() {}
524
525func (p OutputPath) String() string {
526 return filepath.Join(p.config.buildDir, p.path)
527}
528
Colin Crossa2344662016-03-24 13:14:12 -0700529func (p OutputPath) RelPathString() string {
530 return p.path
531}
532
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700533// Join creates a new OutputPath with paths... joined with the current path. The
534// provided paths... may not use '..' to escape from the current path.
535func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
536 path := validatePath(ctx, paths...)
537 return PathForOutput(ctx, p.path, path)
538}
539
540// PathForIntermediates returns an OutputPath representing the top-level
541// intermediates directory.
542func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
543 path := validatePath(ctx, paths...)
544 return PathForOutput(ctx, ".intermediates", path)
545}
546
547// ModuleSrcPath is a Path representing a file rooted from a module's local source dir
548type ModuleSrcPath struct {
Colin Cross7fc17db2017-02-01 14:07:55 -0800549 SourcePath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700550}
551
552var _ Path = ModuleSrcPath{}
553var _ genPathProvider = ModuleSrcPath{}
554var _ objPathProvider = ModuleSrcPath{}
555var _ resPathProvider = ModuleSrcPath{}
556
557// PathForModuleSrc returns a ModuleSrcPath representing the paths... under the
558// module's local source directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700559func PathForModuleSrc(ctx ModuleContext, paths ...string) ModuleSrcPath {
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800560 p := validatePath(ctx, paths...)
561 path := ModuleSrcPath{PathForSource(ctx, ctx.ModuleDir(), p)}
562 path.basePath.rel = p
563 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700564}
565
566// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
567// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700568func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700569 if p == nil {
570 return OptionalPath{}
571 }
572 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
573}
574
Dan Willemsen21ec4902016-11-02 20:43:13 -0700575func (p ModuleSrcPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800576 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700577}
578
Colin Cross635c3b02016-05-18 15:37:25 -0700579func (p ModuleSrcPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800580 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700581}
582
Colin Cross635c3b02016-05-18 15:37:25 -0700583func (p ModuleSrcPath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700584 // TODO: Use full directory if the new ctx is not the current ctx?
585 return PathForModuleRes(ctx, p.path, name)
586}
587
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800588func (p ModuleSrcPath) WithSubDir(ctx ModuleContext, subdir string) ModuleSrcPath {
589 subdir = PathForModuleSrc(ctx, subdir).String()
590 var err error
591 rel, err := filepath.Rel(subdir, p.path)
592 if err != nil {
593 ctx.ModuleErrorf("source file %q is not under path %q", p.path, subdir)
594 return p
595 }
596 p.rel = rel
597 return p
598}
599
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700600// ModuleOutPath is a Path representing a module's output directory.
601type ModuleOutPath struct {
602 OutputPath
603}
604
605var _ Path = ModuleOutPath{}
606
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800607// PathForVndkRefDump returns an OptionalPath representing the path of the reference
608// abi dump for the given module. This is not guaranteed to be valid.
609func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string, vndkOrNdk, isSourceDump bool) OptionalPath {
610 archName := ctx.Arch().ArchType.Name
611 var sourceOrBinaryDir string
612 var vndkOrNdkDir string
613 var ext string
614 if isSourceDump {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700615 ext = ".lsdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800616 sourceOrBinaryDir = "source-based"
617 } else {
Jayant Chowdhary715cac32017-04-20 06:53:59 -0700618 ext = ".bdump.gz"
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800619 sourceOrBinaryDir = "binary-based"
620 }
621 if vndkOrNdk {
622 vndkOrNdkDir = "vndk"
623 } else {
624 vndkOrNdkDir = "ndk"
625 }
626 refDumpFileStr := "prebuilts/abi-dumps/" + vndkOrNdkDir + "/" + version + "/" +
627 archName + "/" + sourceOrBinaryDir + "/" + fileName + ext
Jeff Gaston734e3802017-04-10 15:47:24 -0700628 return ExistentPathForSource(ctx, "", refDumpFileStr)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -0800629}
630
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700631// PathForModuleOut returns a Path representing the paths... under the module's
632// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700633func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700634 p := validatePath(ctx, paths...)
635 return ModuleOutPath{PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir(), p)}
636}
637
638// ModuleGenPath is a Path representing the 'gen' directory in a module's output
639// directory. Mainly used for generated sources.
640type ModuleGenPath struct {
641 ModuleOutPath
642 path string
643}
644
645var _ Path = ModuleGenPath{}
646var _ genPathProvider = ModuleGenPath{}
647var _ objPathProvider = ModuleGenPath{}
648
649// PathForModuleGen returns a Path representing the paths... under the module's
650// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700651func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700652 p := validatePath(ctx, paths...)
653 return ModuleGenPath{
654 PathForModuleOut(ctx, "gen", p),
655 p,
656 }
657}
658
Dan Willemsen21ec4902016-11-02 20:43:13 -0700659func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700660 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -0700661 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700662}
663
Colin Cross635c3b02016-05-18 15:37:25 -0700664func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700665 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
666}
667
668// ModuleObjPath is a Path representing the 'obj' directory in a module's output
669// directory. Used for compiled objects.
670type ModuleObjPath struct {
671 ModuleOutPath
672}
673
674var _ Path = ModuleObjPath{}
675
676// PathForModuleObj returns a Path representing the paths... under the module's
677// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700678func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
679 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700680 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
681}
682
683// ModuleResPath is a a Path representing the 'res' directory in a module's
684// output directory.
685type ModuleResPath struct {
686 ModuleOutPath
687}
688
689var _ Path = ModuleResPath{}
690
691// PathForModuleRes returns a Path representing the paths... under the module's
692// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -0700693func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
694 p := validatePath(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700695 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
696}
697
698// PathForModuleInstall returns a Path representing the install path for the
699// module appended with paths...
Dan Willemsen00269f22017-07-06 16:59:48 -0700700func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) OutputPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700701 var outPaths []string
702 if ctx.Device() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700703 var partition string
Dan Willemsen00269f22017-07-06 16:59:48 -0700704 if ctx.InstallInData() {
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700705 partition = "data"
Dan Willemsen00269f22017-07-06 16:59:48 -0700706 } else if ctx.Vendor() {
707 partition = ctx.DeviceConfig().VendorPath()
Vishwath Mohan87f3b242017-06-07 12:31:57 -0700708 } else {
709 partition = "system"
Dan Willemsen782a2d12015-12-21 14:55:28 -0800710 }
Vishwath Mohan1dd88392017-03-29 22:00:18 -0700711
712 if ctx.InstallInSanitizerDir() {
713 partition = "data/asan/" + partition
Dan Willemsen782a2d12015-12-21 14:55:28 -0800714 }
715 outPaths = []string{"target", "product", ctx.AConfig().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700716 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -0700717 switch ctx.Os() {
718 case Linux:
719 outPaths = []string{"host", "linux-x86"}
720 case LinuxBionic:
721 // TODO: should this be a separate top level, or shared with linux-x86?
722 outPaths = []string{"host", "linux_bionic-x86"}
723 default:
724 outPaths = []string{"host", ctx.Os().String() + "-x86"}
725 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700726 }
Dan Willemsen782a2d12015-12-21 14:55:28 -0800727 if ctx.Debug() {
728 outPaths = append([]string{"debug"}, outPaths...)
729 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700730 outPaths = append(outPaths, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700731 return PathForOutput(ctx, outPaths...)
732}
733
734// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800735// Ensures that each path component does not attempt to leave its component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700736func validateSafePath(ctx PathContext, pathComponents ...string) string {
737 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800738 path := filepath.Clean(path)
739 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
740 reportPathError(ctx, "Path is outside directory: %s", path)
741 return ""
742 }
743 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700744 // TODO: filepath.Join isn't necessarily correct with embedded ninja
745 // variables. '..' may remove the entire ninja variable, even if it
746 // will be expanded to multiple nested directories.
Jeff Gaston734e3802017-04-10 15:47:24 -0700747 return filepath.Join(pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700748}
749
Dan Willemsen80a7c2a2015-12-21 14:57:11 -0800750// validatePath validates that a path does not include ninja variables, and that
751// each path component does not attempt to leave its component. Returns a joined
752// version of each path component.
Jeff Gaston734e3802017-04-10 15:47:24 -0700753func validatePath(ctx PathContext, pathComponents ...string) string {
754 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700755 if strings.Contains(path, "$") {
756 reportPathError(ctx, "Path contains invalid character($): %s", path)
757 return ""
758 }
759 }
Jeff Gaston734e3802017-04-10 15:47:24 -0700760 return validateSafePath(ctx, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -0700761}
Colin Cross5b529592017-05-09 13:34:34 -0700762
763type testPath struct {
764 basePath
765}
766
767func (p testPath) String() string {
768 return p.path
769}
770
771func PathForTesting(paths ...string) Path {
772 p := validateSafePath(nil, paths...)
773 return testPath{basePath{path: p, rel: p}}
774}
775
776func PathsForTesting(strs []string) Paths {
777 p := make(Paths, len(strs))
778 for i, s := range strs {
779 p[i] = PathForTesting(s)
780 }
781
782 return p
783}