blob: cc2e60e5747fd4c53f070713f91206bbadb919c3 [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
Chris Parsons58852a02021-12-09 18:10:18 -050060
61 Enabled bazel.BoolAttribute
Jingwen Chen53681ef2021-04-29 08:15:13 +000062}
63
Jingwen Chen55bc8202021-11-02 06:40:51 +000064func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer12615db2021-09-28 09:19:17 -040065 // Check that a module is a filegroup type
66 isFilegroup := func(m blueprint.Module) bool {
67 return ctx.OtherModuleType(m) == "filegroup"
Jingwen Chen14a8bda2021-06-02 11:10:02 +000068 }
69
Liz Kammer57e2e7a2021-09-20 12:55:02 -040070 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
71 // macro.
72 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Liz Kammer12615db2021-09-28 09:19:17 -040073 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
74 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
75 labelStr := label.Label
76 if !exists || !isFilegroup(m) {
77 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000078 }
Liz Kammer12615db2021-09-28 09:19:17 -040079 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040080 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000081 }
82
Liz Kammer12615db2021-09-28 09:19:17 -040083 isProtoFilegroup := func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
84 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
85 labelStr := label.Label
86 if !exists || !isFilegroup(m) {
87 return labelStr, false
88 }
Liz Kammeraabfb5d2021-12-08 15:25:06 -050089 likelyProtos := filegroupLikelyProtoPattern.MatchString(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -040090 return labelStr, likelyProtos
91 }
92
Liz Kammer57e2e7a2021-09-20 12:55:02 -040093 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
94 partitioned := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Liz Kammeraabfb5d2021-12-08 15:25:06 -050095 protoSrcPartition: bazel.LabelPartition{Extensions: []string{".proto"}, LabelMapper: isProtoFilegroup},
96 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
97 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040098 // C++ is the "catch-all" group, and comprises generated sources because we don't
99 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500100 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400101 })
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000102
Liz Kammerae3994e2021-10-19 09:45:48 -0400103 return partitioned
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000104}
105
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000106// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000107func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000108 lib, ok := module.compiler.(*libraryDecorator)
109 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400110 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000111 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000112 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
113}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000114
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000115// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000116func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000117 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000118}
119
120// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000121func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000122 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400123}
124
Liz Kammer7a210ac2021-09-22 15:52:58 -0400125type depsPartition struct {
126 export bazel.LabelList
127 implementation bazel.LabelList
128}
129
Jingwen Chen55bc8202021-11-02 06:40:51 +0000130type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400131
Jingwen Chen55bc8202021-11-02 06:40:51 +0000132func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400133 if !exportsDeps {
134 return depsPartition{
135 implementation: fn(ctx, allDeps),
136 }
137 }
138
Liz Kammer7a210ac2021-09-22 15:52:58 -0400139 implementation, export := android.FilterList(allDeps, exportedDeps)
140
141 return depsPartition{
142 export: fn(ctx, export),
143 implementation: fn(ctx, implementation),
144 }
145}
146
Jingwen Chen55bc8202021-11-02 06:40:51 +0000147type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400148
Jingwen Chen55bc8202021-11-02 06:40:51 +0000149func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400150 if !exportsDeps {
151 return depsPartition{
152 implementation: fn(ctx, allDeps, excludes),
153 }
154 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400155 implementation, export := android.FilterList(allDeps, exportedDeps)
156
157 return depsPartition{
158 export: fn(ctx, export, excludes),
159 implementation: fn(ctx, implementation, excludes),
160 }
161}
162
Jingwen Chen55bc8202021-11-02 06:40:51 +0000163func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400164 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000165
Liz Kammer9abd62d2021-05-21 08:37:59 -0400166 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Liz Kammercac7f692021-12-16 14:19:32 -0500167 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000168 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400169 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400170
Liz Kammer2b8004b2021-10-04 13:55:44 -0400171 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400172 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
173 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
174
Liz Kammer2b8004b2021-10-04 13:55:44 -0400175 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400176 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
177 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
178
179 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500180 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000181 }
Liz Kammer135bf552021-08-11 10:46:06 -0400182 // system_dynamic_deps distinguishes between nil/empty list behavior:
183 // nil -> use default values
184 // empty list -> no values specified
185 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000186
187 if isStatic {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400188 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StaticProperties{}) {
189 for config, props := range configToProps {
190 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
191 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000192 }
193 }
194 }
195 } else {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400196 for axis, configToProps := range module.GetArchVariantProperties(ctx, &SharedProperties{}) {
197 for config, props := range configToProps {
198 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
199 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000200 }
201 }
202 }
203 }
204
Liz Kammerae3994e2021-10-19 09:45:48 -0400205 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
206 attrs.Srcs = partitionedSrcs[cppSrcPartition]
207 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
208 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000209
Liz Kammer12615db2021-09-28 09:19:17 -0400210 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
211 // TODO(b/208815215): determine whether this is used and add support if necessary
212 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
213 }
214
Jingwen Chenbcf53042021-05-26 04:42:42 +0000215 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000216}
217
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400218// Convenience struct to hold all attributes parsed from prebuilt properties.
219type prebuiltAttributes struct {
220 Src bazel.LabelAttribute
221}
222
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000223// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Jingwen Chen55bc8202021-11-02 06:40:51 +0000224func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400225 var srcLabelAttribute bazel.LabelAttribute
226
Liz Kammer9abd62d2021-05-21 08:37:59 -0400227 for axis, configToProps := range module.GetArchVariantProperties(ctx, &prebuiltLinkerProperties{}) {
228 for config, props := range configToProps {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400229 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
230 if len(prebuiltLinkerProperties.Srcs) > 1 {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400231 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most once source file for %s %s\n", axis, config)
232 continue
233 } else if len(prebuiltLinkerProperties.Srcs) == 0 {
234 continue
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400235 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400236 src := android.BazelLabelForModuleSrcSingle(ctx, prebuiltLinkerProperties.Srcs[0])
237 srcLabelAttribute.SetSelectValue(axis, config, src)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400238 }
239 }
240 }
241
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400242 return prebuiltAttributes{
243 Src: srcLabelAttribute,
244 }
245}
246
Liz Kammere6583482021-10-19 13:56:10 -0400247type baseAttributes struct {
248 compilerAttributes
249 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400250
251 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400252}
253
Jingwen Chen107c0de2021-04-09 10:43:12 +0000254// Convenience struct to hold all attributes parsed from compiler properties.
255type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400256 // Options for all languages
257 copts bazel.StringListAttribute
258 // Assembly options and sources
259 asFlags bazel.StringListAttribute
260 asSrcs bazel.LabelListAttribute
261 // C options and sources
262 conlyFlags bazel.StringListAttribute
263 cSrcs bazel.LabelListAttribute
264 // C++ options and sources
265 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000266 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400267
Liz Kammere6583482021-10-19 13:56:10 -0400268 hdrs bazel.LabelListAttribute
269
Chris Parsons2c788392021-08-10 11:58:07 -0400270 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000271
272 // Not affected by arch variants
273 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500274 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000275 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400276
277 localIncludes bazel.StringListAttribute
278 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400279
Liz Kammer1263d9b2021-12-10 14:28:20 -0500280 includes BazelIncludes
281
Liz Kammer12615db2021-09-28 09:19:17 -0400282 protoSrcs bazel.LabelListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000283}
284
Liz Kammercac7f692021-12-16 14:19:32 -0500285type filterOutFn func(string) bool
286
287func filterOutStdFlag(flag string) bool {
288 return strings.HasPrefix(flag, "-std=")
289}
290
291func parseCommandLineFlags(soongFlags []string, filterOut filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400292 var result []string
293 for _, flag := range soongFlags {
Liz Kammercac7f692021-12-16 14:19:32 -0500294 if filterOut != nil && filterOut(flag) {
295 continue
296 }
Liz Kammere6583482021-10-19 13:56:10 -0400297 // Soong's cflags can contain spaces, like `-include header.h`. For
298 // Bazel's copts, split them up to be compatible with the
299 // no_copts_tokenization feature.
300 result = append(result, strings.Split(flag, " ")...)
301 }
302 return result
303}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000304
Jingwen Chen55bc8202021-11-02 06:40:51 +0000305func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400306 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
307 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
308 if srcsList, ok := parseSrcs(ctx, props); ok {
309 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400310 }
311
Liz Kammere6583482021-10-19 13:56:10 -0400312 localIncludeDirs := props.Local_include_dirs
313 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500314 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400315 if includeBuildDirectory(props.Include_build_directory) {
316 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400317 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000318 }
319
Liz Kammere6583482021-10-19 13:56:10 -0400320 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
321 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
322
Liz Kammercac7f692021-12-16 14:19:32 -0500323 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
324 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
325 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
326 // cases.
327 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
328 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
329 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, nil))
330 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, nil))
Liz Kammere6583482021-10-19 13:56:10 -0400331 ca.rtti.SetSelectValue(axis, config, props.Rtti)
332}
333
Jingwen Chen55bc8202021-11-02 06:40:51 +0000334func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Liz Kammere6583482021-10-19 13:56:10 -0400335 stlPropsByArch := module.GetArchVariantProperties(ctx, &StlProperties{})
336 for _, configToProps := range stlPropsByArch {
337 for _, props := range configToProps {
338 if stlProps, ok := props.(*StlProperties); ok {
339 if stlProps.Stl == nil {
340 continue
Liz Kammer9abd62d2021-05-21 08:37:59 -0400341 }
Liz Kammere6583482021-10-19 13:56:10 -0400342 if ca.stl == nil {
343 ca.stl = stlProps.Stl
344 } else if ca.stl != stlProps.Stl {
345 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 -0400346 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400347 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000348 }
349 }
Liz Kammere6583482021-10-19 13:56:10 -0400350}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000351
Jingwen Chen55bc8202021-11-02 06:40:51 +0000352func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400353 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400354 "Cflags": &ca.copts,
355 "Asflags": &ca.asFlags,
356 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400357 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400358 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000359 if productConfigProps, exists := productVariableProps[propName]; exists {
360 for productConfigProp, prop := range productConfigProps {
361 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400362 if !ok {
363 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
364 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000365 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
366 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400367 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400368 }
369 }
Liz Kammere6583482021-10-19 13:56:10 -0400370}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400371
Jingwen Chen55bc8202021-11-02 06:40:51 +0000372func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400373 ca.srcs.ResolveExcludes()
374 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
375
Liz Kammer12615db2021-09-28 09:19:17 -0400376 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
377
Liz Kammere6583482021-10-19 13:56:10 -0400378 for p, lla := range partitionedSrcs {
379 // if there are no sources, there is no need for headers
380 if lla.IsEmpty() {
381 continue
382 }
383 lla.Append(implementationHdrs)
384 partitionedSrcs[p] = lla
385 }
386
387 ca.srcs = partitionedSrcs[cppSrcPartition]
388 ca.cSrcs = partitionedSrcs[cSrcPartition]
389 ca.asSrcs = partitionedSrcs[asSrcPartition]
390
391 ca.absoluteIncludes.DeduplicateAxesFromBase()
392 ca.localIncludes.DeduplicateAxesFromBase()
393}
394
395// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000396func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400397 anySrcs := false
398 // Add srcs-like dependencies such as generated files.
399 // First create a LabelList containing these dependencies, then merge the values with srcs.
400 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
401 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
402 anySrcs = true
403 }
404
405 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
406 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
407 anySrcs = true
408 }
409 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
410}
411
Chris Parsons79bd2b72021-11-29 17:52:41 -0500412func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
413 var cStdVal, cppStdVal string
414 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
415 // Defaults are handled by the toolchain definition.
416 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammere6583482021-10-19 13:56:10 -0400417 if cpp_std != nil {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500418 cppStdVal = parseCppStd(cpp_std)
Liz Kammere6583482021-10-19 13:56:10 -0400419 } else if gnu_extensions != nil && !*gnu_extensions {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500420 cppStdVal = "c++17"
Liz Kammere6583482021-10-19 13:56:10 -0400421 }
Chris Parsons79bd2b72021-11-29 17:52:41 -0500422 if c_std != nil {
423 cStdVal = parseCStd(c_std)
424 } else if gnu_extensions != nil && !*gnu_extensions {
425 cStdVal = "c99"
426 }
427
428 cStdVal, cppStdVal = maybeReplaceGnuToC(gnu_extensions, cStdVal, cppStdVal)
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500429 var c_std_prop, cpp_std_prop *string
430 if cStdVal != "" {
431 c_std_prop = &cStdVal
432 }
433 if cppStdVal != "" {
434 cpp_std_prop = &cppStdVal
435 }
436
437 return c_std_prop, cpp_std_prop
Liz Kammere6583482021-10-19 13:56:10 -0400438}
439
Liz Kammer1263d9b2021-12-10 14:28:20 -0500440// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
441// is fully-qualified.
442// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
443func packageFromLabel(label string) (string, bool) {
444 split := strings.Split(label, ":")
445 if len(split) != 2 {
446 return "", false
447 }
448 if split[0] == "" {
449 return ".", false
450 }
451 // remove leading "//"
452 return split[0][2:], true
453}
454
455// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
456func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
457 for _, hdr := range labelList.Includes {
458 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
459 absolute = append(absolute, pkg)
460 } else if pkg != "" {
461 relative = append(relative, pkg)
462 }
463 }
464 return relative, absolute
465}
466
Liz Kammere6583482021-10-19 13:56:10 -0400467// bp2BuildParseCompilerProps returns copts, srcs and hdrs and other attributes.
Liz Kammer12615db2021-09-28 09:19:17 -0400468func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400469 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
470 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
471
472 var implementationHdrs bazel.LabelListAttribute
473
474 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
475 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
476 for axis, configMap := range cp {
477 if _, ok := axisToConfigs[axis]; !ok {
478 axisToConfigs[axis] = map[string]bool{}
479 }
480 for config, _ := range configMap {
481 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400482 }
483 }
484 }
Liz Kammere6583482021-10-19 13:56:10 -0400485 allAxesAndConfigs(archVariantCompilerProps)
486 allAxesAndConfigs(archVariantLinkerProps)
Chris Parsonsa967f252021-09-23 16:34:35 -0400487
Liz Kammere6583482021-10-19 13:56:10 -0400488 compilerAttrs := compilerAttributes{}
489 linkerAttrs := linkerAttributes{}
490
491 for axis, configs := range axisToConfigs {
492 for config, _ := range configs {
493 var allHdrs []string
494 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
495 allHdrs = baseCompilerProps.Generated_headers
496
497 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
498 }
499
500 var exportHdrs []string
501
502 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
503 exportHdrs = baseLinkerProps.Export_generated_headers
504
505 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
506 }
507 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
508 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
509 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500510
511 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
512 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
513 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
514
515 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
516 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
517 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
518 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
519 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
520 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
521 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Liz Kammere6583482021-10-19 13:56:10 -0400522 }
523 }
524
525 compilerAttrs.convertStlProps(ctx, module)
526 (&linkerAttrs).convertStripProps(ctx, module)
527
528 productVariableProps := android.ProductVariableProperties(ctx)
529
530 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
531 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
532
533 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500534 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400535
Liz Kammer12615db2021-09-28 09:19:17 -0400536 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
537
538 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
539 // which. This will add the newly generated proto library to the appropriate attribute and nothing
540 // to the other
541 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
542 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
543
Liz Kammere6583482021-10-19 13:56:10 -0400544 return baseAttributes{
545 compilerAttrs,
546 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400547 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000548 }
549}
550
551// Convenience struct to hold all attributes parsed from linker properties.
552type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500553 deps bazel.LabelListAttribute
554 implementationDeps bazel.LabelListAttribute
555 dynamicDeps bazel.LabelListAttribute
556 implementationDynamicDeps bazel.LabelListAttribute
557 wholeArchiveDeps bazel.LabelListAttribute
558 implementationWholeArchiveDeps bazel.LabelListAttribute
559 systemDynamicDeps bazel.LabelListAttribute
560 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400561
Jingwen Chen6ada5892021-09-17 11:38:09 +0000562 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000563 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500564 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000565 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400566 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000567 stripKeepSymbols bazel.BoolAttribute
568 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
569 stripKeepSymbolsList bazel.StringListAttribute
570 stripAll bazel.BoolAttribute
571 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400572 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400573}
574
Liz Kammer54309532021-12-14 12:21:22 -0500575var (
576 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
577)
578
Jingwen Chen55bc8202021-11-02 06:40:51 +0000579func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400580 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
581 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400582
Liz Kammere6583482021-10-19 13:56:10 -0400583 // Excludes to parallel Soong:
584 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
585 staticLibs := android.FirstUniqueStrings(props.Static_libs)
586 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400587
Liz Kammere6583482021-10-19 13:56:10 -0400588 headerLibs := android.FirstUniqueStrings(props.Header_libs)
589 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400590
Liz Kammere6583482021-10-19 13:56:10 -0400591 (&hDeps.export).Append(staticDeps.export)
592 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000593
Liz Kammere6583482021-10-19 13:56:10 -0400594 (&hDeps.implementation).Append(staticDeps.implementation)
595 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400596
Liz Kammere6583482021-10-19 13:56:10 -0400597 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
598 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
599
600 systemSharedLibs := props.System_shared_libs
601 // systemSharedLibs distinguishes between nil/empty list behavior:
602 // nil -> use default values
603 // empty list -> no values specified
604 if len(systemSharedLibs) > 0 {
605 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
606 }
607 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
608
609 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500610 excludeSharedLibs := props.Exclude_shared_libs
611 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
612 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
613 })
614 for _, el := range usedSystem {
615 if la.usedSystemDynamicDepAsDynamicDep == nil {
616 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
617 }
618 la.usedSystemDynamicDepAsDynamicDep[el] = true
619 }
620
Liz Kammere6583482021-10-19 13:56:10 -0400621 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
622 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
623 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
624
625 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
626 axisFeatures = append(axisFeatures, "disable_pack_relocations")
627 }
628
629 if Bool(props.Allow_undefined_symbols) {
630 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
631 }
632
633 var linkerFlags []string
634 if len(props.Ldflags) > 0 {
635 linkerFlags = append(linkerFlags, props.Ldflags...)
636 // binaries remove static flag if -shared is in the linker flags
637 if isBinary && android.InList("-shared", linkerFlags) {
638 axisFeatures = append(axisFeatures, "-static_flag")
639 }
640 }
641 if props.Version_script != nil {
642 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
643 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
644 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
645 }
646 la.linkopts.SetSelectValue(axis, config, linkerFlags)
647 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
648
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500649 if axis == bazel.NoConfigAxis {
650 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
651 }
652
Liz Kammere6583482021-10-19 13:56:10 -0400653 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
654 if props.crt() != nil {
655 if axis == bazel.NoConfigAxis {
656 la.linkCrt.SetSelectValue(axis, config, props.crt())
657 } else if axis == bazel.ArchConfigurationAxis {
658 ctx.ModuleErrorf("nocrt is not supported for arch variants")
659 }
660 }
661
662 if axisFeatures != nil {
663 la.features.SetSelectValue(axis, config, axisFeatures)
664 }
665}
666
Jingwen Chen55bc8202021-11-02 06:40:51 +0000667func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000668 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StripProperties{}) {
669 for config, props := range configToProps {
670 if stripProperties, ok := props.(*StripProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400671 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
672 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
673 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
674 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
675 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000676 }
677 }
678 }
Liz Kammere6583482021-10-19 13:56:10 -0400679}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000680
Jingwen Chen55bc8202021-11-02 06:40:51 +0000681func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000682
Liz Kammer47535c52021-06-02 16:02:22 -0400683 type productVarDep struct {
684 // the name of the corresponding excludes field, if one exists
685 excludesField string
686 // reference to the bazel attribute that should be set for the given product variable config
687 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400688
Jingwen Chen55bc8202021-11-02 06:40:51 +0000689 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400690 }
691
692 productVarToDepFields := map[string]productVarDep{
693 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000694 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
695 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
696 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400697 }
698
Liz Kammer47535c52021-06-02 16:02:22 -0400699 for name, dep := range productVarToDepFields {
700 props, exists := productVariableProps[name]
701 excludeProps, excludesExists := productVariableProps[dep.excludesField]
702 // if neither an include or excludes property exists, then skip it
703 if !exists && !excludesExists {
704 continue
705 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000706 // Collect all the configurations that an include or exclude property exists for.
707 // We want to iterate all configurations rather than either the include or exclude because, for a
708 // particular configuration, we may have either only an include or an exclude to handle.
709 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
710 for p := range props {
711 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400712 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000713 for p := range excludeProps {
714 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400715 }
716
Jingwen Chen25825ca2021-11-15 12:28:43 +0000717 for productConfigProp := range productConfigProps {
718 prop, includesExists := props[productConfigProp]
719 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400720 var includes, excludes []string
721 var ok bool
722 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000723 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400724 ctx.ModuleErrorf("Could not convert product variable %s property", name)
725 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000726 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400727 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
728 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400729
Jingwen Chen58ff6802021-11-17 12:14:41 +0000730 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000731 dep.attribute.SetSelectValue(
732 productConfigProp.ConfigurationAxis(),
733 productConfigProp.SelectKey(),
734 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
735 )
Liz Kammer47535c52021-06-02 16:02:22 -0400736 }
737 }
Liz Kammere6583482021-10-19 13:56:10 -0400738}
Liz Kammer47535c52021-06-02 16:02:22 -0400739
Liz Kammer54309532021-12-14 12:21:22 -0500740func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
741 // if system dynamic deps have the default value, any use of a system dynamic library used will
742 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
743 // from bionic OSes.
744 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
745 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
746 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
747 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
748 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
749 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
750 }
751
Liz Kammere6583482021-10-19 13:56:10 -0400752 la.deps.ResolveExcludes()
753 la.implementationDeps.ResolveExcludes()
754 la.dynamicDeps.ResolveExcludes()
755 la.implementationDynamicDeps.ResolveExcludes()
756 la.wholeArchiveDeps.ResolveExcludes()
757 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -0500758
Jingwen Chen91220d72021-03-24 02:18:33 -0400759}
760
Jingwen Chened9c17d2021-04-13 07:14:55 +0000761// Relativize a list of root-relative paths with respect to the module's
762// directory.
763//
764// include_dirs Soong prop are root-relative (b/183742505), but
765// local_include_dirs, export_include_dirs and export_system_include_dirs are
766// module dir relative. This function makes a list of paths entirely module dir
767// relative.
768//
769// For the `include` attribute, Bazel wants the paths to be relative to the
770// module.
771func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000772 var relativePaths []string
773 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000774 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
775 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
776 if err != nil {
777 panic(err)
778 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000779 relativePaths = append(relativePaths, relativePath)
780 }
781 return relativePaths
782}
783
Liz Kammer5fad5012021-09-09 14:08:21 -0400784// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
785// attributes.
786type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500787 AbsoluteIncludes bazel.StringListAttribute
788 Includes bazel.StringListAttribute
789 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400790}
791
Liz Kammer1263d9b2021-12-10 14:28:20 -0500792func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, existingIncludes BazelIncludes) BazelIncludes {
Jingwen Chen91220d72021-03-24 02:18:33 -0400793 libraryDecorator := module.linker.(*libraryDecorator)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500794 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, &existingIncludes)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400795}
Jingwen Chen91220d72021-03-24 02:18:33 -0400796
Liz Kammer5fad5012021-09-09 14:08:21 -0400797// Bp2buildParseExportedIncludesForPrebuiltLibrary returns a BazelIncludes with Bazel-ified values
798// to export includes from the underlying module's properties.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000799func Bp2BuildParseExportedIncludesForPrebuiltLibrary(ctx android.BazelConversionPathContext, module *Module) BazelIncludes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400800 prebuiltLibraryLinker := module.linker.(*prebuiltLibraryLinker)
801 libraryDecorator := prebuiltLibraryLinker.libraryDecorator
Liz Kammer1263d9b2021-12-10 14:28:20 -0500802 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, nil)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400803}
804
805// bp2BuildParseExportedIncludes creates a string list attribute contains the
806// exported included directories of a module.
Liz Kammer1263d9b2021-12-10 14:28:20 -0500807func bp2BuildParseExportedIncludesHelper(ctx android.BazelConversionPathContext, module *Module, libraryDecorator *libraryDecorator, includes *BazelIncludes) BazelIncludes {
808 var exported BazelIncludes
809 if includes != nil {
810 exported = *includes
811 } else {
812 exported = BazelIncludes{}
813 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400814 for axis, configToProps := range module.GetArchVariantProperties(ctx, &FlagExporterProperties{}) {
815 for config, props := range configToProps {
816 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
Liz Kammer5fad5012021-09-09 14:08:21 -0400817 if len(flagExporterProperties.Export_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500818 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
Liz Kammer5fad5012021-09-09 14:08:21 -0400819 }
820 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500821 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 -0400822 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400823 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400824 }
825 }
Liz Kammer1263d9b2021-12-10 14:28:20 -0500826 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400827 exported.Includes.DeduplicateAxesFromBase()
828 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400829
Liz Kammer5fad5012021-09-09 14:08:21 -0400830 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400831}
Chris Parsons953b3562021-09-20 15:14:39 -0400832
Jingwen Chen55bc8202021-11-02 06:40:51 +0000833func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400834 label := android.BazelModuleLabel(ctx, m)
835 if aModule, ok := m.(android.Module); ok {
836 if ctx.OtherModuleType(aModule) == "cc_library" && !android.GenerateCcLibraryStaticOnly(m.Name()) {
837 label += "_bp2build_cc_library_static"
838 }
839 }
840 return label
841}
842
Jingwen Chen55bc8202021-11-02 06:40:51 +0000843func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400844 // cc_library, at it's root name, propagates the shared library, which depends on the static
845 // library.
846 return android.BazelModuleLabel(ctx, m)
847}
848
Jingwen Chen55bc8202021-11-02 06:40:51 +0000849func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400850 label := bazelLabelForStaticModule(ctx, m)
851 if aModule, ok := m.(android.Module); ok {
852 if android.IsModulePrebuilt(aModule) {
853 label += "_alwayslink"
854 }
855 }
856 return label
857}
858
Jingwen Chen55bc8202021-11-02 06:40:51 +0000859func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400860 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
861}
862
Jingwen Chen55bc8202021-11-02 06:40:51 +0000863func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400864 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
865}
866
Jingwen Chen55bc8202021-11-02 06:40:51 +0000867func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400868 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
869}
870
Jingwen Chen55bc8202021-11-02 06:40:51 +0000871func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400872 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
873}
874
Jingwen Chen55bc8202021-11-02 06:40:51 +0000875func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400876 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
877}
878
Jingwen Chen55bc8202021-11-02 06:40:51 +0000879func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400880 // This is not elegant, but bp2build's shared library targets only propagate
881 // their header information as part of the normal C++ provider.
882 return bazelLabelForSharedDeps(ctx, modules)
883}
884
Jingwen Chen55bc8202021-11-02 06:40:51 +0000885func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400886 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
887}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400888
889type binaryLinkerAttrs struct {
890 Linkshared *bool
891}
892
Jingwen Chen55bc8202021-11-02 06:40:51 +0000893func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400894 attrs := binaryLinkerAttrs{}
895 archVariantProps := m.GetArchVariantProperties(ctx, &BinaryLinkerProperties{})
896 for axis, configToProps := range archVariantProps {
897 for _, p := range configToProps {
898 props := p.(*BinaryLinkerProperties)
899 staticExecutable := props.Static_executable
900 if axis == bazel.NoConfigAxis {
901 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
902 attrs.Linkshared = &linkBinaryShared
903 }
904 } else if staticExecutable != nil {
905 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
906 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
907 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
908 }
909 }
910 }
911
912 return attrs
913}