blob: 2f79caec7259275d01558ef35233323fd510f850 [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//
Cole Faust7071a052022-07-29 15:58:33 -07007// http://www.apache.org/licenses/LICENSE-2.0
Jingwen Chen91220d72021-03-24 02:18:33 -04008//
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"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040020
21 "android/soong/android"
22 "android/soong/bazel"
Alix1be00d42022-05-16 22:56:04 +000023 "android/soong/cc/config"
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 (
Trevor Radcliffecee4e052022-09-06 19:31:25 +000031 cSrcPartition = "c"
32 asSrcPartition = "as"
33 asmSrcPartition = "asm"
34 lSrcPartition = "l"
35 llSrcPartition = "ll"
36 cppSrcPartition = "cpp"
37 protoSrcPartition = "proto"
38 aidlSrcPartition = "aidl"
39 syspropSrcPartition = "sysprop"
Liz Kammer91487d42022-09-13 11:27:11 -040040
41 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040042)
43
Liz Kammer2222c6b2021-05-24 15:41:47 -040044// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000045// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040046type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040047 Srcs bazel.LabelListAttribute
48 Srcs_c bazel.LabelListAttribute
49 Srcs_as bazel.LabelListAttribute
50 Srcs_aidl bazel.LabelListAttribute
51 Hdrs bazel.LabelListAttribute
52 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000053
Liz Kammer12615db2021-09-28 09:19:17 -040054 Deps bazel.LabelListAttribute
55 Implementation_deps bazel.LabelListAttribute
56 Dynamic_deps bazel.LabelListAttribute
57 Implementation_dynamic_deps bazel.LabelListAttribute
58 Whole_archive_deps bazel.LabelListAttribute
59 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070060 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040061
62 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050063
64 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080065
Yu Liu8d82ac52022-05-17 15:13:28 -070066 Native_coverage bazel.BoolAttribute
67
Yu Liufc603162022-03-01 15:44:08 -080068 sdkAttributes
Sam Delmericofb3bb322022-10-21 10:42:24 -040069
70 tidyAttributes
71}
72
73type tidyAttributes struct {
74 Tidy *bool
75 Tidy_flags []string
76 Tidy_checks []string
77 Tidy_checks_as_errors []string
78}
79
80func (m *Module) convertTidyAttributes(moduleAttrs *tidyAttributes) {
81 for _, f := range m.features {
82 if tidy, ok := f.(*tidyFeature); ok {
83 moduleAttrs.Tidy = tidy.Properties.Tidy
84 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
85 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
86 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
87 }
88 }
Jingwen Chen53681ef2021-04-29 08:15:13 +000089}
90
Sam Delmericoc7681022022-02-04 21:01:20 +000091// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000092func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040093 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
94 // macro.
95 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -040096 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
97
98 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -040099 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400100 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
101 return labelStr, false
102 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700103 // If the filegroup is already converted to aidl_library or proto_library,
104 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
105 fg, _ := m.(android.FileGroupAsLibrary)
106 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400107 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000108 }
Liz Kammer12615db2021-09-28 09:19:17 -0400109 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400110 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000111 }
112
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400113 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000114 labels := bazel.LabelPartitions{
115 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500116 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
117 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700118 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400119 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000120 // TODO(http://b/231968910): If there is ever a filegroup target that
121 // contains .l or .ll files we will need to find a way to add a
122 // LabelMapper for these that identifies these filegroups and
123 // converts them appropriately
124 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
125 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400126 // C++ is the "catch-all" group, and comprises generated sources because we don't
127 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000128 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
129 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000130 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000131
Sam Delmericoc7681022022-02-04 21:01:20 +0000132 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000133}
134
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000135// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000136func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000137 lib, ok := module.compiler.(*libraryDecorator)
138 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400139 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000140 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000141 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
142}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000143
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000144// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000145func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000146 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000147}
148
149// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000150func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000151 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400152}
153
Liz Kammer7a210ac2021-09-22 15:52:58 -0400154type depsPartition struct {
155 export bazel.LabelList
156 implementation bazel.LabelList
157}
158
Jingwen Chen55bc8202021-11-02 06:40:51 +0000159type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400160
Jingwen Chen55bc8202021-11-02 06:40:51 +0000161func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400162 if !exportsDeps {
163 return depsPartition{
164 implementation: fn(ctx, allDeps),
165 }
166 }
167
Liz Kammer7a210ac2021-09-22 15:52:58 -0400168 implementation, export := android.FilterList(allDeps, exportedDeps)
169
170 return depsPartition{
171 export: fn(ctx, export),
172 implementation: fn(ctx, implementation),
173 }
174}
175
Jingwen Chen55bc8202021-11-02 06:40:51 +0000176type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400177
Jingwen Chen55bc8202021-11-02 06:40:51 +0000178func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400179 if !exportsDeps {
180 return depsPartition{
181 implementation: fn(ctx, allDeps, excludes),
182 }
183 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400184 implementation, export := android.FilterList(allDeps, exportedDeps)
185
186 return depsPartition{
187 export: fn(ctx, export, excludes),
188 implementation: fn(ctx, implementation, excludes),
189 }
190}
191
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000192func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
193 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
194 for config, props := range configToProps {
195 parseFunc(axis, config, props)
196 }
197 }
198}
199
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000200// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000201func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400202 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000203
Liz Kammer9abd62d2021-05-21 08:37:59 -0400204 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000205 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000206 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400207 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400208
Liz Kammer2b8004b2021-10-04 13:55:44 -0400209 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400210 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
211 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
212
Liz Kammer2b8004b2021-10-04 13:55:44 -0400213 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400214 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
215 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
216
217 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500218 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000219 }
Liz Kammer135bf552021-08-11 10:46:06 -0400220 // system_dynamic_deps distinguishes between nil/empty list behavior:
221 // nil -> use default values
222 // empty list -> no values specified
223 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000224
225 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000226 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
227 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
228 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000229 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000230 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000231 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000232 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
233 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
234 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000235 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000236 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000237 }
238
Liz Kammerae3994e2021-10-19 09:45:48 -0400239 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
240 attrs.Srcs = partitionedSrcs[cppSrcPartition]
241 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
242 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000243
Liz Kammer12615db2021-09-28 09:19:17 -0400244 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
245 // TODO(b/208815215): determine whether this is used and add support if necessary
246 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
247 }
248
Jingwen Chenbcf53042021-05-26 04:42:42 +0000249 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000250}
251
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400252// Convenience struct to hold all attributes parsed from prebuilt properties.
253type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000254 Src bazel.LabelAttribute
255 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400256}
257
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000258func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
259 srcFileError := func() {
260 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
261 }
262 if len(srcs) > 1 {
263 srcFileError()
264 return
265 } else if len(srcs) == 0 {
266 return
267 }
268 if srcLabelAttribute.SelectValue(axis, config) != nil {
269 srcFileError()
270 return
271 }
272 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
273}
274
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000275// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000276func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000277
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400278 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000279 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
280 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000281 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000282 }
283 })
284
285 var enabledLabelAttribute bazel.BoolAttribute
286 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
287 if props.Enabled != nil {
288 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
289 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000290 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000291 }
292
293 if isStatic {
294 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
295 if staticProperties, ok := props.(*StaticProperties); ok {
296 parseAttrs(axis, config, staticProperties.Static)
297 }
298 })
299 } else {
300 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
301 if sharedProperties, ok := props.(*SharedProperties); ok {
302 parseAttrs(axis, config, sharedProperties.Shared)
303 }
304 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400305 }
306
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400307 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000308 Src: srcLabelAttribute,
309 Enabled: enabledLabelAttribute,
310 }
311}
312
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000313func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
314 var srcLabelAttribute bazel.LabelAttribute
315 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
316 if props, ok := props.(*prebuiltLinkerProperties); ok {
317 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000318 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000319 })
320
321 return prebuiltAttributes{
322 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400323 }
324}
325
Liz Kammere6583482021-10-19 13:56:10 -0400326type baseAttributes struct {
327 compilerAttributes
328 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400329
Cole Faust5fa4e962022-08-22 14:31:04 -0700330 // A combination of compilerAttributes.features and linkerAttributes.features
331 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400332 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400333 aidlDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400334}
335
Jingwen Chen107c0de2021-04-09 10:43:12 +0000336// Convenience struct to hold all attributes parsed from compiler properties.
337type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400338 // Options for all languages
339 copts bazel.StringListAttribute
340 // Assembly options and sources
341 asFlags bazel.StringListAttribute
342 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700343 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400344 // C options and sources
345 conlyFlags bazel.StringListAttribute
346 cSrcs bazel.LabelListAttribute
347 // C++ options and sources
348 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000349 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400350
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000351 // Lex sources and options
352 lSrcs bazel.LabelListAttribute
353 llSrcs bazel.LabelListAttribute
354 lexopts bazel.StringListAttribute
355
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000356 // Sysprop sources
357 syspropSrcs bazel.LabelListAttribute
358
Liz Kammere6583482021-10-19 13:56:10 -0400359 hdrs bazel.LabelListAttribute
360
Chris Parsons2c788392021-08-10 11:58:07 -0400361 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000362
363 // Not affected by arch variants
364 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500365 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000366 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400367
368 localIncludes bazel.StringListAttribute
369 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400370
Liz Kammer1263d9b2021-12-10 14:28:20 -0500371 includes BazelIncludes
372
Liz Kammer12615db2021-09-28 09:19:17 -0400373 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400374 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000375
376 stubsSymbolFile *string
377 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700378
379 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500380
381 suffix bazel.StringAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000382}
383
Liz Kammercac7f692021-12-16 14:19:32 -0500384type filterOutFn func(string) bool
385
386func filterOutStdFlag(flag string) bool {
387 return strings.HasPrefix(flag, "-std=")
388}
389
Alix1be00d42022-05-16 22:56:04 +0000390func filterOutClangUnknownCflags(flag string) bool {
391 for _, f := range config.ClangUnknownCflags {
392 if f == flag {
393 return true
394 }
395 }
396 return false
397}
398
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000399func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400400 var result []string
401 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000402 skipFlag := false
403 for _, filter := range filterOut {
404 if filter != nil && filter(flag) {
405 skipFlag = true
406 }
407 }
408 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500409 continue
410 }
Liz Kammere6583482021-10-19 13:56:10 -0400411 // Soong's cflags can contain spaces, like `-include header.h`. For
412 // Bazel's copts, split them up to be compatible with the
413 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000414 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400415 }
416 return result
417}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000418
Jingwen Chen55bc8202021-11-02 06:40:51 +0000419func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400420 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
421 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
422 if srcsList, ok := parseSrcs(ctx, props); ok {
423 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400424 }
425
Liz Kammere6583482021-10-19 13:56:10 -0400426 localIncludeDirs := props.Local_include_dirs
427 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500428 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400429 if includeBuildDirectory(props.Include_build_directory) {
430 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400431 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000432 }
433
Liz Kammere6583482021-10-19 13:56:10 -0400434 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
435 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
436
Cole Faust5fa4e962022-08-22 14:31:04 -0700437 instructionSet := proptools.StringDefault(props.Instruction_set, "")
438 if instructionSet == "arm" {
439 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
440 } else if instructionSet != "" && instructionSet != "thumb" {
441 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
442 }
443
Liz Kammercac7f692021-12-16 14:19:32 -0500444 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
445 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
446 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
447 // cases.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000448 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags))
449 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
450 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
451 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400452 ca.rtti.SetSelectValue(axis, config, props.Rtti)
453}
454
Jingwen Chen55bc8202021-11-02 06:40:51 +0000455func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000456 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
457 if stlProps, ok := props.(*StlProperties); ok {
458 if stlProps.Stl == nil {
459 return
460 }
461 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400462 stl := deduplicateStlInput(*stlProps.Stl)
463 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000464 } else if ca.stl != stlProps.Stl {
465 ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
Liz Kammer9abd62d2021-05-21 08:37:59 -0400466 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000467 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000468 })
Liz Kammere6583482021-10-19 13:56:10 -0400469}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000470
Jingwen Chen55bc8202021-11-02 06:40:51 +0000471func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400472 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400473 "Cflags": &ca.copts,
474 "Asflags": &ca.asFlags,
475 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400476 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400477 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000478 if productConfigProps, exists := productVariableProps[propName]; exists {
479 for productConfigProp, prop := range productConfigProps {
480 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400481 if !ok {
482 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
483 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000484 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
485 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400486 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400487 }
488 }
Liz Kammere6583482021-10-19 13:56:10 -0400489}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400490
Jingwen Chen55bc8202021-11-02 06:40:51 +0000491func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400492 ca.srcs.ResolveExcludes()
493 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
494
Liz Kammer12615db2021-09-28 09:19:17 -0400495 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400496 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400497
Liz Kammere6583482021-10-19 13:56:10 -0400498 for p, lla := range partitionedSrcs {
499 // if there are no sources, there is no need for headers
500 if lla.IsEmpty() {
501 continue
502 }
503 lla.Append(implementationHdrs)
504 partitionedSrcs[p] = lla
505 }
506
507 ca.srcs = partitionedSrcs[cppSrcPartition]
508 ca.cSrcs = partitionedSrcs[cSrcPartition]
509 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700510 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000511 ca.lSrcs = partitionedSrcs[lSrcPartition]
512 ca.llSrcs = partitionedSrcs[llSrcPartition]
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000513 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400514
515 ca.absoluteIncludes.DeduplicateAxesFromBase()
516 ca.localIncludes.DeduplicateAxesFromBase()
517}
518
519// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000520func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400521 anySrcs := false
522 // Add srcs-like dependencies such as generated files.
523 // First create a LabelList containing these dependencies, then merge the values with srcs.
524 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
525 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
526 anySrcs = true
527 }
528
529 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400530
Liz Kammere6583482021-10-19 13:56:10 -0400531 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
532 anySrcs = true
533 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400534
Liz Kammere6583482021-10-19 13:56:10 -0400535 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
536}
537
Liz Kammera5a29de2022-05-25 23:19:37 -0400538func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
539 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500540 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
541 // Defaults are handled by the toolchain definition.
542 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400543 stdVal := proptools.StringDefault(std, defaultVal)
544 if stdVal == "experimental" || stdVal == defaultVal {
545 if stdVal == "experimental" {
546 stdVal = prefix + "_std_experimental"
547 }
548 if !useGnu {
549 stdVal += "_no_gnu"
550 }
551 } else if !useGnu {
552 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500553 }
554
Liz Kammera5a29de2022-05-25 23:19:37 -0400555 if stdVal == defaultVal {
556 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500557 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400558 return &stdVal
559}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500560
Liz Kammera5a29de2022-05-25 23:19:37 -0400561func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
562 useGnu := useGnuExtensions(gnu_extensions)
563
564 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400565}
566
Liz Kammer1263d9b2021-12-10 14:28:20 -0500567// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
568// is fully-qualified.
569// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
570func packageFromLabel(label string) (string, bool) {
571 split := strings.Split(label, ":")
572 if len(split) != 2 {
573 return "", false
574 }
575 if split[0] == "" {
576 return ".", false
577 }
578 // remove leading "//"
579 return split[0][2:], true
580}
581
582// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
583func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
584 for _, hdr := range labelList.Includes {
585 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
586 absolute = append(absolute, pkg)
587 } else if pkg != "" {
588 relative = append(relative, pkg)
589 }
590 }
591 return relative, absolute
592}
593
Cole Faust7071a052022-07-29 15:58:33 -0700594type YasmAttributes struct {
595 Srcs bazel.LabelListAttribute
596 Flags bazel.StringListAttribute
597 Include_dirs bazel.StringListAttribute
598}
599
600func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
601 if ca.asmSrcs.IsEmpty() {
602 return nil
603 }
604
605 // Yasm needs the include directories from both local_includes and
606 // export_include_dirs. We don't care about actually exporting them from the
607 // yasm rule though, because they will also be present on the cc_ rule that
608 // wraps this yasm rule.
609 includes := ca.localIncludes.Clone()
610 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
611 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
612 if len(flagExporterProperties.Export_include_dirs) > 0 {
613 x := bazel.StringListAttribute{}
614 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
615 includes.Append(x)
616 }
617 }
618 })
619
620 ctx.CreateBazelTargetModule(
621 bazel.BazelTargetModuleProperties{
622 Rule_class: "yasm",
623 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
624 },
625 android.CommonAttributes{Name: m.Name() + "_yasm"},
626 &YasmAttributes{
627 Srcs: ca.asmSrcs,
628 Flags: ca.asFlags,
629 Include_dirs: *includes,
630 })
631
632 // We only want to add a dependency on the _yasm target if there are asm
633 // sources in the current configuration. If there are unconfigured asm
634 // sources, always add the dependency. Otherwise, add the dependency only
635 // on the configuration axes and values that had asm sources.
636 if len(ca.asmSrcs.Value.Includes) > 0 {
637 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
638 }
639
640 ret := &bazel.LabelAttribute{}
641 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
642 for config := range ca.asmSrcs.ConfigurableValues[axis] {
643 ret.SetSelectValue(axis, config, bazel.Label{Label: ":" + m.Name() + "_yasm"})
644 }
645 }
646 return ret
647}
648
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000649// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400650func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400651 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
652 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000653 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400654
655 var implementationHdrs bazel.LabelListAttribute
656
657 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
658 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
659 for axis, configMap := range cp {
660 if _, ok := axisToConfigs[axis]; !ok {
661 axisToConfigs[axis] = map[string]bool{}
662 }
663 for config, _ := range configMap {
664 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400665 }
666 }
667 }
Liz Kammere6583482021-10-19 13:56:10 -0400668 allAxesAndConfigs(archVariantCompilerProps)
669 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000670 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400671
Liz Kammere6583482021-10-19 13:56:10 -0400672 compilerAttrs := compilerAttributes{}
673 linkerAttrs := linkerAttributes{}
674
675 for axis, configs := range axisToConfigs {
676 for config, _ := range configs {
677 var allHdrs []string
678 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
679 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000680 if baseCompilerProps.Lex != nil {
681 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
682 }
Liz Kammere6583482021-10-19 13:56:10 -0400683 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
684 }
685
686 var exportHdrs []string
687
688 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
689 exportHdrs = baseLinkerProps.Export_generated_headers
690
691 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
692 }
693 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
694 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
695 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500696
697 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
698 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
699 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
700
701 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
702 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
703 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400704
Liz Kammer1263d9b2021-12-10 14:28:20 -0500705 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400706
Liz Kammer1263d9b2021-12-10 14:28:20 -0500707 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
708 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400709
Liz Kammer1263d9b2021-12-10 14:28:20 -0500710 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000711
712 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
713 if axis == bazel.NoConfigAxis {
714 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
715 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
716 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500717 if suffix := libraryProps.Suffix; suffix != nil {
718 compilerAttrs.suffix.SetSelectValue(axis, config, suffix)
719 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000720 }
Liz Kammere6583482021-10-19 13:56:10 -0400721 }
722 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400723
Liz Kammere6583482021-10-19 13:56:10 -0400724 compilerAttrs.convertStlProps(ctx, module)
725 (&linkerAttrs).convertStripProps(ctx, module)
726
Yu Liu8d82ac52022-05-17 15:13:28 -0700727 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
728 !Bool(module.coverage.Properties.Native_coverage) {
729 // Native_coverage is arch neutral
730 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
731 }
732
Liz Kammere6583482021-10-19 13:56:10 -0400733 productVariableProps := android.ProductVariableProperties(ctx)
734
735 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
736 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
737
738 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500739 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400740
Cole Faust7071a052022-07-29 15:58:33 -0700741 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
742
Liz Kammer12615db2021-09-28 09:19:17 -0400743 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
744
745 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
746 // which. This will add the newly generated proto library to the appropriate attribute and nothing
747 // to the other
748 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
749 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400750
Vinh Tran395a1e92022-09-16 18:27:29 -0400751 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs, linkerAttrs)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400752 if aidlDep != nil {
753 if lib, ok := module.linker.(*libraryDecorator); ok {
754 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
755 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
756 } else {
757 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
758 }
759 }
760 }
Liz Kammer12615db2021-09-28 09:19:17 -0400761
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000762 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
763 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
764 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
765
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000766 if !compilerAttrs.syspropSrcs.IsEmpty() {
767 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
768 }
769
Cole Faust5fa4e962022-08-22 14:31:04 -0700770 features := compilerAttrs.features.Clone().Append(linkerAttrs.features)
771 features.DeduplicateAxesFromBase()
772
Liz Kammere6583482021-10-19 13:56:10 -0400773 return baseAttributes{
774 compilerAttrs,
775 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700776 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400777 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400778 aidlDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000779 }
780}
781
Vinh Tran9f6796a2022-08-16 13:10:31 -0400782func bp2buildCcAidlLibrary(
783 ctx android.Bp2buildMutatorContext,
784 m *Module,
Vinh Trana3b8b782022-09-14 11:40:24 -0400785 aidlLabelList bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -0400786 linkerAttrs linkerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400787) *bazel.LabelAttribute {
Vinh Trana3b8b782022-09-14 11:40:24 -0400788 if !aidlLabelList.IsEmpty() {
789 aidlLibs, aidlSrcs := aidlLabelList.Partition(func(src bazel.Label) bool {
790 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
791 fg.ShouldConvertToAidlLibrary(ctx) {
792 return true
793 }
794 return false
795 })
Vinh Tran9f6796a2022-08-16 13:10:31 -0400796
Vinh Trana3b8b782022-09-14 11:40:24 -0400797 if !aidlSrcs.IsEmpty() {
798 aidlLibName := m.Name() + "_aidl_library"
799 ctx.CreateBazelTargetModule(
800 bazel.BazelTargetModuleProperties{
801 Rule_class: "aidl_library",
802 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
803 },
804 android.CommonAttributes{Name: aidlLibName},
805 &aidlLibraryAttributes{
806 Srcs: aidlSrcs,
807 },
808 )
809 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
810 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400811
Vinh Trana3b8b782022-09-14 11:40:24 -0400812 if !aidlLibs.IsEmpty() {
813 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
Vinh Tran395a1e92022-09-16 18:27:29 -0400814 // Since cc_aidl_library only needs the dynamic deps (aka shared libs) from the parent cc library for compiling,
815 // we err on the side of not re-exporting the headers of the dynamic deps from cc_aidl_lirary
816 // because the parent cc library already has all the dynamic deps
817 implementationDynamicDeps := bazel.MakeLabelListAttribute(
818 bazel.AppendBazelLabelLists(
819 linkerAttrs.dynamicDeps.Value,
820 linkerAttrs.implementationDynamicDeps.Value,
821 ),
822 )
823
Vinh Trana3b8b782022-09-14 11:40:24 -0400824 ctx.CreateBazelTargetModule(
825 bazel.BazelTargetModuleProperties{
826 Rule_class: "cc_aidl_library",
827 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
828 },
829 android.CommonAttributes{Name: ccAidlLibrarylabel},
830 &ccAidlLibraryAttributes{
Vinh Tran395a1e92022-09-16 18:27:29 -0400831 Deps: aidlLibs,
832 Implementation_dynamic_deps: implementationDynamicDeps,
Vinh Trana3b8b782022-09-14 11:40:24 -0400833 },
834 )
835 label := &bazel.LabelAttribute{
836 Value: &bazel.Label{
837 Label: ":" + ccAidlLibrarylabel,
838 },
839 }
840 return label
841 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400842 }
843
Vinh Trana3b8b782022-09-14 11:40:24 -0400844 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -0400845}
846
Yu Liufc603162022-03-01 15:44:08 -0800847func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000848 return sdkAttributes{
849 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800850 Min_sdk_version: module.Properties.Min_sdk_version,
851 }
852}
853
854type sdkAttributes struct {
855 Sdk_version *string
856 Min_sdk_version *string
857}
858
Jingwen Chen107c0de2021-04-09 10:43:12 +0000859// Convenience struct to hold all attributes parsed from linker properties.
860type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500861 deps bazel.LabelListAttribute
862 implementationDeps bazel.LabelListAttribute
863 dynamicDeps bazel.LabelListAttribute
864 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700865 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500866 wholeArchiveDeps bazel.LabelListAttribute
867 implementationWholeArchiveDeps bazel.LabelListAttribute
868 systemDynamicDeps bazel.LabelListAttribute
869 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400870
Jingwen Chen6ada5892021-09-17 11:38:09 +0000871 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000872 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500873 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000874 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400875 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000876 stripKeepSymbols bazel.BoolAttribute
877 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
878 stripKeepSymbolsList bazel.StringListAttribute
879 stripAll bazel.BoolAttribute
880 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400881 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400882}
883
Liz Kammer54309532021-12-14 12:21:22 -0500884var (
885 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -0400886 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -0500887)
888
Vinh Tran85fb07c2022-09-16 16:17:48 -0400889// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
890// since all libs are already excluded by default
891func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, isBinary bool, props *BaseLinkerProperties) {
892 sharedLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
893 ctx,
894 true,
895 props.Target.Apex.Exclude_shared_libs,
896 props.Export_shared_lib_headers,
897 bazelLabelForSharedDeps,
898 )
899 dynamicDeps := la.dynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
900 implDynamicDeps := la.implementationDynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
901 (&dynamicDeps).Append(sharedLibsForNonApex.export)
902 (&implDynamicDeps).Append(sharedLibsForNonApex.implementation)
903 la.dynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, dynamicDeps)
904 la.implementationDynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDynamicDeps)
905
906 staticLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
907 ctx,
908 !isBinary,
909 props.Target.Apex.Exclude_static_libs,
910 props.Export_static_lib_headers,
911 bazelLabelForSharedDeps,
912 )
913 deps := la.deps.SelectValue(bazel.InApexAxis, bazel.NonApex)
914 implDeps := la.implementationDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
915 (&deps).Append(staticLibsForNonApex.export)
916 (&implDeps).Append(staticLibsForNonApex.implementation)
917 la.deps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, deps)
918 la.implementationDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDeps)
919}
920
Jingwen Chen55bc8202021-11-02 06:40:51 +0000921func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400922 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
923 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400924
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400925 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -0400926 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
927 if axis == bazel.NoConfigAxis {
928 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
929 if proptools.Bool(props.Use_version_lib) {
930 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
931 // remove from static libs so there is no duplicate dependency
932 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
933 // only add the dep if it is not in progress
934 if !versionLibAlreadyInDeps {
935 if isBinary {
936 wholeStaticLibs = append(wholeStaticLibs, versionLib)
937 } else {
938 la.implementationWholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, []string{versionLib}, props.Exclude_static_libs))
939 }
940 }
941 }
942 }
943
Liz Kammere6583482021-10-19 13:56:10 -0400944 // Excludes to parallel Soong:
945 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
Liz Kammerbaced712022-09-16 09:01:29 -0400946 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400947
Vinh Tran85fb07c2022-09-16 16:17:48 -0400948 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
949 ctx,
950 !isBinary,
951 staticLibs,
952 // Exclude static libs in Exclude_static_libs and Target.Apex.Exclude_static_libs props
953 append(props.Exclude_static_libs, props.Target.Apex.Exclude_static_libs...),
954 props.Export_static_lib_headers,
955 bazelLabelForStaticDepsExcludes,
956 )
Liz Kammer7a210ac2021-09-22 15:52:58 -0400957
Liz Kammere6583482021-10-19 13:56:10 -0400958 headerLibs := android.FirstUniqueStrings(props.Header_libs)
959 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400960
Liz Kammere6583482021-10-19 13:56:10 -0400961 (&hDeps.export).Append(staticDeps.export)
962 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000963
Liz Kammere6583482021-10-19 13:56:10 -0400964 (&hDeps.implementation).Append(staticDeps.implementation)
965 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400966
Liz Kammere6583482021-10-19 13:56:10 -0400967 systemSharedLibs := props.System_shared_libs
968 // systemSharedLibs distinguishes between nil/empty list behavior:
969 // nil -> use default values
970 // empty list -> no values specified
971 if len(systemSharedLibs) > 0 {
972 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
973 }
974 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
975
976 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500977 excludeSharedLibs := props.Exclude_shared_libs
978 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
979 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
980 })
981 for _, el := range usedSystem {
982 if la.usedSystemDynamicDepAsDynamicDep == nil {
983 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
984 }
985 la.usedSystemDynamicDepAsDynamicDep[el] = true
986 }
987
Vinh Tran85fb07c2022-09-16 16:17:48 -0400988 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
989 ctx,
990 !isBinary,
991 sharedLibs,
992 // Exclude shared libs in Exclude_shared_libs and Target.Apex.Exclude_shared_libs props
993 append(props.Exclude_shared_libs, props.Target.Apex.Exclude_shared_libs...),
994 props.Export_shared_lib_headers,
995 bazelLabelForSharedDepsExcludes,
996 )
Liz Kammere6583482021-10-19 13:56:10 -0400997 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
998 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Vinh Tran85fb07c2022-09-16 16:17:48 -0400999 la.resolveTargetApexProp(ctx, isBinary, props)
1000
Wei Li81852ca2022-07-27 00:22:06 -07001001 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
1002 // If a dependency in la.implementationDynamicDeps has stubs, its stub variant should be
1003 // used when the dependency is linked in a APEX. The dependencies in NoConfigAxis and
1004 // OsConfigurationAxis/OsAndroid are grouped by having stubs or not, so Bazel select()
1005 // statement can be used to choose source/stub variants of them.
1006 depsWithStubs := []bazel.Label{}
1007 for _, l := range sharedDeps.implementation.Includes {
1008 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
1009 if m, ok := dep.(*Module); ok && m.HasStubsVariants() {
1010 depsWithStubs = append(depsWithStubs, l)
1011 }
1012 }
1013 if len(depsWithStubs) > 0 {
1014 implDynamicDeps := bazel.SubtractBazelLabelList(sharedDeps.implementation, bazel.MakeLabelList(depsWithStubs))
1015 la.implementationDynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
1016
1017 stubLibLabels := []bazel.Label{}
1018 for _, l := range depsWithStubs {
Liz Kammer91487d42022-09-13 11:27:11 -04001019 l.Label = l.Label + stubsSuffix
Wei Li81852ca2022-07-27 00:22:06 -07001020 stubLibLabels = append(stubLibLabels, l)
1021 }
1022 inApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
1023 nonApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
1024 defaultSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1025 if axis == bazel.NoConfigAxis {
1026 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1027 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
1028 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +00001029 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1030 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
1031 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001032 } else if config == bazel.OsAndroid {
1033 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1034 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +00001035 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1036 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001037 }
1038 }
1039 }
Liz Kammere6583482021-10-19 13:56:10 -04001040
1041 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1042 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1043 }
1044
1045 if Bool(props.Allow_undefined_symbols) {
1046 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1047 }
1048
1049 var linkerFlags []string
1050 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001051 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001052 // binaries remove static flag if -shared is in the linker flags
1053 if isBinary && android.InList("-shared", linkerFlags) {
1054 axisFeatures = append(axisFeatures, "-static_flag")
1055 }
1056 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001057
1058 // This must happen before the addition of flags for Version Script and
1059 // Dynamic List, as these flags must be split on spaces and those must not
1060 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1061
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001062 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001063 if props.Version_script != nil {
1064 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001065 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001066 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
1067 }
Alix773adaa2022-04-27 17:49:34 +00001068
1069 if props.Dynamic_list != nil {
1070 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001071 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001072 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1073 }
1074
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001075 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001076 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001077 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
1078
1079 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
1080 if props.crt() != nil {
1081 if axis == bazel.NoConfigAxis {
1082 la.linkCrt.SetSelectValue(axis, config, props.crt())
1083 } else if axis == bazel.ArchConfigurationAxis {
1084 ctx.ModuleErrorf("nocrt is not supported for arch variants")
1085 }
1086 }
1087
1088 if axisFeatures != nil {
1089 la.features.SetSelectValue(axis, config, axisFeatures)
1090 }
Cole Faust6b29f592022-08-09 09:50:56 -07001091
1092 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1093 if !runtimeDeps.IsEmpty() {
1094 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1095 }
Liz Kammere6583482021-10-19 13:56:10 -04001096}
1097
Jingwen Chen55bc8202021-11-02 06:40:51 +00001098func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001099 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1100 if stripProperties, ok := props.(*StripProperties); ok {
1101 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1102 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1103 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1104 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1105 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001106 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001107 })
Liz Kammere6583482021-10-19 13:56:10 -04001108}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001109
Jingwen Chen55bc8202021-11-02 06:40:51 +00001110func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001111
Liz Kammer47535c52021-06-02 16:02:22 -04001112 type productVarDep struct {
1113 // the name of the corresponding excludes field, if one exists
1114 excludesField string
1115 // reference to the bazel attribute that should be set for the given product variable config
1116 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001117
Jingwen Chen55bc8202021-11-02 06:40:51 +00001118 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001119 }
1120
Zi Wang0a8a1292022-08-30 06:27:01 +00001121 // an intermediate attribute that holds Header_libs info, and will be appended to
1122 // implementationDeps at the end, to solve the confliction that both header_libs
1123 // and static_libs use implementationDeps.
1124 var headerDeps bazel.LabelListAttribute
1125
Liz Kammer47535c52021-06-02 16:02:22 -04001126 productVarToDepFields := map[string]productVarDep{
1127 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001128 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1129 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1130 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001131 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001132 }
1133
Liz Kammer47535c52021-06-02 16:02:22 -04001134 for name, dep := range productVarToDepFields {
1135 props, exists := productVariableProps[name]
1136 excludeProps, excludesExists := productVariableProps[dep.excludesField]
1137 // if neither an include or excludes property exists, then skip it
1138 if !exists && !excludesExists {
1139 continue
1140 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001141 // Collect all the configurations that an include or exclude property exists for.
1142 // We want to iterate all configurations rather than either the include or exclude because, for a
1143 // particular configuration, we may have either only an include or an exclude to handle.
1144 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1145 for p := range props {
1146 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001147 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001148 for p := range excludeProps {
1149 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001150 }
1151
Jingwen Chen25825ca2021-11-15 12:28:43 +00001152 for productConfigProp := range productConfigProps {
1153 prop, includesExists := props[productConfigProp]
1154 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001155 var includes, excludes []string
1156 var ok bool
1157 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001158 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001159 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1160 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001161 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001162 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1163 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001164
Jingwen Chen58ff6802021-11-17 12:14:41 +00001165 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001166 dep.attribute.SetSelectValue(
1167 productConfigProp.ConfigurationAxis(),
1168 productConfigProp.SelectKey(),
1169 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1170 )
Liz Kammer47535c52021-06-02 16:02:22 -04001171 }
1172 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001173 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001174}
Liz Kammer47535c52021-06-02 16:02:22 -04001175
Liz Kammer54309532021-12-14 12:21:22 -05001176func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1177 // if system dynamic deps have the default value, any use of a system dynamic library used will
1178 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001179 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001180 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
1181 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001182 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001183 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1184 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001185 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001186 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1187 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001188
1189 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1190 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1191 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1192 for _, lib := range toRemove.Includes {
1193 lib.Label += stubsSuffix
1194 stubsToRemove = append(stubsToRemove, lib)
1195 }
1196 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001197 }
1198
Liz Kammere6583482021-10-19 13:56:10 -04001199 la.deps.ResolveExcludes()
1200 la.implementationDeps.ResolveExcludes()
1201 la.dynamicDeps.ResolveExcludes()
1202 la.implementationDynamicDeps.ResolveExcludes()
1203 la.wholeArchiveDeps.ResolveExcludes()
1204 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001205
Jingwen Chen91220d72021-03-24 02:18:33 -04001206}
1207
Jingwen Chened9c17d2021-04-13 07:14:55 +00001208// Relativize a list of root-relative paths with respect to the module's
1209// directory.
1210//
1211// include_dirs Soong prop are root-relative (b/183742505), but
1212// local_include_dirs, export_include_dirs and export_system_include_dirs are
1213// module dir relative. This function makes a list of paths entirely module dir
1214// relative.
1215//
1216// For the `include` attribute, Bazel wants the paths to be relative to the
1217// module.
1218func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001219 var relativePaths []string
1220 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001221 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1222 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1223 if err != nil {
1224 panic(err)
1225 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001226 relativePaths = append(relativePaths, relativePath)
1227 }
1228 return relativePaths
1229}
1230
Liz Kammer5fad5012021-09-09 14:08:21 -04001231// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1232// attributes.
1233type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001234 AbsoluteIncludes bazel.StringListAttribute
1235 Includes bazel.StringListAttribute
1236 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001237}
1238
Liz Kammer54549442022-05-11 13:55:06 -04001239func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001240 var exported BazelIncludes
1241 if includes != nil {
1242 exported = *includes
1243 } else {
1244 exported = BazelIncludes{}
1245 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001246 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1247 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1248 if len(flagExporterProperties.Export_include_dirs) > 0 {
1249 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1250 }
1251 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1252 exported.SystemIncludes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.SystemIncludes.SelectValue(axis, config), flagExporterProperties.Export_system_include_dirs...)))
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001253 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001254 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001255 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001256 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001257 exported.Includes.DeduplicateAxesFromBase()
1258 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001259
Liz Kammer5fad5012021-09-09 14:08:21 -04001260 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001261}
Chris Parsons953b3562021-09-20 15:14:39 -04001262
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001263func BazelLabelNameForStaticModule(baseLabel string) string {
1264 return baseLabel + "_bp2build_cc_library_static"
1265}
1266
Jingwen Chen55bc8202021-11-02 06:40:51 +00001267func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001268 label := android.BazelModuleLabel(ctx, m)
Chris Parsonsad876012022-08-20 14:48:32 -04001269 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GetBp2BuildAllowList().GenerateCcLibraryStaticOnly(m.Name()) {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001270 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001271 }
1272 return label
1273}
1274
Jingwen Chen55bc8202021-11-02 06:40:51 +00001275func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001276 // cc_library, at it's root name, propagates the shared library, which depends on the static
1277 // library.
1278 return android.BazelModuleLabel(ctx, m)
1279}
1280
Jingwen Chen55bc8202021-11-02 06:40:51 +00001281func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001282 label := bazelLabelForStaticModule(ctx, m)
1283 if aModule, ok := m.(android.Module); ok {
1284 if android.IsModulePrebuilt(aModule) {
1285 label += "_alwayslink"
1286 }
1287 }
1288 return label
1289}
1290
Jingwen Chen55bc8202021-11-02 06:40:51 +00001291func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001292 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1293}
1294
Jingwen Chen55bc8202021-11-02 06:40:51 +00001295func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001296 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1297}
1298
Jingwen Chen55bc8202021-11-02 06:40:51 +00001299func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001300 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1301}
1302
Jingwen Chen55bc8202021-11-02 06:40:51 +00001303func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001304 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1305}
1306
Jingwen Chen55bc8202021-11-02 06:40:51 +00001307func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001308 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1309}
1310
Jingwen Chen55bc8202021-11-02 06:40:51 +00001311func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001312 // This is not elegant, but bp2build's shared library targets only propagate
1313 // their header information as part of the normal C++ provider.
1314 return bazelLabelForSharedDeps(ctx, modules)
1315}
1316
Zi Wang0a8a1292022-08-30 06:27:01 +00001317func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1318 // This is only used when product_variable header_libs is processed, to follow
1319 // the pattern of depResolutionFunc
1320 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1321}
1322
Jingwen Chen55bc8202021-11-02 06:40:51 +00001323func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001324 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1325}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001326
1327type binaryLinkerAttrs struct {
1328 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001329 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001330}
1331
Jingwen Chen55bc8202021-11-02 06:40:51 +00001332func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001333 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001334 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1335 linkerProps := props.(*BinaryLinkerProperties)
1336 staticExecutable := linkerProps.Static_executable
1337 if axis == bazel.NoConfigAxis {
1338 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1339 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001340 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001341 } else if staticExecutable != nil {
1342 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1343 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1344 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001345 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001346 if suffix := linkerProps.Suffix; suffix != nil {
1347 attrs.Suffix.SetSelectValue(axis, config, suffix)
1348 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001349 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001350
1351 return attrs
1352}