blob: fad40beea96493afa069a1a38bbe841a0d609ddd [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// Copyright 2021 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.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Liz Kammeraabfb5d2021-12-08 15:25:06 -050019 "regexp"
Jingwen Chen3950cd62021-05-12 04:33:00 +000020 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040021
22 "android/soong/android"
23 "android/soong/bazel"
Liz Kammer7a210ac2021-09-22 15:52:58 -040024
Chris Parsons953b3562021-09-20 15:14:39 -040025 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040026
27 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040028)
29
Liz Kammerae3994e2021-10-19 09:45:48 -040030const (
Liz Kammer12615db2021-09-28 09:19:17 -040031 cSrcPartition = "c"
32 asSrcPartition = "as"
33 cppSrcPartition = "cpp"
34 protoSrcPartition = "proto"
Liz Kammerae3994e2021-10-19 09:45:48 -040035)
36
Liz Kammeraabfb5d2021-12-08 15:25:06 -050037var (
38 // ignoring case, checks for proto or protos as an independent word in the name, whether at the
39 // beginning, end, or middle. e.g. "proto.foo", "bar-protos", "baz_proto_srcs" would all match
40 filegroupLikelyProtoPattern = regexp.MustCompile("(?i)(^|[^a-z])proto(s)?([^a-z]|$)")
41)
42
Liz Kammer2222c6b2021-05-24 15:41:47 -040043// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000044// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040045type staticOrSharedAttributes struct {
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000046 Srcs bazel.LabelListAttribute
47 Srcs_c bazel.LabelListAttribute
48 Srcs_as bazel.LabelListAttribute
Liz Kammere6583482021-10-19 13:56:10 -040049 Hdrs bazel.LabelListAttribute
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000050 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000051
Liz Kammer12615db2021-09-28 09:19:17 -040052 Deps bazel.LabelListAttribute
53 Implementation_deps bazel.LabelListAttribute
54 Dynamic_deps bazel.LabelListAttribute
55 Implementation_dynamic_deps bazel.LabelListAttribute
56 Whole_archive_deps bazel.LabelListAttribute
57 Implementation_whole_archive_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040058
59 System_dynamic_deps bazel.LabelListAttribute
Jingwen Chen53681ef2021-04-29 08:15:13 +000060}
61
Jingwen Chen55bc8202021-11-02 06:40:51 +000062func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer12615db2021-09-28 09:19:17 -040063 // Check that a module is a filegroup type
64 isFilegroup := func(m blueprint.Module) bool {
65 return ctx.OtherModuleType(m) == "filegroup"
Jingwen Chen14a8bda2021-06-02 11:10:02 +000066 }
67
Liz Kammer57e2e7a2021-09-20 12:55:02 -040068 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
69 // macro.
70 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Liz Kammer12615db2021-09-28 09:19:17 -040071 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
72 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
73 labelStr := label.Label
74 if !exists || !isFilegroup(m) {
75 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000076 }
Liz Kammer12615db2021-09-28 09:19:17 -040077 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040078 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000079 }
80
Liz Kammer12615db2021-09-28 09:19:17 -040081 isProtoFilegroup := func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
82 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
83 labelStr := label.Label
84 if !exists || !isFilegroup(m) {
85 return labelStr, false
86 }
Liz Kammeraabfb5d2021-12-08 15:25:06 -050087 likelyProtos := filegroupLikelyProtoPattern.MatchString(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -040088 return labelStr, likelyProtos
89 }
90
Liz Kammer57e2e7a2021-09-20 12:55:02 -040091 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
92 partitioned := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Liz Kammeraabfb5d2021-12-08 15:25:06 -050093 protoSrcPartition: bazel.LabelPartition{Extensions: []string{".proto"}, LabelMapper: isProtoFilegroup},
94 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
95 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040096 // C++ is the "catch-all" group, and comprises generated sources because we don't
97 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -050098 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040099 })
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000100
Liz Kammerae3994e2021-10-19 09:45:48 -0400101 return partitioned
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000102}
103
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000104// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000105func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000106 lib, ok := module.compiler.(*libraryDecorator)
107 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400108 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000109 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000110 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
111}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000112
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000113// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000114func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000115 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000116}
117
118// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000119func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000120 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400121}
122
Liz Kammer7a210ac2021-09-22 15:52:58 -0400123type depsPartition struct {
124 export bazel.LabelList
125 implementation bazel.LabelList
126}
127
Jingwen Chen55bc8202021-11-02 06:40:51 +0000128type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400129
Jingwen Chen55bc8202021-11-02 06:40:51 +0000130func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400131 if !exportsDeps {
132 return depsPartition{
133 implementation: fn(ctx, allDeps),
134 }
135 }
136
Liz Kammer7a210ac2021-09-22 15:52:58 -0400137 implementation, export := android.FilterList(allDeps, exportedDeps)
138
139 return depsPartition{
140 export: fn(ctx, export),
141 implementation: fn(ctx, implementation),
142 }
143}
144
Jingwen Chen55bc8202021-11-02 06:40:51 +0000145type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400146
Jingwen Chen55bc8202021-11-02 06:40:51 +0000147func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400148 if !exportsDeps {
149 return depsPartition{
150 implementation: fn(ctx, allDeps, excludes),
151 }
152 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400153 implementation, export := android.FilterList(allDeps, exportedDeps)
154
155 return depsPartition{
156 export: fn(ctx, export, excludes),
157 implementation: fn(ctx, implementation, excludes),
158 }
159}
160
Jingwen Chen55bc8202021-11-02 06:40:51 +0000161func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400162 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000163
Liz Kammer9abd62d2021-05-21 08:37:59 -0400164 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000165 attrs.Copts.SetSelectValue(axis, config, props.Cflags)
166 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400167 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400168
Liz Kammer2b8004b2021-10-04 13:55:44 -0400169 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400170 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
171 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
172
Liz Kammer2b8004b2021-10-04 13:55:44 -0400173 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400174 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
175 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
176
177 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Jingwen Chenbcf53042021-05-26 04:42:42 +0000178 }
Liz Kammer135bf552021-08-11 10:46:06 -0400179 // system_dynamic_deps distinguishes between nil/empty list behavior:
180 // nil -> use default values
181 // empty list -> no values specified
182 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000183
184 if isStatic {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400185 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StaticProperties{}) {
186 for config, props := range configToProps {
187 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
188 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000189 }
190 }
191 }
192 } else {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400193 for axis, configToProps := range module.GetArchVariantProperties(ctx, &SharedProperties{}) {
194 for config, props := range configToProps {
195 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
196 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000197 }
198 }
199 }
200 }
201
Liz Kammerae3994e2021-10-19 09:45:48 -0400202 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
203 attrs.Srcs = partitionedSrcs[cppSrcPartition]
204 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
205 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000206
Liz Kammer12615db2021-09-28 09:19:17 -0400207 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
208 // TODO(b/208815215): determine whether this is used and add support if necessary
209 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
210 }
211
Jingwen Chenbcf53042021-05-26 04:42:42 +0000212 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000213}
214
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400215// Convenience struct to hold all attributes parsed from prebuilt properties.
216type prebuiltAttributes struct {
217 Src bazel.LabelAttribute
218}
219
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000220// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Jingwen Chen55bc8202021-11-02 06:40:51 +0000221func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400222 var srcLabelAttribute bazel.LabelAttribute
223
Liz Kammer9abd62d2021-05-21 08:37:59 -0400224 for axis, configToProps := range module.GetArchVariantProperties(ctx, &prebuiltLinkerProperties{}) {
225 for config, props := range configToProps {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400226 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
227 if len(prebuiltLinkerProperties.Srcs) > 1 {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400228 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most once source file for %s %s\n", axis, config)
229 continue
230 } else if len(prebuiltLinkerProperties.Srcs) == 0 {
231 continue
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400232 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400233 src := android.BazelLabelForModuleSrcSingle(ctx, prebuiltLinkerProperties.Srcs[0])
234 srcLabelAttribute.SetSelectValue(axis, config, src)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400235 }
236 }
237 }
238
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400239 return prebuiltAttributes{
240 Src: srcLabelAttribute,
241 }
242}
243
Liz Kammere6583482021-10-19 13:56:10 -0400244type baseAttributes struct {
245 compilerAttributes
246 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400247
248 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400249}
250
Jingwen Chen107c0de2021-04-09 10:43:12 +0000251// Convenience struct to hold all attributes parsed from compiler properties.
252type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400253 // Options for all languages
254 copts bazel.StringListAttribute
255 // Assembly options and sources
256 asFlags bazel.StringListAttribute
257 asSrcs bazel.LabelListAttribute
258 // C options and sources
259 conlyFlags bazel.StringListAttribute
260 cSrcs bazel.LabelListAttribute
261 // C++ options and sources
262 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000263 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400264
Liz Kammere6583482021-10-19 13:56:10 -0400265 hdrs bazel.LabelListAttribute
266
Chris Parsons2c788392021-08-10 11:58:07 -0400267 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000268
269 // Not affected by arch variants
270 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500271 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000272 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400273
274 localIncludes bazel.StringListAttribute
275 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400276
Liz Kammer1263d9b2021-12-10 14:28:20 -0500277 includes BazelIncludes
278
Liz Kammer12615db2021-09-28 09:19:17 -0400279 protoSrcs bazel.LabelListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000280}
281
Liz Kammere6583482021-10-19 13:56:10 -0400282func parseCommandLineFlags(soongFlags []string) []string {
283 var result []string
284 for _, flag := range soongFlags {
285 // Soong's cflags can contain spaces, like `-include header.h`. For
286 // Bazel's copts, split them up to be compatible with the
287 // no_copts_tokenization feature.
288 result = append(result, strings.Split(flag, " ")...)
289 }
290 return result
291}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000292
Jingwen Chen55bc8202021-11-02 06:40:51 +0000293func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400294 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
295 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
296 if srcsList, ok := parseSrcs(ctx, props); ok {
297 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400298 }
299
Liz Kammere6583482021-10-19 13:56:10 -0400300 localIncludeDirs := props.Local_include_dirs
301 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500302 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400303 if includeBuildDirectory(props.Include_build_directory) {
304 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400305 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000306 }
307
Liz Kammere6583482021-10-19 13:56:10 -0400308 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
309 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
310
311 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags))
312 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags))
313 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags))
314 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags))
315 ca.rtti.SetSelectValue(axis, config, props.Rtti)
316}
317
Jingwen Chen55bc8202021-11-02 06:40:51 +0000318func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Liz Kammere6583482021-10-19 13:56:10 -0400319 stlPropsByArch := module.GetArchVariantProperties(ctx, &StlProperties{})
320 for _, configToProps := range stlPropsByArch {
321 for _, props := range configToProps {
322 if stlProps, ok := props.(*StlProperties); ok {
323 if stlProps.Stl == nil {
324 continue
Liz Kammer9abd62d2021-05-21 08:37:59 -0400325 }
Liz Kammere6583482021-10-19 13:56:10 -0400326 if ca.stl == nil {
327 ca.stl = stlProps.Stl
328 } else if ca.stl != stlProps.Stl {
329 ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
Liz Kammerae3994e2021-10-19 09:45:48 -0400330 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400331 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000332 }
333 }
Liz Kammere6583482021-10-19 13:56:10 -0400334}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000335
Jingwen Chen55bc8202021-11-02 06:40:51 +0000336func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400337 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400338 "Cflags": &ca.copts,
339 "Asflags": &ca.asFlags,
340 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400341 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400342 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000343 if productConfigProps, exists := productVariableProps[propName]; exists {
344 for productConfigProp, prop := range productConfigProps {
345 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400346 if !ok {
347 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
348 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000349 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
350 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400351 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400352 }
353 }
Liz Kammere6583482021-10-19 13:56:10 -0400354}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400355
Jingwen Chen55bc8202021-11-02 06:40:51 +0000356func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400357 ca.srcs.ResolveExcludes()
358 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
359
Liz Kammer12615db2021-09-28 09:19:17 -0400360 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
361
Liz Kammere6583482021-10-19 13:56:10 -0400362 for p, lla := range partitionedSrcs {
363 // if there are no sources, there is no need for headers
364 if lla.IsEmpty() {
365 continue
366 }
367 lla.Append(implementationHdrs)
368 partitionedSrcs[p] = lla
369 }
370
371 ca.srcs = partitionedSrcs[cppSrcPartition]
372 ca.cSrcs = partitionedSrcs[cSrcPartition]
373 ca.asSrcs = partitionedSrcs[asSrcPartition]
374
375 ca.absoluteIncludes.DeduplicateAxesFromBase()
376 ca.localIncludes.DeduplicateAxesFromBase()
377}
378
379// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000380func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400381 anySrcs := false
382 // Add srcs-like dependencies such as generated files.
383 // First create a LabelList containing these dependencies, then merge the values with srcs.
384 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
385 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
386 anySrcs = true
387 }
388
389 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
390 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
391 anySrcs = true
392 }
393 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
394}
395
Chris Parsons79bd2b72021-11-29 17:52:41 -0500396func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
397 var cStdVal, cppStdVal string
398 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
399 // Defaults are handled by the toolchain definition.
400 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammere6583482021-10-19 13:56:10 -0400401 if cpp_std != nil {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500402 cppStdVal = parseCppStd(cpp_std)
Liz Kammere6583482021-10-19 13:56:10 -0400403 } else if gnu_extensions != nil && !*gnu_extensions {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500404 cppStdVal = "c++17"
Liz Kammere6583482021-10-19 13:56:10 -0400405 }
Chris Parsons79bd2b72021-11-29 17:52:41 -0500406 if c_std != nil {
407 cStdVal = parseCStd(c_std)
408 } else if gnu_extensions != nil && !*gnu_extensions {
409 cStdVal = "c99"
410 }
411
412 cStdVal, cppStdVal = maybeReplaceGnuToC(gnu_extensions, cStdVal, cppStdVal)
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500413 var c_std_prop, cpp_std_prop *string
414 if cStdVal != "" {
415 c_std_prop = &cStdVal
416 }
417 if cppStdVal != "" {
418 cpp_std_prop = &cppStdVal
419 }
420
421 return c_std_prop, cpp_std_prop
Liz Kammere6583482021-10-19 13:56:10 -0400422}
423
Liz Kammer1263d9b2021-12-10 14:28:20 -0500424// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
425// is fully-qualified.
426// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
427func packageFromLabel(label string) (string, bool) {
428 split := strings.Split(label, ":")
429 if len(split) != 2 {
430 return "", false
431 }
432 if split[0] == "" {
433 return ".", false
434 }
435 // remove leading "//"
436 return split[0][2:], true
437}
438
439// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
440func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
441 for _, hdr := range labelList.Includes {
442 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
443 absolute = append(absolute, pkg)
444 } else if pkg != "" {
445 relative = append(relative, pkg)
446 }
447 }
448 return relative, absolute
449}
450
Liz Kammere6583482021-10-19 13:56:10 -0400451// bp2BuildParseCompilerProps returns copts, srcs and hdrs and other attributes.
Liz Kammer12615db2021-09-28 09:19:17 -0400452func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400453 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
454 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
455
456 var implementationHdrs bazel.LabelListAttribute
457
458 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
459 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
460 for axis, configMap := range cp {
461 if _, ok := axisToConfigs[axis]; !ok {
462 axisToConfigs[axis] = map[string]bool{}
463 }
464 for config, _ := range configMap {
465 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400466 }
467 }
468 }
Liz Kammere6583482021-10-19 13:56:10 -0400469 allAxesAndConfigs(archVariantCompilerProps)
470 allAxesAndConfigs(archVariantLinkerProps)
Chris Parsonsa967f252021-09-23 16:34:35 -0400471
Liz Kammere6583482021-10-19 13:56:10 -0400472 compilerAttrs := compilerAttributes{}
473 linkerAttrs := linkerAttributes{}
474
475 for axis, configs := range axisToConfigs {
476 for config, _ := range configs {
477 var allHdrs []string
478 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
479 allHdrs = baseCompilerProps.Generated_headers
480
481 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
482 }
483
484 var exportHdrs []string
485
486 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
487 exportHdrs = baseLinkerProps.Export_generated_headers
488
489 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
490 }
491 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
492 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
493 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500494
495 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
496 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
497 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
498
499 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
500 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
501 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
502 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
503 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
504 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
505 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Liz Kammere6583482021-10-19 13:56:10 -0400506 }
507 }
508
509 compilerAttrs.convertStlProps(ctx, module)
510 (&linkerAttrs).convertStripProps(ctx, module)
511
512 productVariableProps := android.ProductVariableProperties(ctx)
513
514 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
515 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
516
517 (&compilerAttrs).finalize(ctx, implementationHdrs)
518 (&linkerAttrs).finalize()
519
Liz Kammer12615db2021-09-28 09:19:17 -0400520 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
521
522 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
523 // which. This will add the newly generated proto library to the appropriate attribute and nothing
524 // to the other
525 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
526 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
527
Liz Kammere6583482021-10-19 13:56:10 -0400528 return baseAttributes{
529 compilerAttrs,
530 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400531 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000532 }
533}
534
535// Convenience struct to hold all attributes parsed from linker properties.
536type linkerAttributes struct {
Liz Kammer12615db2021-09-28 09:19:17 -0400537 deps bazel.LabelListAttribute
538 implementationDeps bazel.LabelListAttribute
539 dynamicDeps bazel.LabelListAttribute
540 implementationDynamicDeps bazel.LabelListAttribute
541 wholeArchiveDeps bazel.LabelListAttribute
542 implementationWholeArchiveDeps bazel.LabelListAttribute
543 systemDynamicDeps bazel.LabelListAttribute
Liz Kammer7a210ac2021-09-22 15:52:58 -0400544
Jingwen Chen6ada5892021-09-17 11:38:09 +0000545 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000546 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500547 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000548 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400549 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000550 stripKeepSymbols bazel.BoolAttribute
551 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
552 stripKeepSymbolsList bazel.StringListAttribute
553 stripAll bazel.BoolAttribute
554 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400555 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400556}
557
Jingwen Chen55bc8202021-11-02 06:40:51 +0000558func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400559 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
560 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400561
Liz Kammere6583482021-10-19 13:56:10 -0400562 // Excludes to parallel Soong:
563 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
564 staticLibs := android.FirstUniqueStrings(props.Static_libs)
565 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400566
Liz Kammere6583482021-10-19 13:56:10 -0400567 headerLibs := android.FirstUniqueStrings(props.Header_libs)
568 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400569
Liz Kammere6583482021-10-19 13:56:10 -0400570 (&hDeps.export).Append(staticDeps.export)
571 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000572
Liz Kammere6583482021-10-19 13:56:10 -0400573 (&hDeps.implementation).Append(staticDeps.implementation)
574 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400575
Liz Kammere6583482021-10-19 13:56:10 -0400576 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
577 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
578
579 systemSharedLibs := props.System_shared_libs
580 // systemSharedLibs distinguishes between nil/empty list behavior:
581 // nil -> use default values
582 // empty list -> no values specified
583 if len(systemSharedLibs) > 0 {
584 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
585 }
586 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
587
588 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
589 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
590 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
591 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
592
593 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
594 axisFeatures = append(axisFeatures, "disable_pack_relocations")
595 }
596
597 if Bool(props.Allow_undefined_symbols) {
598 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
599 }
600
601 var linkerFlags []string
602 if len(props.Ldflags) > 0 {
603 linkerFlags = append(linkerFlags, props.Ldflags...)
604 // binaries remove static flag if -shared is in the linker flags
605 if isBinary && android.InList("-shared", linkerFlags) {
606 axisFeatures = append(axisFeatures, "-static_flag")
607 }
608 }
609 if props.Version_script != nil {
610 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
611 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
612 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
613 }
614 la.linkopts.SetSelectValue(axis, config, linkerFlags)
615 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
616
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500617 if axis == bazel.NoConfigAxis {
618 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
619 }
620
Liz Kammere6583482021-10-19 13:56:10 -0400621 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
622 if props.crt() != nil {
623 if axis == bazel.NoConfigAxis {
624 la.linkCrt.SetSelectValue(axis, config, props.crt())
625 } else if axis == bazel.ArchConfigurationAxis {
626 ctx.ModuleErrorf("nocrt is not supported for arch variants")
627 }
628 }
629
630 if axisFeatures != nil {
631 la.features.SetSelectValue(axis, config, axisFeatures)
632 }
633}
634
Jingwen Chen55bc8202021-11-02 06:40:51 +0000635func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000636 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StripProperties{}) {
637 for config, props := range configToProps {
638 if stripProperties, ok := props.(*StripProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400639 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
640 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
641 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
642 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
643 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000644 }
645 }
646 }
Liz Kammere6583482021-10-19 13:56:10 -0400647}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000648
Jingwen Chen55bc8202021-11-02 06:40:51 +0000649func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000650
Liz Kammer47535c52021-06-02 16:02:22 -0400651 type productVarDep struct {
652 // the name of the corresponding excludes field, if one exists
653 excludesField string
654 // reference to the bazel attribute that should be set for the given product variable config
655 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400656
Jingwen Chen55bc8202021-11-02 06:40:51 +0000657 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400658 }
659
660 productVarToDepFields := map[string]productVarDep{
661 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000662 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
663 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
664 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400665 }
666
Liz Kammer47535c52021-06-02 16:02:22 -0400667 for name, dep := range productVarToDepFields {
668 props, exists := productVariableProps[name]
669 excludeProps, excludesExists := productVariableProps[dep.excludesField]
670 // if neither an include or excludes property exists, then skip it
671 if !exists && !excludesExists {
672 continue
673 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000674 // Collect all the configurations that an include or exclude property exists for.
675 // We want to iterate all configurations rather than either the include or exclude because, for a
676 // particular configuration, we may have either only an include or an exclude to handle.
677 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
678 for p := range props {
679 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400680 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000681 for p := range excludeProps {
682 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400683 }
684
Jingwen Chen25825ca2021-11-15 12:28:43 +0000685 for productConfigProp := range productConfigProps {
686 prop, includesExists := props[productConfigProp]
687 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400688 var includes, excludes []string
689 var ok bool
690 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000691 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400692 ctx.ModuleErrorf("Could not convert product variable %s property", name)
693 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000694 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400695 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
696 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400697
Jingwen Chen58ff6802021-11-17 12:14:41 +0000698 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000699 dep.attribute.SetSelectValue(
700 productConfigProp.ConfigurationAxis(),
701 productConfigProp.SelectKey(),
702 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
703 )
Liz Kammer47535c52021-06-02 16:02:22 -0400704 }
705 }
Liz Kammere6583482021-10-19 13:56:10 -0400706}
Liz Kammer47535c52021-06-02 16:02:22 -0400707
Liz Kammere6583482021-10-19 13:56:10 -0400708func (la *linkerAttributes) finalize() {
709 la.deps.ResolveExcludes()
710 la.implementationDeps.ResolveExcludes()
711 la.dynamicDeps.ResolveExcludes()
712 la.implementationDynamicDeps.ResolveExcludes()
713 la.wholeArchiveDeps.ResolveExcludes()
714 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Jingwen Chen91220d72021-03-24 02:18:33 -0400715}
716
Jingwen Chened9c17d2021-04-13 07:14:55 +0000717// Relativize a list of root-relative paths with respect to the module's
718// directory.
719//
720// include_dirs Soong prop are root-relative (b/183742505), but
721// local_include_dirs, export_include_dirs and export_system_include_dirs are
722// module dir relative. This function makes a list of paths entirely module dir
723// relative.
724//
725// For the `include` attribute, Bazel wants the paths to be relative to the
726// module.
727func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000728 var relativePaths []string
729 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000730 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
731 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
732 if err != nil {
733 panic(err)
734 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000735 relativePaths = append(relativePaths, relativePath)
736 }
737 return relativePaths
738}
739
Liz Kammer5fad5012021-09-09 14:08:21 -0400740// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
741// attributes.
742type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500743 AbsoluteIncludes bazel.StringListAttribute
744 Includes bazel.StringListAttribute
745 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400746}
747
Liz Kammer1263d9b2021-12-10 14:28:20 -0500748func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, existingIncludes BazelIncludes) BazelIncludes {
Jingwen Chen91220d72021-03-24 02:18:33 -0400749 libraryDecorator := module.linker.(*libraryDecorator)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500750 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, &existingIncludes)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400751}
Jingwen Chen91220d72021-03-24 02:18:33 -0400752
Liz Kammer5fad5012021-09-09 14:08:21 -0400753// Bp2buildParseExportedIncludesForPrebuiltLibrary returns a BazelIncludes with Bazel-ified values
754// to export includes from the underlying module's properties.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000755func Bp2BuildParseExportedIncludesForPrebuiltLibrary(ctx android.BazelConversionPathContext, module *Module) BazelIncludes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400756 prebuiltLibraryLinker := module.linker.(*prebuiltLibraryLinker)
757 libraryDecorator := prebuiltLibraryLinker.libraryDecorator
Liz Kammer1263d9b2021-12-10 14:28:20 -0500758 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, nil)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400759}
760
761// bp2BuildParseExportedIncludes creates a string list attribute contains the
762// exported included directories of a module.
Liz Kammer1263d9b2021-12-10 14:28:20 -0500763func bp2BuildParseExportedIncludesHelper(ctx android.BazelConversionPathContext, module *Module, libraryDecorator *libraryDecorator, includes *BazelIncludes) BazelIncludes {
764 var exported BazelIncludes
765 if includes != nil {
766 exported = *includes
767 } else {
768 exported = BazelIncludes{}
769 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400770 for axis, configToProps := range module.GetArchVariantProperties(ctx, &FlagExporterProperties{}) {
771 for config, props := range configToProps {
772 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
Liz Kammer5fad5012021-09-09 14:08:21 -0400773 if len(flagExporterProperties.Export_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500774 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
Liz Kammer5fad5012021-09-09 14:08:21 -0400775 }
776 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500777 exported.SystemIncludes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.SystemIncludes.SelectValue(axis, config), flagExporterProperties.Export_system_include_dirs...)))
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400778 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400779 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400780 }
781 }
Liz Kammer1263d9b2021-12-10 14:28:20 -0500782 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400783 exported.Includes.DeduplicateAxesFromBase()
784 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400785
Liz Kammer5fad5012021-09-09 14:08:21 -0400786 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400787}
Chris Parsons953b3562021-09-20 15:14:39 -0400788
Jingwen Chen55bc8202021-11-02 06:40:51 +0000789func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400790 label := android.BazelModuleLabel(ctx, m)
791 if aModule, ok := m.(android.Module); ok {
792 if ctx.OtherModuleType(aModule) == "cc_library" && !android.GenerateCcLibraryStaticOnly(m.Name()) {
793 label += "_bp2build_cc_library_static"
794 }
795 }
796 return label
797}
798
Jingwen Chen55bc8202021-11-02 06:40:51 +0000799func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400800 // cc_library, at it's root name, propagates the shared library, which depends on the static
801 // library.
802 return android.BazelModuleLabel(ctx, m)
803}
804
Jingwen Chen55bc8202021-11-02 06:40:51 +0000805func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400806 label := bazelLabelForStaticModule(ctx, m)
807 if aModule, ok := m.(android.Module); ok {
808 if android.IsModulePrebuilt(aModule) {
809 label += "_alwayslink"
810 }
811 }
812 return label
813}
814
Jingwen Chen55bc8202021-11-02 06:40:51 +0000815func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400816 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
817}
818
Jingwen Chen55bc8202021-11-02 06:40:51 +0000819func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400820 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
821}
822
Jingwen Chen55bc8202021-11-02 06:40:51 +0000823func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400824 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
825}
826
Jingwen Chen55bc8202021-11-02 06:40:51 +0000827func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400828 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
829}
830
Jingwen Chen55bc8202021-11-02 06:40:51 +0000831func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400832 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
833}
834
Jingwen Chen55bc8202021-11-02 06:40:51 +0000835func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400836 // This is not elegant, but bp2build's shared library targets only propagate
837 // their header information as part of the normal C++ provider.
838 return bazelLabelForSharedDeps(ctx, modules)
839}
840
Jingwen Chen55bc8202021-11-02 06:40:51 +0000841func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400842 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
843}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400844
845type binaryLinkerAttrs struct {
846 Linkshared *bool
847}
848
Jingwen Chen55bc8202021-11-02 06:40:51 +0000849func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400850 attrs := binaryLinkerAttrs{}
851 archVariantProps := m.GetArchVariantProperties(ctx, &BinaryLinkerProperties{})
852 for axis, configToProps := range archVariantProps {
853 for _, p := range configToProps {
854 props := p.(*BinaryLinkerProperties)
855 staticExecutable := props.Static_executable
856 if axis == bazel.NoConfigAxis {
857 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
858 attrs.Linkshared = &linkBinaryShared
859 }
860 } else if staticExecutable != nil {
861 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
862 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
863 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
864 }
865 }
866 }
867
868 return attrs
869}