blob: b5746f7504da146ead06665b01f877d07f799ada [file] [log] [blame]
Liz Kammer620dea62021-04-14 17:36:10 -04001// 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
15package android
16
17import (
Liz Kammer620dea62021-04-14 17:36:10 -040018 "fmt"
19 "path/filepath"
20 "strings"
21
Chris Parsons953b3562021-09-20 15:14:39 -040022 "android/soong/bazel"
23
Liz Kammer620dea62021-04-14 17:36:10 -040024 "github.com/google/blueprint"
25 "github.com/google/blueprint/pathtools"
26)
27
28// bazel_paths contains methods to:
29// * resolve Soong path and module references into bazel.LabelList
30// * resolve Bazel path references into Soong-compatible paths
31//
32// There is often a similar method for Bazel as there is for Soong path handling and should be used
33// in similar circumstances
34//
35// Bazel Soong
36//
37// BazelLabelForModuleSrc PathForModuleSrc
38// BazelLabelForModuleSrcExcludes PathForModuleSrcExcludes
39// BazelLabelForModuleDeps n/a
40// tbd PathForSource
41// tbd ExistentPathsForSources
42// PathForBazelOut PathForModuleOut
43//
44// Use cases:
45// * Module contains a property (often tagged `android:"path"`) that expects paths *relative to the
46// module directory*:
47// * BazelLabelForModuleSrcExcludes, if the module also contains an excludes_<propname> property
48// * BazelLabelForModuleSrc, otherwise
49// * Converting references to other modules to Bazel Labels:
50// BazelLabelForModuleDeps
51// * Converting a path obtained from bazel_handler cquery results:
52// PathForBazelOut
53//
54// NOTE: all Soong globs are expanded within Soong rather than being converted to a Bazel glob
55// syntax. This occurs because Soong does not have a concept of crossing package boundaries,
56// so the glob as computed by Soong may contain paths that cross package-boundaries. These
57// would be unknowingly omitted if the glob were handled by Bazel. By expanding globs within
58// Soong, we support identification and detection (within Bazel) use of paths that cross
59// package boundaries.
60//
61// Path resolution:
62// * filepath/globs: resolves as itself or is converted to an absolute Bazel label (e.g.
63// //path/to/dir:<filepath>) if path exists in a separate package or subpackage.
64// * references to other modules (using the ":name{.tag}" syntax). These resolve as a Bazel label
65// for a target. If the Bazel target is in the local module directory, it will be returned
66// relative to the current package (e.g. ":<target>"). Otherwise, it will be returned as an
67// absolute Bazel label (e.g. "//path/to/dir:<target>"). If the reference to another module
68// cannot be resolved,the function will panic. This is often due to the dependency not being added
69// via an AddDependency* method.
70
71// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
72// order to form a Bazel-compatible label for conversion.
73type BazelConversionPathContext interface {
74 EarlyModulePathContext
75
76 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Chris Parsons5a34ffb2021-07-21 14:34:58 -040077 ModuleFromName(name string) (blueprint.Module, bool)
Liz Kammer620dea62021-04-14 17:36:10 -040078 Module() Module
Liz Kammer6eff3232021-08-26 08:37:59 -040079 OtherModuleType(m blueprint.Module) string
Liz Kammer620dea62021-04-14 17:36:10 -040080 OtherModuleName(m blueprint.Module) string
81 OtherModuleDir(m blueprint.Module) string
Liz Kammer6eff3232021-08-26 08:37:59 -040082 AddUnconvertedBp2buildDep(string)
Liz Kammer620dea62021-04-14 17:36:10 -040083}
84
85// BazelLabelForModuleDeps expects a list of reference to other modules, ("<module>"
86// or ":<module>") and returns a Bazel-compatible label which corresponds to dependencies on the
87// module within the given ctx.
Chris Parsons953b3562021-09-20 15:14:39 -040088func BazelLabelForModuleDeps(ctx TopDownMutatorContext, modules []string) bazel.LabelList {
89 return BazelLabelForModuleDepsWithFn(ctx, modules, BazelModuleLabel)
Liz Kammer2d7bbe32021-06-10 18:20:06 -040090}
91
92// BazelLabelForModuleWholeDepsExcludes expects two lists: modules (containing modules to include in
93// the list), and excludes (modules to exclude from the list). Both of these should contain
94// references to other modules, ("<module>" or ":<module>"). It returns a Bazel-compatible label
95// list which corresponds to dependencies on the module within the given ctx, and the excluded
96// dependencies. Prebuilt dependencies will be appended with _alwayslink so they can be handled as
97// whole static libraries.
Chris Parsons953b3562021-09-20 15:14:39 -040098func BazelLabelForModuleDepsExcludes(ctx TopDownMutatorContext, modules, excludes []string) bazel.LabelList {
99 return BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, BazelModuleLabel)
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400100}
101
Chris Parsons953b3562021-09-20 15:14:39 -0400102// BazelLabelForModuleDepsWithFn expects a list of reference to other modules, ("<module>"
103// or ":<module>") and applies moduleToLabelFn to determine and return a Bazel-compatible label
104// which corresponds to dependencies on the module within the given ctx.
105func BazelLabelForModuleDepsWithFn(ctx TopDownMutatorContext, modules []string,
106 moduleToLabelFn func(TopDownMutatorContext, blueprint.Module) string) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400107 var labels bazel.LabelList
Chris Parsons51f8c392021-08-03 21:01:05 -0400108 // In some cases, a nil string list is different than an explicitly empty list.
109 if len(modules) == 0 && modules != nil {
110 labels.Includes = []bazel.Label{}
111 return labels
112 }
Liz Kammer620dea62021-04-14 17:36:10 -0400113 for _, module := range modules {
114 bpText := module
115 if m := SrcIsModule(module); m == "" {
116 module = ":" + module
117 }
118 if m, t := SrcIsModuleWithTag(module); m != "" {
Chris Parsons953b3562021-09-20 15:14:39 -0400119 l := getOtherModuleLabel(ctx, m, t, moduleToLabelFn)
Jingwen Chen38e62642021-04-19 05:00:15 +0000120 l.OriginalModuleName = bpText
Liz Kammer620dea62021-04-14 17:36:10 -0400121 labels.Includes = append(labels.Includes, l)
122 } else {
123 ctx.ModuleErrorf("%q, is not a module reference", module)
124 }
125 }
126 return labels
127}
128
Chris Parsons953b3562021-09-20 15:14:39 -0400129// BazelLabelForModuleDepsExcludesWithFn expects two lists: modules (containing modules to include in the
130// list), and excludes (modules to exclude from the list). Both of these should contain references
131// to other modules, ("<module>" or ":<module>"). It applies moduleToLabelFn to determine and return a
132// Bazel-compatible label list which corresponds to dependencies on the module within the given ctx, and
133// the excluded dependencies.
134func BazelLabelForModuleDepsExcludesWithFn(ctx TopDownMutatorContext, modules, excludes []string,
135 moduleToLabelFn func(TopDownMutatorContext, blueprint.Module) string) bazel.LabelList {
136 moduleLabels := BazelLabelForModuleDepsWithFn(ctx, RemoveListFromList(modules, excludes), moduleToLabelFn)
Liz Kammer47535c52021-06-02 16:02:22 -0400137 if len(excludes) == 0 {
138 return moduleLabels
139 }
Chris Parsons953b3562021-09-20 15:14:39 -0400140 excludeLabels := BazelLabelForModuleDepsWithFn(ctx, excludes, moduleToLabelFn)
Liz Kammer47535c52021-06-02 16:02:22 -0400141 return bazel.LabelList{
142 Includes: moduleLabels.Includes,
143 Excludes: excludeLabels.Includes,
144 }
145}
146
Chris Parsons953b3562021-09-20 15:14:39 -0400147func BazelLabelForModuleSrcSingle(ctx TopDownMutatorContext, path string) bazel.Label {
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200148 return BazelLabelForModuleSrcExcludes(ctx, []string{path}, []string(nil)).Includes[0]
149}
150
Chris Parsons953b3562021-09-20 15:14:39 -0400151func BazelLabelForModuleDepSingle(ctx TopDownMutatorContext, path string) bazel.Label {
Rupert Shuttleworth6e4950a2021-07-27 01:34:59 -0400152 return BazelLabelForModuleDepsExcludes(ctx, []string{path}, []string(nil)).Includes[0]
153}
154
Liz Kammer620dea62021-04-14 17:36:10 -0400155// BazelLabelForModuleSrc expects a list of path (relative to local module directory) and module
156// references (":<module>") and returns a bazel.LabelList{} containing the resolved references in
157// paths, relative to the local module, or Bazel-labels (absolute if in a different package or
158// relative if within the same package).
159// Properties must have been annotated with struct tag `android:"path"` so that dependencies modules
160// will have already been handled by the path_deps mutator.
Chris Parsons953b3562021-09-20 15:14:39 -0400161func BazelLabelForModuleSrc(ctx TopDownMutatorContext, paths []string) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400162 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
163}
164
165// BazelLabelForModuleSrc expects lists of path and excludes (relative to local module directory)
166// and module references (":<module>") and returns a bazel.LabelList{} containing the resolved
167// references in paths, minus those in excludes, relative to the local module, or Bazel-labels
168// (absolute if in a different package or relative if within the same package).
169// Properties must have been annotated with struct tag `android:"path"` so that dependencies modules
170// will have already been handled by the path_deps mutator.
Chris Parsons953b3562021-09-20 15:14:39 -0400171func BazelLabelForModuleSrcExcludes(ctx TopDownMutatorContext, paths, excludes []string) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400172 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
173 excluded := make([]string, 0, len(excludeLabels.Includes))
174 for _, e := range excludeLabels.Includes {
175 excluded = append(excluded, e.Label)
176 }
177 labels := expandSrcsForBazel(ctx, paths, excluded)
178 labels.Excludes = excludeLabels.Includes
179 labels = transformSubpackagePaths(ctx, labels)
180 return labels
181}
182
183// Returns true if a prefix + components[:i] + /Android.bp exists
184// TODO(b/185358476) Could check for BUILD file instead of checking for Android.bp file, or ensure BUILD is always generated?
185func directoryHasBlueprint(fs pathtools.FileSystem, prefix string, components []string, componentIndex int) bool {
186 blueprintPath := prefix
187 if blueprintPath != "" {
188 blueprintPath = blueprintPath + "/"
189 }
190 blueprintPath = blueprintPath + strings.Join(components[:componentIndex+1], "/")
191 blueprintPath = blueprintPath + "/Android.bp"
192 if exists, _, _ := fs.Exists(blueprintPath); exists {
193 return true
194 } else {
195 return false
196 }
197}
198
199// Transform a path (if necessary) to acknowledge package boundaries
200//
201// e.g. something like
202// async_safe/include/async_safe/CHECK.h
203// might become
204// //bionic/libc/async_safe:include/async_safe/CHECK.h
205// if the "async_safe" directory is actually a package and not just a directory.
206//
207// In particular, paths that extend into packages are transformed into absolute labels beginning with //.
208func transformSubpackagePath(ctx BazelConversionPathContext, path bazel.Label) bazel.Label {
209 var newPath bazel.Label
210
Jingwen Chen38e62642021-04-19 05:00:15 +0000211 // Don't transform OriginalModuleName
212 newPath.OriginalModuleName = path.OriginalModuleName
Liz Kammer620dea62021-04-14 17:36:10 -0400213
214 if strings.HasPrefix(path.Label, "//") {
215 // Assume absolute labels are already correct (e.g. //path/to/some/package:foo.h)
216 newPath.Label = path.Label
217 return newPath
218 }
219
220 newLabel := ""
221 pathComponents := strings.Split(path.Label, "/")
222 foundBlueprint := false
223 // Check the deepest subdirectory first and work upwards
224 for i := len(pathComponents) - 1; i >= 0; i-- {
225 pathComponent := pathComponents[i]
226 var sep string
227 if !foundBlueprint && directoryHasBlueprint(ctx.Config().fs, ctx.ModuleDir(), pathComponents, i) {
228 sep = ":"
229 foundBlueprint = true
230 } else {
231 sep = "/"
232 }
233 if newLabel == "" {
234 newLabel = pathComponent
235 } else {
236 newLabel = pathComponent + sep + newLabel
237 }
238 }
239 if foundBlueprint {
240 // Ensure paths end up looking like //bionic/... instead of //./bionic/...
241 moduleDir := ctx.ModuleDir()
242 if strings.HasPrefix(moduleDir, ".") {
243 moduleDir = moduleDir[1:]
244 }
245 // Make the path into an absolute label (e.g. //bionic/libc/foo:bar.h instead of just foo:bar.h)
246 if moduleDir == "" {
247 newLabel = "//" + newLabel
248 } else {
249 newLabel = "//" + moduleDir + "/" + newLabel
250 }
251 }
252 newPath.Label = newLabel
253
254 return newPath
255}
256
257// Transform paths to acknowledge package boundaries
258// See transformSubpackagePath() for more information
259func transformSubpackagePaths(ctx BazelConversionPathContext, paths bazel.LabelList) bazel.LabelList {
260 var newPaths bazel.LabelList
261 for _, include := range paths.Includes {
262 newPaths.Includes = append(newPaths.Includes, transformSubpackagePath(ctx, include))
263 }
264 for _, exclude := range paths.Excludes {
265 newPaths.Excludes = append(newPaths.Excludes, transformSubpackagePath(ctx, exclude))
266 }
267 return newPaths
268}
269
270// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local source
271// directory and Bazel target labels, excluding those included in the excludes argument (which
272// should already be expanded to resolve references to Soong-modules). Valid elements of paths
273// include:
274// * filepath, relative to local module directory, resolves as a filepath relative to the local
275// source directory
276// * glob, relative to the local module directory, resolves as filepath(s), relative to the local
277// module directory. Because Soong does not have a concept of crossing package boundaries, the
278// glob as computed by Soong may contain paths that cross package-boundaries that would be
279// unknowingly omitted if the glob were handled by Bazel. To allow identification and detect
280// (within Bazel) use of paths that cross package boundaries, we expand globs within Soong rather
281// than converting Soong glob syntax to Bazel glob syntax. **Invalid for excludes.**
282// * other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
283// or OutputFileProducer. These resolve as a Bazel label for a target. If the Bazel target is in
284// the local module directory, it will be returned relative to the current package (e.g.
285// ":<target>"). Otherwise, it will be returned as an absolute Bazel label (e.g.
286// "//path/to/dir:<target>"). If the reference to another module cannot be resolved,the function
287// will panic.
288// Properties passed as the paths or excludes argument must have been annotated with struct tag
289// `android:"path"` so that dependencies on other modules will have already been handled by the
290// path_deps mutator.
Chris Parsons953b3562021-09-20 15:14:39 -0400291func expandSrcsForBazel(ctx TopDownMutatorContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400292 if paths == nil {
293 return bazel.LabelList{}
294 }
295 labels := bazel.LabelList{
296 Includes: []bazel.Label{},
297 }
Jingwen Chen4ecc67d2021-04-27 09:47:02 +0000298
299 // expandedExcludes contain module-dir relative paths, but root-relative paths
300 // are needed for GlobFiles later.
301 var rootRelativeExpandedExcludes []string
302 for _, e := range expandedExcludes {
303 rootRelativeExpandedExcludes = append(rootRelativeExpandedExcludes, filepath.Join(ctx.ModuleDir(), e))
304 }
305
Liz Kammer620dea62021-04-14 17:36:10 -0400306 for _, p := range paths {
307 if m, tag := SrcIsModuleWithTag(p); m != "" {
Chris Parsons953b3562021-09-20 15:14:39 -0400308 l := getOtherModuleLabel(ctx, m, tag, BazelModuleLabel)
Liz Kammer620dea62021-04-14 17:36:10 -0400309 if !InList(l.Label, expandedExcludes) {
Jingwen Chen38e62642021-04-19 05:00:15 +0000310 l.OriginalModuleName = fmt.Sprintf(":%s", m)
Liz Kammer620dea62021-04-14 17:36:10 -0400311 labels.Includes = append(labels.Includes, l)
312 }
313 } else {
314 var expandedPaths []bazel.Label
315 if pathtools.IsGlob(p) {
Jingwen Chen4ecc67d2021-04-27 09:47:02 +0000316 // e.g. turn "math/*.c" in
317 // external/arm-optimized-routines to external/arm-optimized-routines/math/*.c
318 rootRelativeGlobPath := pathForModuleSrc(ctx, p).String()
319 globbedPaths := GlobFiles(ctx, rootRelativeGlobPath, rootRelativeExpandedExcludes)
Liz Kammer620dea62021-04-14 17:36:10 -0400320 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
321 for _, path := range globbedPaths {
322 s := path.Rel()
323 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
324 }
325 } else {
326 if !InList(p, expandedExcludes) {
327 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
328 }
329 }
330 labels.Includes = append(labels.Includes, expandedPaths...)
331 }
332 }
333 return labels
334}
335
336// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
337// module. The label will be relative to the current directory if appropriate. The dependency must
338// already be resolved by either deps mutator or path deps mutator.
Chris Parsons953b3562021-09-20 15:14:39 -0400339func getOtherModuleLabel(ctx TopDownMutatorContext, dep, tag string,
340 labelFromModule func(TopDownMutatorContext, blueprint.Module) string) bazel.Label {
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400341 m, _ := ctx.ModuleFromName(dep)
Liz Kammer620dea62021-04-14 17:36:10 -0400342 if m == nil {
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400343 panic(fmt.Errorf("No module named %q found, but was a direct dep of %q", dep, ctx.Module().Name()))
Liz Kammer620dea62021-04-14 17:36:10 -0400344 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400345 if !convertedToBazel(ctx, m) {
346 ctx.AddUnconvertedBp2buildDep(dep)
347 }
Chris Parsons953b3562021-09-20 15:14:39 -0400348 label := BazelModuleLabel(ctx, ctx.Module())
349 otherLabel := labelFromModule(ctx, m)
350
351 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
352
Liz Kammer620dea62021-04-14 17:36:10 -0400353 if samePackage(label, otherLabel) {
354 otherLabel = bazelShortLabel(otherLabel)
355 }
356
357 return bazel.Label{
358 Label: otherLabel,
359 }
360}
361
Chris Parsons953b3562021-09-20 15:14:39 -0400362func BazelModuleLabel(ctx TopDownMutatorContext, module blueprint.Module) string {
Liz Kammer620dea62021-04-14 17:36:10 -0400363 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
Liz Kammer6eff3232021-08-26 08:37:59 -0400364 if !convertedToBazel(ctx, module) {
Liz Kammer620dea62021-04-14 17:36:10 -0400365 return bp2buildModuleLabel(ctx, module)
366 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400367 b, _ := module.(Bazelable)
Liz Kammer620dea62021-04-14 17:36:10 -0400368 return b.GetBazelLabel(ctx, module)
369}
370
371func bazelShortLabel(label string) string {
372 i := strings.Index(label, ":")
373 return label[i:]
374}
375
376func bazelPackage(label string) string {
377 i := strings.Index(label, ":")
378 return label[0:i]
379}
380
381func samePackage(label1, label2 string) bool {
382 return bazelPackage(label1) == bazelPackage(label2)
383}
384
385func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
386 moduleName := ctx.OtherModuleName(module)
387 moduleDir := ctx.OtherModuleDir(module)
388 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
389}
390
391// BazelOutPath is a Bazel output path compatible to be used for mixed builds within Soong/Ninja.
392type BazelOutPath struct {
393 OutputPath
394}
395
396var _ Path = BazelOutPath{}
397var _ objPathProvider = BazelOutPath{}
398
399func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
400 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
401}
402
403// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
404// bazel-owned outputs.
405func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
406 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
407 execRootPath := filepath.Join(execRootPathComponents...)
408 validatedExecRootPath, err := validatePath(execRootPath)
409 if err != nil {
410 reportPathError(ctx, err)
411 }
412
413 outputPath := OutputPath{basePath{"", ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200414 ctx.Config().soongOutDir,
Liz Kammer620dea62021-04-14 17:36:10 -0400415 ctx.Config().BazelContext.OutputBase()}
416
417 return BazelOutPath{
418 OutputPath: outputPath.withRel(validatedExecRootPath),
419 }
420}
Liz Kammerb6a55bf2021-04-12 15:42:51 -0400421
422// PathsForBazelOut returns a list of paths representing the paths under an output directory
423// dedicated to Bazel-owned outputs.
424func PathsForBazelOut(ctx PathContext, paths []string) Paths {
425 outs := make(Paths, 0, len(paths))
426 for _, p := range paths {
427 outs = append(outs, PathForBazelOut(ctx, p))
428 }
429 return outs
430}