blob: 37504b62f39b4b502426b65c38761a23d43b13c5 [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 Cross988414c2020-01-11 01:11:46 +000019 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070020 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070021 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070022 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
Colin Cross0e446152021-05-03 13:35:32 -070027 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
Colin Cross662d6142022-11-03 20:38:01 -070041 PathContext
Colin Cross7f19f372016-11-01 11:10:25 -070042 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
43}
44
Colin Crossaabf6792017-11-29 00:27:14 -080045var _ PathContext = SingletonContext(nil)
46var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070047
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010048// "Null" path context is a minimal path context for a given config.
49type NullPathContext struct {
50 config Config
51}
52
53func (NullPathContext) AddNinjaFileDeps(...string) {}
54func (ctx NullPathContext) Config() Config { return ctx.config }
55
Liz Kammera830f3a2020-11-10 10:50:34 -080056// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
57// Path methods. These path methods can be called before any mutators have run.
58type EarlyModulePathContext interface {
Liz Kammera830f3a2020-11-10 10:50:34 -080059 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
63}
64
65var _ EarlyModulePathContext = ModuleContext(nil)
66
67// Glob globs files and directories matching globPattern relative to ModuleDir(),
68// paths in the excludes parameter will be omitted.
69func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
70 ret, err := ctx.GlobWithDeps(globPattern, excludes)
71 if err != nil {
72 ctx.ModuleErrorf("glob: %s", err.Error())
73 }
74 return pathsForModuleSrcFromFullPath(ctx, ret, true)
75}
76
77// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
78// Paths in the excludes parameter will be omitted.
79func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
80 ret, err := ctx.GlobWithDeps(globPattern, excludes)
81 if err != nil {
82 ctx.ModuleErrorf("glob: %s", err.Error())
83 }
84 return pathsForModuleSrcFromFullPath(ctx, ret, false)
85}
86
87// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
88// the Path methods that rely on module dependencies having been resolved.
89type ModuleWithDepsPathContext interface {
90 EarlyModulePathContext
Paul Duffin40131a32021-07-09 17:10:35 +010091 VisitDirectDepsBlueprint(visit func(blueprint.Module))
92 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Liz Kammera830f3a2020-11-10 10:50:34 -080093}
94
95// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
96// the Path methods that rely on module dependencies having been resolved and ability to report
97// missing dependency errors.
98type ModuleMissingDepsPathContext interface {
99 ModuleWithDepsPathContext
100 AddMissingDependencies(missingDeps []string)
101}
102
Dan Willemsen00269f22017-07-06 16:59:48 -0700103type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700104 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700105
106 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700107 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700108 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800109 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700110 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900111 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900112 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700113 InstallInRoot() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900114 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700115}
116
117var _ ModuleInstallPathContext = ModuleContext(nil)
118
Cole Faust11edf552023-10-13 11:32:14 -0700119type baseModuleContextToModuleInstallPathContext struct {
120 BaseModuleContext
121}
122
123func (ctx *baseModuleContextToModuleInstallPathContext) InstallInData() bool {
124 return ctx.Module().InstallInData()
125}
126
127func (ctx *baseModuleContextToModuleInstallPathContext) InstallInTestcases() bool {
128 return ctx.Module().InstallInTestcases()
129}
130
131func (ctx *baseModuleContextToModuleInstallPathContext) InstallInSanitizerDir() bool {
132 return ctx.Module().InstallInSanitizerDir()
133}
134
135func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRamdisk() bool {
136 return ctx.Module().InstallInRamdisk()
137}
138
139func (ctx *baseModuleContextToModuleInstallPathContext) InstallInVendorRamdisk() bool {
140 return ctx.Module().InstallInVendorRamdisk()
141}
142
143func (ctx *baseModuleContextToModuleInstallPathContext) InstallInDebugRamdisk() bool {
144 return ctx.Module().InstallInDebugRamdisk()
145}
146
147func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRecovery() bool {
148 return ctx.Module().InstallInRecovery()
149}
150
151func (ctx *baseModuleContextToModuleInstallPathContext) InstallInRoot() bool {
152 return ctx.Module().InstallInRoot()
153}
154
155func (ctx *baseModuleContextToModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
156 return ctx.Module().InstallForceOS()
157}
158
159var _ ModuleInstallPathContext = (*baseModuleContextToModuleInstallPathContext)(nil)
160
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700161// errorfContext is the interface containing the Errorf method matching the
162// Errorf method in blueprint.SingletonContext.
163type errorfContext interface {
164 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800165}
166
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700167var _ errorfContext = blueprint.SingletonContext(nil)
168
169// moduleErrorf is the interface containing the ModuleErrorf method matching
170// the ModuleErrorf method in blueprint.ModuleContext.
171type moduleErrorf interface {
172 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800173}
174
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700175var _ moduleErrorf = blueprint.ModuleContext(nil)
176
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700177// reportPathError will register an error with the attached context. It
178// attempts ctx.ModuleErrorf for a better error message first, then falls
179// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800180func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100181 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800182}
183
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100184// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800185// attempts ctx.ModuleErrorf for a better error message first, then falls
186// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100187func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700188 if mctx, ok := ctx.(moduleErrorf); ok {
189 mctx.ModuleErrorf(format, args...)
190 } else if ectx, ok := ctx.(errorfContext); ok {
191 ectx.Errorf(format, args...)
192 } else {
193 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700194 }
195}
196
Colin Cross5e708052019-08-06 13:59:50 -0700197func pathContextName(ctx PathContext, module blueprint.Module) string {
198 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
199 return x.ModuleName(module)
200 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
201 return x.OtherModuleName(module)
202 }
203 return "unknown"
204}
205
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700206type Path interface {
207 // Returns the path in string form
208 String() string
209
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700210 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700211 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700212
213 // Base returns the last element of the path
214 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800215
216 // Rel returns the portion of the path relative to the directory it was created from. For
217 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800218 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800219 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000220
221 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
222 //
223 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
224 // InstallPath then the returned value can be converted to an InstallPath.
225 //
226 // A standard build has the following structure:
227 // ../top/
228 // out/ - make install files go here.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200229 // out/soong - this is the soongOutDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000230 // ... - the source files
231 //
232 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200233 // * Make install paths, which have the pattern "soongOutDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000234 // relative path "out/<path>"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200235 // * Soong install paths and other writable paths, which have the pattern "soongOutDir/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000236 // converted into the top relative path "out/soong/<path>".
237 // * Source paths are already relative to the top.
238 // * Phony paths are not relative to anything.
239 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
240 // order to test.
241 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700242}
243
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000244const (
245 OutDir = "out"
246 OutSoongDir = OutDir + "/soong"
247)
248
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700249// WritablePath is a type of path that can be used as an output for build rules.
250type WritablePath interface {
251 Path
252
Paul Duffin9b478b02019-12-10 13:41:51 +0000253 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200254 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000255
Jeff Gaston734e3802017-04-10 15:47:24 -0700256 // the writablePath method doesn't directly do anything,
257 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700258 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100259
260 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700261}
262
263type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800264 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700265}
266type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800267 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700268}
269type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800270 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700271}
272
273// GenPathWithExt derives a new file path in ctx's generated sources directory
274// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800275func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700276 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700277 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700278 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100279 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700280 return PathForModuleGen(ctx)
281}
282
283// ObjPathWithExt derives a new file path in ctx's object directory from the
284// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800285func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700286 if path, ok := p.(objPathProvider); ok {
287 return path.objPathWithExt(ctx, subdir, ext)
288 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100289 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700290 return PathForModuleObj(ctx)
291}
292
293// ResPathWithName derives a new path in ctx's output resource directory, using
294// the current path to create the directory name, and the `name` argument for
295// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800296func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700297 if path, ok := p.(resPathProvider); ok {
298 return path.resPathWithName(ctx, name)
299 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100300 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700301 return PathForModuleRes(ctx)
302}
303
304// OptionalPath is a container that may or may not contain a valid Path.
305type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100306 path Path // nil if invalid.
307 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700308}
309
310// OptionalPathForPath returns an OptionalPath containing the path.
311func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100312 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700313}
314
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100315// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
316func InvalidOptionalPath(reason string) OptionalPath {
317
318 return OptionalPath{invalidReason: reason}
319}
320
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700321// Valid returns whether there is a valid path
322func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100323 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700324}
325
326// Path returns the Path embedded in this OptionalPath. You must be sure that
327// there is a valid path, since this method will panic if there is not.
328func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100329 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100330 msg := "Requesting an invalid path"
331 if p.invalidReason != "" {
332 msg += ": " + p.invalidReason
333 }
334 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700335 }
336 return p.path
337}
338
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100339// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
340func (p OptionalPath) InvalidReason() string {
341 if p.path != nil {
342 return ""
343 }
344 if p.invalidReason == "" {
345 return "unknown"
346 }
347 return p.invalidReason
348}
349
Paul Duffinef081852021-05-13 11:11:15 +0100350// AsPaths converts the OptionalPath into Paths.
351//
352// It returns nil if this is not valid, or a single length slice containing the Path embedded in
353// this OptionalPath.
354func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100355 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100356 return nil
357 }
358 return Paths{p.path}
359}
360
Paul Duffinafdd4062021-03-30 19:44:07 +0100361// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
362// result of calling Path.RelativeToTop on it.
363func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100364 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100365 return p
366 }
367 p.path = p.path.RelativeToTop()
368 return p
369}
370
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700371// String returns the string version of the Path, or "" if it isn't valid.
372func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100373 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700374 return p.path.String()
375 } else {
376 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700377 }
378}
Colin Cross6e18ca42015-07-14 18:55:36 -0700379
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700380// Paths is a slice of Path objects, with helpers to operate on the collection.
381type Paths []Path
382
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000383// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
384// item in this slice.
385func (p Paths) RelativeToTop() Paths {
386 ensureTestOnly()
387 if p == nil {
388 return p
389 }
390 ret := make(Paths, len(p))
391 for i, path := range p {
392 ret[i] = path.RelativeToTop()
393 }
394 return ret
395}
396
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000397func (paths Paths) containsPath(path Path) bool {
398 for _, p := range paths {
399 if p == path {
400 return true
401 }
402 }
403 return false
404}
405
Liz Kammer7aa52882021-02-11 09:16:14 -0500406// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
407// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700408func PathsForSource(ctx PathContext, paths []string) Paths {
409 ret := make(Paths, len(paths))
410 for i, path := range paths {
411 ret[i] = PathForSource(ctx, path)
412 }
413 return ret
414}
415
Liz Kammer7aa52882021-02-11 09:16:14 -0500416// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
417// module's local source directory, that are found in the tree. If any are not found, they are
418// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross662d6142022-11-03 20:38:01 -0700419func ExistentPathsForSources(ctx PathGlobContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800420 ret := make(Paths, 0, len(paths))
421 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800422 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800423 if p.Valid() {
424 ret = append(ret, p.Path())
425 }
426 }
427 return ret
428}
429
Liz Kammer620dea62021-04-14 17:36:10 -0400430// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700431// - filepath, relative to local module directory, resolves as a filepath relative to the local
432// source directory
433// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
434// source directory.
435// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
436// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
437// filepath.
438//
Liz Kammer620dea62021-04-14 17:36:10 -0400439// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700440// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000441// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400442// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700443// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400444// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700445// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800446func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800447 return PathsForModuleSrcExcludes(ctx, paths, nil)
448}
449
Liz Kammer619be462022-01-28 15:13:39 -0500450type SourceInput struct {
451 Context ModuleMissingDepsPathContext
452 Paths []string
453 ExcludePaths []string
454 IncludeDirs bool
455}
456
Liz Kammer620dea62021-04-14 17:36:10 -0400457// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
458// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700459// - filepath, relative to local module directory, resolves as a filepath relative to the local
460// source directory
461// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
462// source directory. Not valid in excludes.
463// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
464// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
465// filepath.
466//
Liz Kammer620dea62021-04-14 17:36:10 -0400467// excluding the items (similarly resolved
468// Properties passed as the paths argument must have been annotated with struct tag
469// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000470// pathdeps mutator.
Liz Kammer620dea62021-04-14 17:36:10 -0400471// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700472// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400473// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700474// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800475func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500476 return PathsRelativeToModuleSourceDir(SourceInput{
477 Context: ctx,
478 Paths: paths,
479 ExcludePaths: excludes,
480 IncludeDirs: true,
481 })
482}
483
484func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
485 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
486 if input.Context.Config().AllowMissingDependencies() {
487 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700488 } else {
489 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500490 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700491 }
492 }
493 return ret
494}
495
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000496// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
497type OutputPaths []OutputPath
498
499// Paths returns the OutputPaths as a Paths
500func (p OutputPaths) Paths() Paths {
501 if p == nil {
502 return nil
503 }
504 ret := make(Paths, len(p))
505 for i, path := range p {
506 ret[i] = path
507 }
508 return ret
509}
510
511// Strings returns the string forms of the writable paths.
512func (p OutputPaths) Strings() []string {
513 if p == nil {
514 return nil
515 }
516 ret := make([]string, len(p))
517 for i, path := range p {
518 ret[i] = path.String()
519 }
520 return ret
521}
522
Colin Crossa44551f2021-10-25 15:36:21 -0700523// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
524func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
Cole Faust3b703f32023-10-16 13:30:51 -0700525 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin")
Colin Crossa44551f2021-10-25 15:36:21 -0700526 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
527 return goBinaryInstallDir.Join(ctx, rel)
528}
529
Liz Kammera830f3a2020-11-10 10:50:34 -0800530// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
531// If the dependency is not found, a missingErrorDependency is returned.
532// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
533func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100534 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800535 if module == nil {
536 return nil, missingDependencyError{[]string{moduleName}}
537 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700538 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
539 return nil, missingDependencyError{[]string{moduleName}}
540 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800541 if outProducer, ok := module.(OutputFileProducer); ok {
542 outputFiles, err := outProducer.OutputFiles(tag)
543 if err != nil {
544 return nil, fmt.Errorf("path dependency %q: %s", path, err)
545 }
546 return outputFiles, nil
547 } else if tag != "" {
548 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700549 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
Colin Crossa44551f2021-10-25 15:36:21 -0700550 goBinaryPath := PathForGoBinary(ctx, goBinary)
551 return Paths{goBinaryPath}, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800552 } else if srcProducer, ok := module.(SourceFileProducer); ok {
553 return srcProducer.Srcs(), nil
554 } else {
555 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
556 }
557}
558
Paul Duffind5cf92e2021-07-09 17:38:55 +0100559// GetModuleFromPathDep will return the module that was added as a dependency automatically for
560// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
561// ExtractSourcesDeps.
562//
563// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
564// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
565// the tag must be "".
566//
567// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
568// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100569func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100570 var found blueprint.Module
571 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
572 // module name and the tag. Dependencies added automatically for properties tagged with
573 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
574 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
575 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
576 // moduleName referring to the same dependency module.
577 //
578 // It does not matter whether the moduleName is a fully qualified name or if the module
579 // dependency is a prebuilt module. All that matters is the same information is supplied to
580 // create the tag here as was supplied to create the tag when the dependency was added so that
581 // this finds the matching dependency module.
582 expectedTag := sourceOrOutputDepTag(moduleName, tag)
583 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
584 depTag := ctx.OtherModuleDependencyTag(module)
585 if depTag == expectedTag {
586 found = module
587 }
588 })
589 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100590}
591
Liz Kammer620dea62021-04-14 17:36:10 -0400592// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
593// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700594// - filepath, relative to local module directory, resolves as a filepath relative to the local
595// source directory
596// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
597// source directory. Not valid in excludes.
598// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
599// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
600// filepath.
601//
Liz Kammer620dea62021-04-14 17:36:10 -0400602// and a list of the module names of missing module dependencies are returned as the second return.
603// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700604// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000605// pathdeps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500606func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
607 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
608 Context: ctx,
609 Paths: paths,
610 ExcludePaths: excludes,
611 IncludeDirs: true,
612 })
613}
614
615func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
616 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800617
618 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500619 if input.ExcludePaths != nil {
620 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700621 }
Colin Cross8a497952019-03-05 22:25:09 -0800622
Colin Crossba71a3f2019-03-18 12:12:48 -0700623 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500624 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700625 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500626 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800627 if m, ok := err.(missingDependencyError); ok {
628 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
629 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500630 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800631 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800632 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800633 }
634 } else {
635 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
636 }
637 }
638
Liz Kammer619be462022-01-28 15:13:39 -0500639 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700640 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800641 }
642
Colin Crossba71a3f2019-03-18 12:12:48 -0700643 var missingDeps []string
644
Liz Kammer619be462022-01-28 15:13:39 -0500645 expandedSrcFiles := make(Paths, 0, len(input.Paths))
646 for _, s := range input.Paths {
647 srcFiles, err := expandOneSrcPath(sourcePathInput{
648 context: input.Context,
649 path: s,
650 expandedExcludes: expandedExcludes,
651 includeDirs: input.IncludeDirs,
652 })
Colin Cross8a497952019-03-05 22:25:09 -0800653 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700654 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800655 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500656 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800657 }
658 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
659 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700660
661 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800662}
663
664type missingDependencyError struct {
665 missingDeps []string
666}
667
668func (e missingDependencyError) Error() string {
669 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
670}
671
Liz Kammer619be462022-01-28 15:13:39 -0500672type sourcePathInput struct {
673 context ModuleWithDepsPathContext
674 path string
675 expandedExcludes []string
676 includeDirs bool
677}
678
Liz Kammera830f3a2020-11-10 10:50:34 -0800679// Expands one path string to Paths rooted from the module's local source
680// directory, excluding those listed in the expandedExcludes.
681// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500682func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900683 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500684 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900685 return paths
686 }
687 remainder := make(Paths, 0, len(paths))
688 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500689 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900690 remainder = append(remainder, p)
691 }
692 }
693 return remainder
694 }
Liz Kammer619be462022-01-28 15:13:39 -0500695 if m, t := SrcIsModuleWithTag(input.path); m != "" {
696 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800697 if err != nil {
698 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800699 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800700 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800701 }
Colin Cross8a497952019-03-05 22:25:09 -0800702 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500703 p := pathForModuleSrc(input.context, input.path)
704 if pathtools.IsGlob(input.path) {
705 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
706 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
707 } else {
708 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
709 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
710 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
711 ReportPathErrorf(input.context, "module source path %q does not exist", p)
712 } else if !input.includeDirs {
713 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
714 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
715 } else if isDir {
716 ReportPathErrorf(input.context, "module source path %q is a directory", p)
717 }
718 }
Colin Cross8a497952019-03-05 22:25:09 -0800719
Liz Kammer619be462022-01-28 15:13:39 -0500720 if InList(p.String(), input.expandedExcludes) {
721 return nil, nil
722 }
723 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800724 }
Colin Cross8a497952019-03-05 22:25:09 -0800725 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700726}
727
728// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
729// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800730// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700731// It intended for use in globs that only list files that exist, so it allows '$' in
732// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800733func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200734 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700735 if prefix == "./" {
736 prefix = ""
737 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700738 ret := make(Paths, 0, len(paths))
739 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800740 if !incDirs && strings.HasSuffix(p, "/") {
741 continue
742 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700743 path := filepath.Clean(p)
744 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100745 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700746 continue
747 }
Colin Crosse3924e12018-08-15 20:18:53 -0700748
Colin Crossfe4bc362018-09-12 10:02:13 -0700749 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700750 if err != nil {
751 reportPathError(ctx, err)
752 continue
753 }
754
Colin Cross07e51612019-03-05 12:46:40 -0800755 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700756
Colin Cross07e51612019-03-05 12:46:40 -0800757 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700758 }
759 return ret
760}
761
Liz Kammera830f3a2020-11-10 10:50:34 -0800762// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
763// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
764func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800765 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700766 return PathsForModuleSrc(ctx, input)
767 }
768 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
769 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200770 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800771 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700772}
773
774// Strings returns the Paths in string form
775func (p Paths) Strings() []string {
776 if p == nil {
777 return nil
778 }
779 ret := make([]string, len(p))
780 for i, path := range p {
781 ret[i] = path.String()
782 }
783 return ret
784}
785
Colin Crossc0efd1d2020-07-03 11:56:24 -0700786func CopyOfPaths(paths Paths) Paths {
787 return append(Paths(nil), paths...)
788}
789
Colin Crossb6715442017-10-24 11:13:31 -0700790// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
791// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700792func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800793 // 128 was chosen based on BenchmarkFirstUniquePaths results.
794 if len(list) > 128 {
795 return firstUniquePathsMap(list)
796 }
797 return firstUniquePathsList(list)
798}
799
Colin Crossc0efd1d2020-07-03 11:56:24 -0700800// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
801// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900802func SortedUniquePaths(list Paths) Paths {
803 unique := FirstUniquePaths(list)
804 sort.Slice(unique, func(i, j int) bool {
805 return unique[i].String() < unique[j].String()
806 })
807 return unique
808}
809
Colin Cross27027c72020-02-28 15:34:17 -0800810func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700811 k := 0
812outer:
813 for i := 0; i < len(list); i++ {
814 for j := 0; j < k; j++ {
815 if list[i] == list[j] {
816 continue outer
817 }
818 }
819 list[k] = list[i]
820 k++
821 }
822 return list[:k]
823}
824
Colin Cross27027c72020-02-28 15:34:17 -0800825func firstUniquePathsMap(list Paths) Paths {
826 k := 0
827 seen := make(map[Path]bool, len(list))
828 for i := 0; i < len(list); i++ {
829 if seen[list[i]] {
830 continue
831 }
832 seen[list[i]] = true
833 list[k] = list[i]
834 k++
835 }
836 return list[:k]
837}
838
Colin Cross5d583952020-11-24 16:21:24 -0800839// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
840// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
841func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
842 // 128 was chosen based on BenchmarkFirstUniquePaths results.
843 if len(list) > 128 {
844 return firstUniqueInstallPathsMap(list)
845 }
846 return firstUniqueInstallPathsList(list)
847}
848
849func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
850 k := 0
851outer:
852 for i := 0; i < len(list); i++ {
853 for j := 0; j < k; j++ {
854 if list[i] == list[j] {
855 continue outer
856 }
857 }
858 list[k] = list[i]
859 k++
860 }
861 return list[:k]
862}
863
864func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
865 k := 0
866 seen := make(map[InstallPath]bool, len(list))
867 for i := 0; i < len(list); i++ {
868 if seen[list[i]] {
869 continue
870 }
871 seen[list[i]] = true
872 list[k] = list[i]
873 k++
874 }
875 return list[:k]
876}
877
Colin Crossb6715442017-10-24 11:13:31 -0700878// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
879// modifies the Paths slice contents in place, and returns a subslice of the original slice.
880func LastUniquePaths(list Paths) Paths {
881 totalSkip := 0
882 for i := len(list) - 1; i >= totalSkip; i-- {
883 skip := 0
884 for j := i - 1; j >= totalSkip; j-- {
885 if list[i] == list[j] {
886 skip++
887 } else {
888 list[j+skip] = list[j]
889 }
890 }
891 totalSkip += skip
892 }
893 return list[totalSkip:]
894}
895
Colin Crossa140bb02018-04-17 10:52:26 -0700896// ReversePaths returns a copy of a Paths in reverse order.
897func ReversePaths(list Paths) Paths {
898 if list == nil {
899 return nil
900 }
901 ret := make(Paths, len(list))
902 for i := range list {
903 ret[i] = list[len(list)-1-i]
904 }
905 return ret
906}
907
Jeff Gaston294356f2017-09-27 17:05:30 -0700908func indexPathList(s Path, list []Path) int {
909 for i, l := range list {
910 if l == s {
911 return i
912 }
913 }
914
915 return -1
916}
917
918func inPathList(p Path, list []Path) bool {
919 return indexPathList(p, list) != -1
920}
921
922func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000923 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
924}
925
926func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700927 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000928 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700929 filtered = append(filtered, l)
930 } else {
931 remainder = append(remainder, l)
932 }
933 }
934
935 return
936}
937
Colin Cross93e85952017-08-15 13:34:18 -0700938// HasExt returns true of any of the paths have extension ext, otherwise false
939func (p Paths) HasExt(ext string) bool {
940 for _, path := range p {
941 if path.Ext() == ext {
942 return true
943 }
944 }
945
946 return false
947}
948
949// FilterByExt returns the subset of the paths that have extension ext
950func (p Paths) FilterByExt(ext string) Paths {
951 ret := make(Paths, 0, len(p))
952 for _, path := range p {
953 if path.Ext() == ext {
954 ret = append(ret, path)
955 }
956 }
957 return ret
958}
959
960// FilterOutByExt returns the subset of the paths that do not have extension ext
961func (p Paths) FilterOutByExt(ext string) Paths {
962 ret := make(Paths, 0, len(p))
963 for _, path := range p {
964 if path.Ext() != ext {
965 ret = append(ret, path)
966 }
967 }
968 return ret
969}
970
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700971// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
972// (including subdirectories) are in a contiguous subslice of the list, and can be found in
973// O(log(N)) time using a binary search on the directory prefix.
974type DirectorySortedPaths Paths
975
976func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
977 ret := append(DirectorySortedPaths(nil), paths...)
978 sort.Slice(ret, func(i, j int) bool {
979 return ret[i].String() < ret[j].String()
980 })
981 return ret
982}
983
984// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
985// that are in the specified directory and its subdirectories.
986func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
987 prefix := filepath.Clean(dir) + "/"
988 start := sort.Search(len(p), func(i int) bool {
989 return prefix < p[i].String()
990 })
991
992 ret := p[start:]
993
994 end := sort.Search(len(ret), func(i int) bool {
995 return !strings.HasPrefix(ret[i].String(), prefix)
996 })
997
998 ret = ret[:end]
999
1000 return Paths(ret)
1001}
1002
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001003// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001004type WritablePaths []WritablePath
1005
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001006// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1007// each item in this slice.
1008func (p WritablePaths) RelativeToTop() WritablePaths {
1009 ensureTestOnly()
1010 if p == nil {
1011 return p
1012 }
1013 ret := make(WritablePaths, len(p))
1014 for i, path := range p {
1015 ret[i] = path.RelativeToTop().(WritablePath)
1016 }
1017 return ret
1018}
1019
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001020// Strings returns the string forms of the writable paths.
1021func (p WritablePaths) Strings() []string {
1022 if p == nil {
1023 return nil
1024 }
1025 ret := make([]string, len(p))
1026 for i, path := range p {
1027 ret[i] = path.String()
1028 }
1029 return ret
1030}
1031
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001032// Paths returns the WritablePaths as a Paths
1033func (p WritablePaths) Paths() Paths {
1034 if p == nil {
1035 return nil
1036 }
1037 ret := make(Paths, len(p))
1038 for i, path := range p {
1039 ret[i] = path
1040 }
1041 return ret
1042}
1043
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001044type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001045 path string
1046 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001047}
1048
1049func (p basePath) Ext() string {
1050 return filepath.Ext(p.path)
1051}
1052
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001053func (p basePath) Base() string {
1054 return filepath.Base(p.path)
1055}
1056
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001057func (p basePath) Rel() string {
1058 if p.rel != "" {
1059 return p.rel
1060 }
1061 return p.path
1062}
1063
Colin Cross0875c522017-11-28 17:34:01 -08001064func (p basePath) String() string {
1065 return p.path
1066}
1067
Colin Cross0db55682017-12-05 15:36:55 -08001068func (p basePath) withRel(rel string) basePath {
1069 p.path = filepath.Join(p.path, rel)
1070 p.rel = rel
1071 return p
1072}
1073
Cole Faustbc65a3f2023-08-01 16:38:55 +00001074func (p basePath) RelativeToTop() Path {
1075 ensureTestOnly()
1076 return p
1077}
1078
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001079// SourcePath is a Path representing a file path rooted from SrcDir
1080type SourcePath struct {
1081 basePath
1082}
1083
1084var _ Path = SourcePath{}
1085
Colin Cross0db55682017-12-05 15:36:55 -08001086func (p SourcePath) withRel(rel string) SourcePath {
1087 p.basePath = p.basePath.withRel(rel)
1088 return p
1089}
1090
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001091// safePathForSource is for paths that we expect are safe -- only for use by go
1092// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001093func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1094 p, err := validateSafePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001095 ret := SourcePath{basePath{p, ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -07001096 if err != nil {
1097 return ret, err
1098 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001099
Colin Cross7b3dcc32019-01-24 13:14:39 -08001100 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001101 // special-case api surface gen files for now
1102 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001103 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001104 }
1105
Colin Crossfe4bc362018-09-12 10:02:13 -07001106 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001107}
1108
Colin Cross192e97a2018-02-22 14:21:02 -08001109// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1110func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001111 p, err := validatePath(pathComponents...)
Cole Faust483d1f72023-01-09 14:35:27 -08001112 ret := SourcePath{basePath{p, ""}}
Colin Cross94a32102018-02-22 14:21:02 -08001113 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001114 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001115 }
1116
Colin Cross7b3dcc32019-01-24 13:14:39 -08001117 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001118 // special-case for now
1119 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001120 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001121 }
1122
Colin Cross192e97a2018-02-22 14:21:02 -08001123 return ret, nil
1124}
1125
1126// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1127// path does not exist.
Colin Cross662d6142022-11-03 20:38:01 -07001128func existsWithDependencies(ctx PathGlobContext, path SourcePath) (exists bool, err error) {
Colin Cross192e97a2018-02-22 14:21:02 -08001129 var files []string
1130
Colin Cross662d6142022-11-03 20:38:01 -07001131 // Use glob to produce proper dependencies, even though we only want
1132 // a single file.
1133 files, err = ctx.GlobWithDeps(path.String(), nil)
Colin Cross192e97a2018-02-22 14:21:02 -08001134
1135 if err != nil {
1136 return false, fmt.Errorf("glob: %s", err.Error())
1137 }
1138
1139 return len(files) > 0, nil
1140}
1141
1142// PathForSource joins the provided path components and validates that the result
1143// neither escapes the source dir nor is in the out dir.
1144// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1145func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1146 path, err := pathForSource(ctx, pathComponents...)
1147 if err != nil {
1148 reportPathError(ctx, err)
1149 }
1150
Colin Crosse3924e12018-08-15 20:18:53 -07001151 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001152 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001153 }
1154
Liz Kammera830f3a2020-11-10 10:50:34 -08001155 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross662d6142022-11-03 20:38:01 -07001156 exists, err := existsWithDependencies(modCtx, path)
Colin Cross192e97a2018-02-22 14:21:02 -08001157 if err != nil {
1158 reportPathError(ctx, err)
1159 }
1160 if !exists {
1161 modCtx.AddMissingDependencies([]string{path.String()})
1162 }
Colin Cross988414c2020-01-11 01:11:46 +00001163 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001164 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001165 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001166 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001167 }
1168 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001169}
1170
Cole Faustbc65a3f2023-08-01 16:38:55 +00001171// PathForArbitraryOutput creates a path for the given components. Unlike PathForOutput,
1172// the path is relative to the root of the output folder, not the out/soong folder.
1173func PathForArbitraryOutput(ctx PathContext, pathComponents ...string) Path {
1174 p, err := validatePath(pathComponents...)
1175 if err != nil {
1176 reportPathError(ctx, err)
1177 }
1178 return basePath{path: filepath.Join(ctx.Config().OutDir(), p)}
1179}
1180
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001181// MaybeExistentPathForSource joins the provided path components and validates that the result
1182// neither escapes the source dir nor is in the out dir.
1183// It does not validate whether the path exists.
1184func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1185 path, err := pathForSource(ctx, pathComponents...)
1186 if err != nil {
1187 reportPathError(ctx, err)
1188 }
1189
1190 if pathtools.IsGlob(path.String()) {
1191 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1192 }
1193 return path
1194}
1195
Liz Kammer7aa52882021-02-11 09:16:14 -05001196// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1197// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1198// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1199// of the path changes.
Colin Cross662d6142022-11-03 20:38:01 -07001200func ExistentPathForSource(ctx PathGlobContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001201 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001202 if err != nil {
1203 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001204 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001205 return OptionalPath{}
1206 }
Colin Crossc48c1432018-02-23 07:09:01 +00001207
Colin Crosse3924e12018-08-15 20:18:53 -07001208 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001209 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001210 return OptionalPath{}
1211 }
1212
Colin Cross192e97a2018-02-22 14:21:02 -08001213 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001214 if err != nil {
1215 reportPathError(ctx, err)
1216 return OptionalPath{}
1217 }
Colin Cross192e97a2018-02-22 14:21:02 -08001218 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001219 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001220 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001221 return OptionalPathForPath(path)
1222}
1223
1224func (p SourcePath) String() string {
Cole Faust483d1f72023-01-09 14:35:27 -08001225 if p.path == "" {
1226 return "."
1227 }
1228 return p.path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001229}
1230
1231// Join creates a new SourcePath with paths... joined with the current path. The
1232// provided paths... may not use '..' to escape from the current path.
1233func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001234 path, err := validatePath(paths...)
1235 if err != nil {
1236 reportPathError(ctx, err)
1237 }
Colin Cross0db55682017-12-05 15:36:55 -08001238 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001239}
1240
Colin Cross2fafa3e2019-03-05 12:39:51 -08001241// join is like Join but does less path validation.
1242func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1243 path, err := validateSafePath(paths...)
1244 if err != nil {
1245 reportPathError(ctx, err)
1246 }
1247 return p.withRel(path)
1248}
1249
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001250// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1251// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001252func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001253 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001254 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001255 relDir = srcPath.path
1256 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001257 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001258 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001259 return OptionalPath{}
1260 }
Cole Faust483d1f72023-01-09 14:35:27 -08001261 dir := filepath.Join(p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001262 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001263 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001264 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001265 }
Colin Cross461b4452018-02-23 09:22:42 -08001266 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001267 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001268 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001269 return OptionalPath{}
1270 }
1271 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001272 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001273 }
Cole Faust483d1f72023-01-09 14:35:27 -08001274 return OptionalPathForPath(PathForSource(ctx, paths[0]))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001275}
1276
Colin Cross70dda7e2019-10-01 22:05:35 -07001277// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001278type OutputPath struct {
1279 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001280
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001281 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001282 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001283
Colin Crossd63c9a72020-01-29 16:52:50 -08001284 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001285}
1286
Colin Cross702e0f82017-10-18 17:27:54 -07001287func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001288 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001289 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001290 return p
1291}
1292
Colin Cross3063b782018-08-15 11:19:12 -07001293func (p OutputPath) WithoutRel() OutputPath {
1294 p.basePath.rel = filepath.Base(p.basePath.path)
1295 return p
1296}
1297
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001298func (p OutputPath) getSoongOutDir() string {
1299 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001300}
1301
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001302func (p OutputPath) RelativeToTop() Path {
1303 return p.outputPathRelativeToTop()
1304}
1305
1306func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001307 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1308 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001309 return p
1310}
1311
Paul Duffin0267d492021-02-02 10:05:52 +00001312func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1313 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1314}
1315
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001316var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001317var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001318var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001319
Chris Parsons8f232a22020-06-23 17:37:05 -04001320// toolDepPath is a Path representing a dependency of the build tool.
1321type toolDepPath struct {
1322 basePath
1323}
1324
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001325func (t toolDepPath) RelativeToTop() Path {
1326 ensureTestOnly()
1327 return t
1328}
1329
Chris Parsons8f232a22020-06-23 17:37:05 -04001330var _ Path = toolDepPath{}
1331
1332// pathForBuildToolDep returns a toolDepPath representing the given path string.
1333// There is no validation for the path, as it is "trusted": It may fail
1334// normal validation checks. For example, it may be an absolute path.
1335// Only use this function to construct paths for dependencies of the build
1336// tool invocation.
1337func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001338 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001339}
1340
Jeff Gaston734e3802017-04-10 15:47:24 -07001341// PathForOutput joins the provided paths and returns an OutputPath that is
1342// validated to not escape the build dir.
1343// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1344func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001345 path, err := validatePath(pathComponents...)
1346 if err != nil {
1347 reportPathError(ctx, err)
1348 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001349 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001350 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001351 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001352}
1353
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001354// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001355func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1356 ret := make(WritablePaths, len(paths))
1357 for i, path := range paths {
1358 ret[i] = PathForOutput(ctx, path)
1359 }
1360 return ret
1361}
1362
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001363func (p OutputPath) writablePath() {}
1364
1365func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001366 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001367}
1368
1369// Join creates a new OutputPath with paths... joined with the current path. The
1370// provided paths... may not use '..' to escape from the current path.
1371func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001372 path, err := validatePath(paths...)
1373 if err != nil {
1374 reportPathError(ctx, err)
1375 }
Colin Cross0db55682017-12-05 15:36:55 -08001376 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001377}
1378
Colin Cross8854a5a2019-02-11 14:14:16 -08001379// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1380func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1381 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001382 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001383 }
1384 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001385 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001386 return ret
1387}
1388
Colin Cross40e33732019-02-15 11:08:35 -08001389// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1390func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1391 path, err := validatePath(paths...)
1392 if err != nil {
1393 reportPathError(ctx, err)
1394 }
1395
1396 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001397 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001398 return ret
1399}
1400
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001401// PathForIntermediates returns an OutputPath representing the top-level
1402// intermediates directory.
1403func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001404 path, err := validatePath(paths...)
1405 if err != nil {
1406 reportPathError(ctx, err)
1407 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001408 return PathForOutput(ctx, ".intermediates", path)
1409}
1410
Colin Cross07e51612019-03-05 12:46:40 -08001411var _ genPathProvider = SourcePath{}
1412var _ objPathProvider = SourcePath{}
1413var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001414
Colin Cross07e51612019-03-05 12:46:40 -08001415// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001416// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001417func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001418 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1419 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1420 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1421 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1422 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001423 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001424 if err != nil {
1425 if depErr, ok := err.(missingDependencyError); ok {
1426 if ctx.Config().AllowMissingDependencies() {
1427 ctx.AddMissingDependencies(depErr.missingDeps)
1428 } else {
1429 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1430 }
1431 } else {
1432 reportPathError(ctx, err)
1433 }
1434 return nil
1435 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001436 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001437 return nil
1438 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001439 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001440 }
1441 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001442}
1443
Liz Kammera830f3a2020-11-10 10:50:34 -08001444func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001445 p, err := validatePath(paths...)
1446 if err != nil {
1447 reportPathError(ctx, err)
1448 }
1449
1450 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1451 if err != nil {
1452 reportPathError(ctx, err)
1453 }
1454
1455 path.basePath.rel = p
1456
1457 return path
1458}
1459
Colin Cross2fafa3e2019-03-05 12:39:51 -08001460// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1461// will return the path relative to subDir in the module's source directory. If any input paths are not located
1462// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001463func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001464 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001465 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001466 for i, path := range paths {
1467 rel := Rel(ctx, subDirFullPath.String(), path.String())
1468 paths[i] = subDirFullPath.join(ctx, rel)
1469 }
1470 return paths
1471}
1472
1473// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1474// module's source directory. If the input path is not located inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001475func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001476 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001477 rel := Rel(ctx, subDirFullPath.String(), path.String())
1478 return subDirFullPath.Join(ctx, rel)
1479}
1480
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001481// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1482// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001483func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001484 if p == nil {
1485 return OptionalPath{}
1486 }
1487 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1488}
1489
Liz Kammera830f3a2020-11-10 10:50:34 -08001490func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001491 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001492}
1493
Liz Kammera830f3a2020-11-10 10:50:34 -08001494func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001495 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001496}
1497
Liz Kammera830f3a2020-11-10 10:50:34 -08001498func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001499 // TODO: Use full directory if the new ctx is not the current ctx?
1500 return PathForModuleRes(ctx, p.path, name)
1501}
1502
1503// ModuleOutPath is a Path representing a module's output directory.
1504type ModuleOutPath struct {
1505 OutputPath
1506}
1507
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001508func (p ModuleOutPath) RelativeToTop() Path {
1509 p.OutputPath = p.outputPathRelativeToTop()
1510 return p
1511}
1512
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001513var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001514var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001515
Liz Kammera830f3a2020-11-10 10:50:34 -08001516func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001517 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1518}
1519
Liz Kammera830f3a2020-11-10 10:50:34 -08001520// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1521type ModuleOutPathContext interface {
1522 PathContext
1523
1524 ModuleName() string
1525 ModuleDir() string
1526 ModuleSubDir() string
Inseob Kim8ff69de2023-06-16 14:19:33 +09001527 SoongConfigTraceHash() string
Liz Kammera830f3a2020-11-10 10:50:34 -08001528}
1529
1530func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Inseob Kim8ff69de2023-06-16 14:19:33 +09001531 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir(), ctx.SoongConfigTraceHash())
Colin Cross702e0f82017-10-18 17:27:54 -07001532}
1533
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001534// PathForModuleOut returns a Path representing the paths... under the module's
1535// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001536func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001537 p, err := validatePath(paths...)
1538 if err != nil {
1539 reportPathError(ctx, err)
1540 }
Colin Cross702e0f82017-10-18 17:27:54 -07001541 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001542 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001543 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001544}
1545
1546// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1547// directory. Mainly used for generated sources.
1548type ModuleGenPath struct {
1549 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001550}
1551
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001552func (p ModuleGenPath) RelativeToTop() Path {
1553 p.OutputPath = p.outputPathRelativeToTop()
1554 return p
1555}
1556
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001557var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001558var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001559var _ genPathProvider = ModuleGenPath{}
1560var _ objPathProvider = ModuleGenPath{}
1561
1562// PathForModuleGen returns a Path representing the paths... under the module's
1563// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001564func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001565 p, err := validatePath(paths...)
1566 if err != nil {
1567 reportPathError(ctx, err)
1568 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001569 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001570 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001571 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001572 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001573 }
1574}
1575
Liz Kammera830f3a2020-11-10 10:50:34 -08001576func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001577 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001578 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001579}
1580
Liz Kammera830f3a2020-11-10 10:50:34 -08001581func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001582 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1583}
1584
1585// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1586// directory. Used for compiled objects.
1587type ModuleObjPath struct {
1588 ModuleOutPath
1589}
1590
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001591func (p ModuleObjPath) RelativeToTop() Path {
1592 p.OutputPath = p.outputPathRelativeToTop()
1593 return p
1594}
1595
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001596var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001597var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001598
1599// PathForModuleObj returns a Path representing the paths... under the module's
1600// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001601func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001602 p, err := validatePath(pathComponents...)
1603 if err != nil {
1604 reportPathError(ctx, err)
1605 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001606 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1607}
1608
1609// ModuleResPath is a a Path representing the 'res' directory in a module's
1610// output directory.
1611type ModuleResPath struct {
1612 ModuleOutPath
1613}
1614
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001615func (p ModuleResPath) RelativeToTop() Path {
1616 p.OutputPath = p.outputPathRelativeToTop()
1617 return p
1618}
1619
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001620var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001621var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001622
1623// PathForModuleRes returns a Path representing the paths... under the module's
1624// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001625func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001626 p, err := validatePath(pathComponents...)
1627 if err != nil {
1628 reportPathError(ctx, err)
1629 }
1630
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001631 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1632}
1633
Colin Cross70dda7e2019-10-01 22:05:35 -07001634// InstallPath is a Path representing a installed file path rooted from the build directory
1635type InstallPath struct {
1636 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001637
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001638 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001639 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001640
Jiyong Park957bcd92020-10-20 18:23:33 +09001641 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1642 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1643 partitionDir string
1644
Colin Crossb1692a32021-10-25 15:39:01 -07001645 partition string
1646
Jiyong Park957bcd92020-10-20 18:23:33 +09001647 // makePath indicates whether this path is for Soong (false) or Make (true).
1648 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001649}
1650
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001651// Will panic if called from outside a test environment.
1652func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001653 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001654 return
1655 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001656 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001657}
1658
1659func (p InstallPath) RelativeToTop() Path {
1660 ensureTestOnly()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001661 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001662 return p
1663}
1664
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001665func (p InstallPath) getSoongOutDir() string {
1666 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001667}
1668
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001669func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1670 panic("Not implemented")
1671}
1672
Paul Duffin9b478b02019-12-10 13:41:51 +00001673var _ Path = InstallPath{}
1674var _ WritablePath = InstallPath{}
1675
Colin Cross70dda7e2019-10-01 22:05:35 -07001676func (p InstallPath) writablePath() {}
1677
1678func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001679 if p.makePath {
1680 // Make path starts with out/ instead of out/soong.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001681 return filepath.Join(p.soongOutDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001682 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001683 return filepath.Join(p.soongOutDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001684 }
1685}
1686
1687// PartitionDir returns the path to the partition where the install path is rooted at. It is
1688// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1689// The ./soong is dropped if the install path is for Make.
1690func (p InstallPath) PartitionDir() string {
1691 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001692 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001693 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001694 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001695 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001696}
1697
Jihoon Kangf78a8902022-09-01 22:47:07 +00001698func (p InstallPath) Partition() string {
1699 return p.partition
1700}
1701
Colin Cross70dda7e2019-10-01 22:05:35 -07001702// Join creates a new InstallPath with paths... joined with the current path. The
1703// provided paths... may not use '..' to escape from the current path.
1704func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1705 path, err := validatePath(paths...)
1706 if err != nil {
1707 reportPathError(ctx, err)
1708 }
1709 return p.withRel(path)
1710}
1711
1712func (p InstallPath) withRel(rel string) InstallPath {
1713 p.basePath = p.basePath.withRel(rel)
1714 return p
1715}
1716
Colin Crossc68db4b2021-11-11 18:59:15 -08001717// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1718// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001719func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001720 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001721 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001722}
1723
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001724// PathForModuleInstall returns a Path representing the install path for the
1725// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001726func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001727 os, arch := osAndArch(ctx)
Cole Faust11edf552023-10-13 11:32:14 -07001728 partition := modulePartition(ctx, os.Class == Device)
Cole Faust3b703f32023-10-16 13:30:51 -07001729 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001730}
1731
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001732// PathForHostDexInstall returns an InstallPath representing the install path for the
1733// module appended with paths...
1734func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Cole Faust3b703f32023-10-16 13:30:51 -07001735 return pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", pathComponents...)
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001736}
1737
Spandan Das5d1b9292021-06-03 19:36:41 +00001738// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1739func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1740 os, arch := osAndArch(ctx)
Cole Faust3b703f32023-10-16 13:30:51 -07001741 return pathForInstall(ctx, os, arch, partition, pathComponents...)
Spandan Das5d1b9292021-06-03 19:36:41 +00001742}
1743
1744func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001745 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001746 arch := ctx.Arch().ArchType
1747 forceOS, forceArch := ctx.InstallForceOS()
1748 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001749 os = *forceOS
1750 }
Jiyong Park87788b52020-09-01 12:37:45 +09001751 if forceArch != nil {
1752 arch = *forceArch
1753 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001754 return os, arch
1755}
Colin Cross609c49a2020-02-13 13:20:11 -08001756
Cole Faust3b703f32023-10-16 13:30:51 -07001757func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string,
Colin Cross609c49a2020-02-13 13:20:11 -08001758 pathComponents ...string) InstallPath {
1759
Jiyong Park97859152023-02-14 17:05:48 +09001760 var partitionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001761
Colin Cross6e359402020-02-10 15:29:54 -08001762 if os.Class == Device {
Jiyong Park97859152023-02-14 17:05:48 +09001763 partitionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001764 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001765 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001766 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001767 // instead of linux_glibc
1768 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001769 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001770 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1771 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1772 // compiling we will still use "linux_musl".
1773 osName = "linux"
1774 }
1775
Jiyong Park87788b52020-09-01 12:37:45 +09001776 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1777 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1778 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1779 // Let's keep using x86 for the existing cases until we have a need to support
1780 // other architectures.
1781 archName := arch.String()
1782 if os.Class == Host && (arch == X86_64 || arch == Common) {
1783 archName = "x86"
1784 }
Jiyong Park97859152023-02-14 17:05:48 +09001785 partitionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001786 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001787
Jiyong Park97859152023-02-14 17:05:48 +09001788 partitionPath, err := validatePath(partitionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001789 if err != nil {
1790 reportPathError(ctx, err)
1791 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001792
Jiyong Park957bcd92020-10-20 18:23:33 +09001793 base := InstallPath{
Jiyong Park97859152023-02-14 17:05:48 +09001794 basePath: basePath{partitionPath, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001795 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park97859152023-02-14 17:05:48 +09001796 partitionDir: partitionPath,
Colin Crossb1692a32021-10-25 15:39:01 -07001797 partition: partition,
Colin Crossc68db4b2021-11-11 18:59:15 -08001798 }
1799
1800 if ctx.Config().KatiEnabled() {
1801 base.makePath = true
Jiyong Park957bcd92020-10-20 18:23:33 +09001802 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001803
Jiyong Park957bcd92020-10-20 18:23:33 +09001804 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001805}
1806
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001807func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001808 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001809 basePath: basePath{prefix, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001810 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001811 partitionDir: prefix,
1812 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001813 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001814 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001815}
1816
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001817func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1818 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1819}
1820
1821func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1822 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1823}
1824
Colin Cross70dda7e2019-10-01 22:05:35 -07001825func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001826 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001827 return "/" + rel
1828}
1829
Cole Faust11edf552023-10-13 11:32:14 -07001830func modulePartition(ctx ModuleInstallPathContext, device bool) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001831 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001832 if ctx.InstallInTestcases() {
1833 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001834 partition = "testcases"
Cole Faust11edf552023-10-13 11:32:14 -07001835 } else if device {
Colin Cross6e359402020-02-10 15:29:54 -08001836 if ctx.InstallInData() {
1837 partition = "data"
1838 } else if ctx.InstallInRamdisk() {
1839 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1840 partition = "recovery/root/first_stage_ramdisk"
1841 } else {
1842 partition = "ramdisk"
1843 }
1844 if !ctx.InstallInRoot() {
1845 partition += "/system"
1846 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001847 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001848 // The module is only available after switching root into
1849 // /first_stage_ramdisk. To expose the module before switching root
1850 // on a device without a dedicated recovery partition, install the
1851 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001852 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001853 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001854 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001855 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001856 }
1857 if !ctx.InstallInRoot() {
1858 partition += "/system"
1859 }
Inseob Kim08758f02021-04-08 21:13:22 +09001860 } else if ctx.InstallInDebugRamdisk() {
1861 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001862 } else if ctx.InstallInRecovery() {
1863 if ctx.InstallInRoot() {
1864 partition = "recovery/root"
1865 } else {
1866 // the layout of recovery partion is the same as that of system partition
1867 partition = "recovery/root/system"
1868 }
1869 } else if ctx.SocSpecific() {
1870 partition = ctx.DeviceConfig().VendorPath()
1871 } else if ctx.DeviceSpecific() {
1872 partition = ctx.DeviceConfig().OdmPath()
1873 } else if ctx.ProductSpecific() {
1874 partition = ctx.DeviceConfig().ProductPath()
1875 } else if ctx.SystemExtSpecific() {
1876 partition = ctx.DeviceConfig().SystemExtPath()
1877 } else if ctx.InstallInRoot() {
1878 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001879 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001880 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001881 }
Colin Cross6e359402020-02-10 15:29:54 -08001882 if ctx.InstallInSanitizerDir() {
1883 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001884 }
Colin Cross43f08db2018-11-12 10:13:39 -08001885 }
1886 return partition
1887}
1888
Colin Cross609c49a2020-02-13 13:20:11 -08001889type InstallPaths []InstallPath
1890
1891// Paths returns the InstallPaths as a Paths
1892func (p InstallPaths) Paths() Paths {
1893 if p == nil {
1894 return nil
1895 }
1896 ret := make(Paths, len(p))
1897 for i, path := range p {
1898 ret[i] = path
1899 }
1900 return ret
1901}
1902
1903// Strings returns the string forms of the install paths.
1904func (p InstallPaths) Strings() []string {
1905 if p == nil {
1906 return nil
1907 }
1908 ret := make([]string, len(p))
1909 for i, path := range p {
1910 ret[i] = path.String()
1911 }
1912 return ret
1913}
1914
Jingwen Chen24d0c562023-02-07 09:29:36 +00001915// validatePathInternal ensures that a path does not leave its component, and
1916// optionally doesn't contain Ninja variables.
1917func validatePathInternal(allowNinjaVariables bool, pathComponents ...string) (string, error) {
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001918 initialEmpty := 0
1919 finalEmpty := 0
1920 for i, path := range pathComponents {
Jingwen Chen24d0c562023-02-07 09:29:36 +00001921 if !allowNinjaVariables && strings.Contains(path, "$") {
1922 return "", fmt.Errorf("Path contains invalid character($): %s", path)
1923 }
1924
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001925 path := filepath.Clean(path)
1926 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001927 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001928 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001929
1930 if i == initialEmpty && pathComponents[i] == "" {
1931 initialEmpty++
1932 }
1933 if i == finalEmpty && pathComponents[len(pathComponents)-1-i] == "" {
1934 finalEmpty++
1935 }
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001936 }
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001937 // Optimization: filepath.Join("foo", "") returns a newly allocated copy
1938 // of "foo", while filepath.Join("foo") does not. Strip out any empty
1939 // path components.
1940 if initialEmpty == len(pathComponents) {
1941 return "", nil
1942 }
1943 nonEmptyPathComponents := pathComponents[initialEmpty : len(pathComponents)-finalEmpty]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001944 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1945 // variables. '..' may remove the entire ninja variable, even if it
1946 // will be expanded to multiple nested directories.
Colin Crossbf9ed3f2023-10-24 14:17:03 -07001947 return filepath.Join(nonEmptyPathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001948}
1949
Jingwen Chen24d0c562023-02-07 09:29:36 +00001950// validateSafePath validates a path that we trust (may contain ninja
1951// variables). Ensures that each path component does not attempt to leave its
1952// component. Returns a joined version of each path component.
1953func validateSafePath(pathComponents ...string) (string, error) {
1954 return validatePathInternal(true, pathComponents...)
1955}
1956
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001957// validatePath validates that a path does not include ninja variables, and that
1958// each path component does not attempt to leave its component. Returns a joined
1959// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001960func validatePath(pathComponents ...string) (string, error) {
Jingwen Chen24d0c562023-02-07 09:29:36 +00001961 return validatePathInternal(false, pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001962}
Colin Cross5b529592017-05-09 13:34:34 -07001963
Colin Cross0875c522017-11-28 17:34:01 -08001964func PathForPhony(ctx PathContext, phony string) WritablePath {
1965 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001966 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001967 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001968 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001969}
1970
Colin Cross74e3fe42017-12-11 15:51:44 -08001971type PhonyPath struct {
1972 basePath
1973}
1974
1975func (p PhonyPath) writablePath() {}
1976
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001977func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00001978 // A phone path cannot contain any / so cannot be relative to the build directory.
1979 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001980}
1981
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001982func (p PhonyPath) RelativeToTop() Path {
1983 ensureTestOnly()
1984 // A phony path cannot contain any / so does not have a build directory so switching to a new
1985 // build directory has no effect so just return this path.
1986 return p
1987}
1988
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001989func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1990 panic("Not implemented")
1991}
1992
Colin Cross74e3fe42017-12-11 15:51:44 -08001993var _ Path = PhonyPath{}
1994var _ WritablePath = PhonyPath{}
1995
Colin Cross5b529592017-05-09 13:34:34 -07001996type testPath struct {
1997 basePath
1998}
1999
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002000func (p testPath) RelativeToTop() Path {
2001 ensureTestOnly()
2002 return p
2003}
2004
Colin Cross5b529592017-05-09 13:34:34 -07002005func (p testPath) String() string {
2006 return p.path
2007}
2008
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002009var _ Path = testPath{}
2010
Colin Cross40e33732019-02-15 11:08:35 -08002011// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2012// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002013func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002014 p, err := validateSafePath(paths...)
2015 if err != nil {
2016 panic(err)
2017 }
Colin Cross5b529592017-05-09 13:34:34 -07002018 return testPath{basePath{path: p, rel: p}}
2019}
2020
Sam Delmerico2351eac2022-05-24 17:10:02 +00002021func PathForTestingWithRel(path, rel string) Path {
2022 p, err := validateSafePath(path, rel)
2023 if err != nil {
2024 panic(err)
2025 }
2026 r, err := validatePath(rel)
2027 if err != nil {
2028 panic(err)
2029 }
2030 return testPath{basePath{path: p, rel: r}}
2031}
2032
Colin Cross40e33732019-02-15 11:08:35 -08002033// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2034func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002035 p := make(Paths, len(strs))
2036 for i, s := range strs {
2037 p[i] = PathForTesting(s)
2038 }
2039
2040 return p
2041}
Colin Cross43f08db2018-11-12 10:13:39 -08002042
Colin Cross40e33732019-02-15 11:08:35 -08002043type testPathContext struct {
2044 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002045}
2046
Colin Cross40e33732019-02-15 11:08:35 -08002047func (x *testPathContext) Config() Config { return x.config }
2048func (x *testPathContext) AddNinjaFileDeps(...string) {}
2049
2050// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2051// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002052func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002053 return &testPathContext{
2054 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002055 }
2056}
2057
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002058type testModuleInstallPathContext struct {
2059 baseModuleContext
2060
2061 inData bool
2062 inTestcases bool
2063 inSanitizerDir bool
2064 inRamdisk bool
2065 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002066 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002067 inRecovery bool
2068 inRoot bool
2069 forceOS *OsType
2070 forceArch *ArchType
2071}
2072
2073func (m testModuleInstallPathContext) Config() Config {
2074 return m.baseModuleContext.config
2075}
2076
2077func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2078
2079func (m testModuleInstallPathContext) InstallInData() bool {
2080 return m.inData
2081}
2082
2083func (m testModuleInstallPathContext) InstallInTestcases() bool {
2084 return m.inTestcases
2085}
2086
2087func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2088 return m.inSanitizerDir
2089}
2090
2091func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2092 return m.inRamdisk
2093}
2094
2095func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2096 return m.inVendorRamdisk
2097}
2098
Inseob Kim08758f02021-04-08 21:13:22 +09002099func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2100 return m.inDebugRamdisk
2101}
2102
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002103func (m testModuleInstallPathContext) InstallInRecovery() bool {
2104 return m.inRecovery
2105}
2106
2107func (m testModuleInstallPathContext) InstallInRoot() bool {
2108 return m.inRoot
2109}
2110
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002111func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2112 return m.forceOS, m.forceArch
2113}
2114
2115// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2116// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2117// delegated to it will panic.
2118func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2119 ctx := &testModuleInstallPathContext{}
2120 ctx.config = config
2121 ctx.os = Android
2122 return ctx
2123}
2124
Colin Cross43f08db2018-11-12 10:13:39 -08002125// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2126// targetPath is not inside basePath.
2127func Rel(ctx PathContext, basePath string, targetPath string) string {
2128 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2129 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002130 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002131 return ""
2132 }
2133 return rel
2134}
2135
2136// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2137// targetPath is not inside basePath.
2138func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002139 rel, isRel, err := maybeRelErr(basePath, targetPath)
2140 if err != nil {
2141 reportPathError(ctx, err)
2142 }
2143 return rel, isRel
2144}
2145
2146func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002147 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2148 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002149 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002150 }
2151 rel, err := filepath.Rel(basePath, targetPath)
2152 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002153 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002154 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002155 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002156 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002157 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002158}
Colin Cross988414c2020-01-11 01:11:46 +00002159
2160// Writes a file to the output directory. Attempting to write directly to the output directory
2161// will fail due to the sandbox of the soong_build process.
Chris Parsons1a12d032023-02-06 22:37:41 -05002162// Only writes the file if the file doesn't exist or if it has different contents, to prevent
2163// updating the timestamp if no changes would be made. (This is better for incremental
2164// performance.)
Colin Cross988414c2020-01-11 01:11:46 +00002165func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002166 absPath := absolutePath(path.String())
2167 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2168 if err != nil {
2169 return err
2170 }
Chris Parsons1a12d032023-02-06 22:37:41 -05002171 return pathtools.WriteFileIfChanged(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002172}
2173
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002174func RemoveAllOutputDir(path WritablePath) error {
2175 return os.RemoveAll(absolutePath(path.String()))
2176}
2177
2178func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2179 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002180 return createDirIfNonexistent(dir, perm)
2181}
2182
2183func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002184 if _, err := os.Stat(dir); os.IsNotExist(err) {
2185 return os.MkdirAll(dir, os.ModePerm)
2186 } else {
2187 return err
2188 }
2189}
2190
Jingwen Chen78257e52021-05-21 02:34:24 +00002191// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2192// read arbitrary files without going through the methods in the current package that track
2193// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002194func absolutePath(path string) string {
2195 if filepath.IsAbs(path) {
2196 return path
2197 }
2198 return filepath.Join(absSrcDir, path)
2199}
Chris Parsons216e10a2020-07-09 17:12:52 -04002200
2201// A DataPath represents the path of a file to be used as data, for example
2202// a test library to be installed alongside a test.
2203// The data file should be installed (copied from `<SrcPath>`) to
2204// `<install_root>/<RelativeInstallPath>/<filename>`, or
2205// `<install_root>/<filename>` if RelativeInstallPath is empty.
2206type DataPath struct {
2207 // The path of the data file that should be copied into the data directory
2208 SrcPath Path
2209 // The install path of the data file, relative to the install root.
2210 RelativeInstallPath string
2211}
Colin Crossdcf71b22021-02-01 13:59:03 -08002212
Colin Crossd442a0e2023-11-16 11:19:26 -08002213func (d *DataPath) ToRelativeInstallPath() string {
2214 relPath := d.SrcPath.Rel()
2215 if d.RelativeInstallPath != "" {
2216 relPath = filepath.Join(d.RelativeInstallPath, relPath)
2217 }
2218 return relPath
2219}
2220
Colin Crossdcf71b22021-02-01 13:59:03 -08002221// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2222func PathsIfNonNil(paths ...Path) Paths {
2223 if len(paths) == 0 {
2224 // Fast path for empty argument list
2225 return nil
2226 } else if len(paths) == 1 {
2227 // Fast path for a single argument
2228 if paths[0] != nil {
2229 return paths
2230 } else {
2231 return nil
2232 }
2233 }
2234 ret := make(Paths, 0, len(paths))
2235 for _, path := range paths {
2236 if path != nil {
2237 ret = append(ret, path)
2238 }
2239 }
2240 if len(ret) == 0 {
2241 return nil
2242 }
2243 return ret
2244}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002245
2246var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2247 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2248 regexp.MustCompile("^hardware/google/"),
2249 regexp.MustCompile("^hardware/interfaces/"),
2250 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2251 regexp.MustCompile("^hardware/ril/"),
2252}
2253
2254func IsThirdPartyPath(path string) bool {
2255 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2256
2257 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2258 for _, prefix := range thirdPartyDirPrefixExceptions {
2259 if prefix.MatchString(path) {
2260 return false
2261 }
2262 }
2263 return true
2264 }
2265 return false
2266}