blob: 6cd67330fe86a346903090c6ac40e8d388a92206 [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"
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 (
Liz Kammer12615db2021-09-28 09:19:17 -040031 cSrcPartition = "c"
32 asSrcPartition = "as"
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000033 lSrcPartition = "l"
34 llSrcPartition = "ll"
Liz Kammer12615db2021-09-28 09:19:17 -040035 cppSrcPartition = "cpp"
36 protoSrcPartition = "proto"
Liz Kammerae3994e2021-10-19 09:45:48 -040037)
38
Liz Kammer2222c6b2021-05-24 15:41:47 -040039// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000040// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040041type staticOrSharedAttributes struct {
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000042 Srcs bazel.LabelListAttribute
43 Srcs_c bazel.LabelListAttribute
44 Srcs_as bazel.LabelListAttribute
Liz Kammere6583482021-10-19 13:56:10 -040045 Hdrs bazel.LabelListAttribute
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000046 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000047
Liz Kammer12615db2021-09-28 09:19:17 -040048 Deps bazel.LabelListAttribute
49 Implementation_deps bazel.LabelListAttribute
50 Dynamic_deps bazel.LabelListAttribute
51 Implementation_dynamic_deps bazel.LabelListAttribute
52 Whole_archive_deps bazel.LabelListAttribute
53 Implementation_whole_archive_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040054
55 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050056
57 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080058
Yu Liu8d82ac52022-05-17 15:13:28 -070059 Native_coverage bazel.BoolAttribute
60
Yu Liufc603162022-03-01 15:44:08 -080061 sdkAttributes
Jingwen Chen53681ef2021-04-29 08:15:13 +000062}
63
Sam Delmericoc7681022022-02-04 21:01:20 +000064// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000065func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040066 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
67 // macro.
68 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Liz Kammer12615db2021-09-28 09:19:17 -040069 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
70 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
71 labelStr := label.Label
Sam Delmericoc7681022022-02-04 21:01:20 +000072 if !exists || !android.IsFilegroup(ctx, m) {
Liz Kammer12615db2021-09-28 09:19:17 -040073 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000074 }
Liz Kammer12615db2021-09-28 09:19:17 -040075 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040076 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000077 }
78
Liz Kammer57e2e7a2021-09-20 12:55:02 -040079 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000080 labels := bazel.LabelPartitions{
81 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050082 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
83 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000084 // TODO(http://b/231968910): If there is ever a filegroup target that
85 // contains .l or .ll files we will need to find a way to add a
86 // LabelMapper for these that identifies these filegroups and
87 // converts them appropriately
88 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
89 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040090 // C++ is the "catch-all" group, and comprises generated sources because we don't
91 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -050092 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Sam Delmericoc7681022022-02-04 21:01:20 +000093 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000094
Sam Delmericoc7681022022-02-04 21:01:20 +000095 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +000096}
97
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000098// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +000099func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000100 lib, ok := module.compiler.(*libraryDecorator)
101 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400102 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000103 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000104 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
105}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000106
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000107// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000108func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000109 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000110}
111
112// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000113func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000114 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400115}
116
Liz Kammer7a210ac2021-09-22 15:52:58 -0400117type depsPartition struct {
118 export bazel.LabelList
119 implementation bazel.LabelList
120}
121
Jingwen Chen55bc8202021-11-02 06:40:51 +0000122type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400123
Jingwen Chen55bc8202021-11-02 06:40:51 +0000124func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400125 if !exportsDeps {
126 return depsPartition{
127 implementation: fn(ctx, allDeps),
128 }
129 }
130
Liz Kammer7a210ac2021-09-22 15:52:58 -0400131 implementation, export := android.FilterList(allDeps, exportedDeps)
132
133 return depsPartition{
134 export: fn(ctx, export),
135 implementation: fn(ctx, implementation),
136 }
137}
138
Jingwen Chen55bc8202021-11-02 06:40:51 +0000139type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400140
Jingwen Chen55bc8202021-11-02 06:40:51 +0000141func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400142 if !exportsDeps {
143 return depsPartition{
144 implementation: fn(ctx, allDeps, excludes),
145 }
146 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400147 implementation, export := android.FilterList(allDeps, exportedDeps)
148
149 return depsPartition{
150 export: fn(ctx, export, excludes),
151 implementation: fn(ctx, implementation, excludes),
152 }
153}
154
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000155// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000156func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400157 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000158
Liz Kammer9abd62d2021-05-21 08:37:59 -0400159 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Alix1be00d42022-05-16 22:56:04 +0000160 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000161 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400162 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400163
Liz Kammer2b8004b2021-10-04 13:55:44 -0400164 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400165 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
166 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
167
Liz Kammer2b8004b2021-10-04 13:55:44 -0400168 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400169 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
170 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
171
172 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500173 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000174 }
Liz Kammer135bf552021-08-11 10:46:06 -0400175 // system_dynamic_deps distinguishes between nil/empty list behavior:
176 // nil -> use default values
177 // empty list -> no values specified
178 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000179
180 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000181 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
182 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
183 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000184 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000185 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000186 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000187 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
188 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
189 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000190 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000191 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000192 }
193
Liz Kammerae3994e2021-10-19 09:45:48 -0400194 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
195 attrs.Srcs = partitionedSrcs[cppSrcPartition]
196 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
197 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000198
Liz Kammer12615db2021-09-28 09:19:17 -0400199 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
200 // TODO(b/208815215): determine whether this is used and add support if necessary
201 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
202 }
203
Jingwen Chenbcf53042021-05-26 04:42:42 +0000204 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000205}
206
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400207// Convenience struct to hold all attributes parsed from prebuilt properties.
208type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000209 Src bazel.LabelAttribute
210 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400211}
212
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000213// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000214func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
215 manySourceFileError := func(axis bazel.ConfigurationAxis, config string) {
216 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most one source file for %s %s\n", axis, config)
217 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400218 var srcLabelAttribute bazel.LabelAttribute
219
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000220 parseSrcs := func(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, srcs []string) {
221 if len(srcs) > 1 {
222 manySourceFileError(axis, config)
223 return
224 } else if len(srcs) == 0 {
225 return
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400226 }
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000227 if srcLabelAttribute.SelectValue(axis, config) != nil {
228 manySourceFileError(axis, config)
229 return
230 }
231
232 src := android.BazelLabelForModuleSrcSingle(ctx, srcs[0])
233 srcLabelAttribute.SetSelectValue(axis, config, src)
234 }
235
236 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
237 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
238 parseSrcs(ctx, axis, config, prebuiltLinkerProperties.Srcs)
239 }
240 })
241
242 var enabledLabelAttribute bazel.BoolAttribute
243 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
244 if props.Enabled != nil {
245 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
246 }
247 parseSrcs(ctx, axis, config, props.Srcs)
248 }
249
250 if isStatic {
251 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
252 if staticProperties, ok := props.(*StaticProperties); ok {
253 parseAttrs(axis, config, staticProperties.Static)
254 }
255 })
256 } else {
257 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
258 if sharedProperties, ok := props.(*SharedProperties); ok {
259 parseAttrs(axis, config, sharedProperties.Shared)
260 }
261 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400262 }
263
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400264 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000265 Src: srcLabelAttribute,
266 Enabled: enabledLabelAttribute,
267 }
268}
269
270func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
271 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
272 for config, props := range configToProps {
273 parseFunc(axis, config, props)
274 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400275 }
276}
277
Liz Kammere6583482021-10-19 13:56:10 -0400278type baseAttributes struct {
279 compilerAttributes
280 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400281
282 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400283}
284
Jingwen Chen107c0de2021-04-09 10:43:12 +0000285// Convenience struct to hold all attributes parsed from compiler properties.
286type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400287 // Options for all languages
288 copts bazel.StringListAttribute
289 // Assembly options and sources
290 asFlags bazel.StringListAttribute
291 asSrcs bazel.LabelListAttribute
292 // C options and sources
293 conlyFlags bazel.StringListAttribute
294 cSrcs bazel.LabelListAttribute
295 // C++ options and sources
296 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000297 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400298
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000299 // Lex sources and options
300 lSrcs bazel.LabelListAttribute
301 llSrcs bazel.LabelListAttribute
302 lexopts bazel.StringListAttribute
303
Liz Kammere6583482021-10-19 13:56:10 -0400304 hdrs bazel.LabelListAttribute
305
Chris Parsons2c788392021-08-10 11:58:07 -0400306 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000307
308 // Not affected by arch variants
309 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500310 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000311 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400312
313 localIncludes bazel.StringListAttribute
314 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400315
Liz Kammer1263d9b2021-12-10 14:28:20 -0500316 includes BazelIncludes
317
Liz Kammer12615db2021-09-28 09:19:17 -0400318 protoSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000319
320 stubsSymbolFile *string
321 stubsVersions bazel.StringListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000322}
323
Liz Kammercac7f692021-12-16 14:19:32 -0500324type filterOutFn func(string) bool
325
326func filterOutStdFlag(flag string) bool {
327 return strings.HasPrefix(flag, "-std=")
328}
329
Alix1be00d42022-05-16 22:56:04 +0000330func filterOutClangUnknownCflags(flag string) bool {
331 for _, f := range config.ClangUnknownCflags {
332 if f == flag {
333 return true
334 }
335 }
336 return false
337}
338
339func parseCommandLineFlags(soongFlags []string, noCoptsTokenization bool, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400340 var result []string
341 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000342 skipFlag := false
343 for _, filter := range filterOut {
344 if filter != nil && filter(flag) {
345 skipFlag = true
346 }
347 }
348 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500349 continue
350 }
Liz Kammere6583482021-10-19 13:56:10 -0400351 // Soong's cflags can contain spaces, like `-include header.h`. For
352 // Bazel's copts, split them up to be compatible with the
353 // no_copts_tokenization feature.
Alix1be00d42022-05-16 22:56:04 +0000354 if noCoptsTokenization {
355 result = append(result, strings.Split(flag, " ")...)
356 } else {
357 // Soong's Version Script and Dynamic List Properties are added as flags
358 // to Bazel's linkopts using "($location label)" syntax.
359 // Splitting on spaces would separate this into two different flags
360 // "($ location" and "label)"
361 result = append(result, flag)
362 }
Liz Kammere6583482021-10-19 13:56:10 -0400363 }
364 return result
365}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000366
Jingwen Chen55bc8202021-11-02 06:40:51 +0000367func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400368 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
369 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
370 if srcsList, ok := parseSrcs(ctx, props); ok {
371 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400372 }
373
Liz Kammere6583482021-10-19 13:56:10 -0400374 localIncludeDirs := props.Local_include_dirs
375 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500376 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400377 if includeBuildDirectory(props.Include_build_directory) {
378 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400379 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000380 }
381
Liz Kammere6583482021-10-19 13:56:10 -0400382 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
383 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
384
Liz Kammercac7f692021-12-16 14:19:32 -0500385 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
386 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
387 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
388 // cases.
Alix1be00d42022-05-16 22:56:04 +0000389 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag, filterOutClangUnknownCflags))
390 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, true, nil))
391 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, true, filterOutClangUnknownCflags))
392 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, true, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400393 ca.rtti.SetSelectValue(axis, config, props.Rtti)
394}
395
Jingwen Chen55bc8202021-11-02 06:40:51 +0000396func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000397 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
398 if stlProps, ok := props.(*StlProperties); ok {
399 if stlProps.Stl == nil {
400 return
401 }
402 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400403 stl := deduplicateStlInput(*stlProps.Stl)
404 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000405 } else if ca.stl != stlProps.Stl {
406 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 -0400407 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000408 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000409 })
Liz Kammere6583482021-10-19 13:56:10 -0400410}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000411
Jingwen Chen55bc8202021-11-02 06:40:51 +0000412func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400413 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400414 "Cflags": &ca.copts,
415 "Asflags": &ca.asFlags,
416 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400417 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400418 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000419 if productConfigProps, exists := productVariableProps[propName]; exists {
420 for productConfigProp, prop := range productConfigProps {
421 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400422 if !ok {
423 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
424 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000425 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
426 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400427 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400428 }
429 }
Liz Kammere6583482021-10-19 13:56:10 -0400430}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400431
Jingwen Chen55bc8202021-11-02 06:40:51 +0000432func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400433 ca.srcs.ResolveExcludes()
434 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
435
Liz Kammer12615db2021-09-28 09:19:17 -0400436 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
437
Liz Kammere6583482021-10-19 13:56:10 -0400438 for p, lla := range partitionedSrcs {
439 // if there are no sources, there is no need for headers
440 if lla.IsEmpty() {
441 continue
442 }
443 lla.Append(implementationHdrs)
444 partitionedSrcs[p] = lla
445 }
446
447 ca.srcs = partitionedSrcs[cppSrcPartition]
448 ca.cSrcs = partitionedSrcs[cSrcPartition]
449 ca.asSrcs = partitionedSrcs[asSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000450 ca.lSrcs = partitionedSrcs[lSrcPartition]
451 ca.llSrcs = partitionedSrcs[llSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400452
453 ca.absoluteIncludes.DeduplicateAxesFromBase()
454 ca.localIncludes.DeduplicateAxesFromBase()
455}
456
457// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000458func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400459 anySrcs := false
460 // Add srcs-like dependencies such as generated files.
461 // First create a LabelList containing these dependencies, then merge the values with srcs.
462 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
463 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
464 anySrcs = true
465 }
466
467 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
468 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
469 anySrcs = true
470 }
471 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
472}
473
Liz Kammera5a29de2022-05-25 23:19:37 -0400474func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
475 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500476 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
477 // Defaults are handled by the toolchain definition.
478 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400479 stdVal := proptools.StringDefault(std, defaultVal)
480 if stdVal == "experimental" || stdVal == defaultVal {
481 if stdVal == "experimental" {
482 stdVal = prefix + "_std_experimental"
483 }
484 if !useGnu {
485 stdVal += "_no_gnu"
486 }
487 } else if !useGnu {
488 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500489 }
490
Liz Kammera5a29de2022-05-25 23:19:37 -0400491 if stdVal == defaultVal {
492 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500493 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400494 return &stdVal
495}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500496
Liz Kammera5a29de2022-05-25 23:19:37 -0400497func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
498 useGnu := useGnuExtensions(gnu_extensions)
499
500 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400501}
502
Liz Kammer1263d9b2021-12-10 14:28:20 -0500503// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
504// is fully-qualified.
505// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
506func packageFromLabel(label string) (string, bool) {
507 split := strings.Split(label, ":")
508 if len(split) != 2 {
509 return "", false
510 }
511 if split[0] == "" {
512 return ".", false
513 }
514 // remove leading "//"
515 return split[0][2:], true
516}
517
518// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
519func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
520 for _, hdr := range labelList.Includes {
521 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
522 absolute = append(absolute, pkg)
523 } else if pkg != "" {
524 relative = append(relative, pkg)
525 }
526 }
527 return relative, absolute
528}
529
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000530// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400531func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400532 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
533 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000534 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400535
536 var implementationHdrs bazel.LabelListAttribute
537
538 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
539 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
540 for axis, configMap := range cp {
541 if _, ok := axisToConfigs[axis]; !ok {
542 axisToConfigs[axis] = map[string]bool{}
543 }
544 for config, _ := range configMap {
545 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400546 }
547 }
548 }
Liz Kammere6583482021-10-19 13:56:10 -0400549 allAxesAndConfigs(archVariantCompilerProps)
550 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000551 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400552
Liz Kammere6583482021-10-19 13:56:10 -0400553 compilerAttrs := compilerAttributes{}
554 linkerAttrs := linkerAttributes{}
555
556 for axis, configs := range axisToConfigs {
557 for config, _ := range configs {
558 var allHdrs []string
559 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
560 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000561 if baseCompilerProps.Lex != nil {
562 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
563 }
Liz Kammere6583482021-10-19 13:56:10 -0400564 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
565 }
566
567 var exportHdrs []string
568
569 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
570 exportHdrs = baseLinkerProps.Export_generated_headers
571
572 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
573 }
574 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
575 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
576 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500577
578 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
579 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
580 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
581
582 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
583 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
584 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
585 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
586 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
587 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
588 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000589
590 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
591 if axis == bazel.NoConfigAxis {
592 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
593 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
594 }
595 }
Liz Kammere6583482021-10-19 13:56:10 -0400596 }
597 }
Liz Kammere6583482021-10-19 13:56:10 -0400598 compilerAttrs.convertStlProps(ctx, module)
599 (&linkerAttrs).convertStripProps(ctx, module)
600
Yu Liu8d82ac52022-05-17 15:13:28 -0700601 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
602 !Bool(module.coverage.Properties.Native_coverage) {
603 // Native_coverage is arch neutral
604 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
605 }
606
Liz Kammere6583482021-10-19 13:56:10 -0400607 productVariableProps := android.ProductVariableProperties(ctx)
608
609 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
610 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
611
612 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500613 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400614
Liz Kammer12615db2021-09-28 09:19:17 -0400615 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
616
617 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
618 // which. This will add the newly generated proto library to the appropriate attribute and nothing
619 // to the other
620 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
621 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
622
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000623 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
624 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
625 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
626
Liz Kammere6583482021-10-19 13:56:10 -0400627 return baseAttributes{
628 compilerAttrs,
629 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400630 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000631 }
632}
633
Yu Liufc603162022-03-01 15:44:08 -0800634func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000635 return sdkAttributes{
636 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800637 Min_sdk_version: module.Properties.Min_sdk_version,
638 }
639}
640
641type sdkAttributes struct {
642 Sdk_version *string
643 Min_sdk_version *string
644}
645
Jingwen Chen107c0de2021-04-09 10:43:12 +0000646// Convenience struct to hold all attributes parsed from linker properties.
647type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500648 deps bazel.LabelListAttribute
649 implementationDeps bazel.LabelListAttribute
650 dynamicDeps bazel.LabelListAttribute
651 implementationDynamicDeps bazel.LabelListAttribute
652 wholeArchiveDeps bazel.LabelListAttribute
653 implementationWholeArchiveDeps bazel.LabelListAttribute
654 systemDynamicDeps bazel.LabelListAttribute
655 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400656
Jingwen Chen6ada5892021-09-17 11:38:09 +0000657 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000658 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500659 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000660 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400661 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000662 stripKeepSymbols bazel.BoolAttribute
663 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
664 stripKeepSymbolsList bazel.StringListAttribute
665 stripAll bazel.BoolAttribute
666 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400667 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400668}
669
Liz Kammer54309532021-12-14 12:21:22 -0500670var (
671 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
672)
673
Jingwen Chen55bc8202021-11-02 06:40:51 +0000674func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400675 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
676 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400677
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400678 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
679 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammere6583482021-10-19 13:56:10 -0400680 // Excludes to parallel Soong:
681 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400682 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
683
Liz Kammere6583482021-10-19 13:56:10 -0400684 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400685
Liz Kammere6583482021-10-19 13:56:10 -0400686 headerLibs := android.FirstUniqueStrings(props.Header_libs)
687 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400688
Liz Kammere6583482021-10-19 13:56:10 -0400689 (&hDeps.export).Append(staticDeps.export)
690 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000691
Liz Kammere6583482021-10-19 13:56:10 -0400692 (&hDeps.implementation).Append(staticDeps.implementation)
693 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400694
Liz Kammere6583482021-10-19 13:56:10 -0400695 systemSharedLibs := props.System_shared_libs
696 // systemSharedLibs distinguishes between nil/empty list behavior:
697 // nil -> use default values
698 // empty list -> no values specified
699 if len(systemSharedLibs) > 0 {
700 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
701 }
702 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
703
704 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500705 excludeSharedLibs := props.Exclude_shared_libs
706 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
707 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
708 })
709 for _, el := range usedSystem {
710 if la.usedSystemDynamicDepAsDynamicDep == nil {
711 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
712 }
713 la.usedSystemDynamicDepAsDynamicDep[el] = true
714 }
715
Liz Kammere6583482021-10-19 13:56:10 -0400716 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
717 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
718 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
719
720 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
721 axisFeatures = append(axisFeatures, "disable_pack_relocations")
722 }
723
724 if Bool(props.Allow_undefined_symbols) {
725 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
726 }
727
728 var linkerFlags []string
729 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500730 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400731 // binaries remove static flag if -shared is in the linker flags
732 if isBinary && android.InList("-shared", linkerFlags) {
733 axisFeatures = append(axisFeatures, "-static_flag")
734 }
735 }
736 if props.Version_script != nil {
737 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
738 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
739 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
740 }
Alix773adaa2022-04-27 17:49:34 +0000741
742 if props.Dynamic_list != nil {
743 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
744 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
745 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
746 }
747
Alix1be00d42022-05-16 22:56:04 +0000748 la.linkopts.SetSelectValue(axis, config, parseCommandLineFlags(linkerFlags, false, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400749 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
750
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500751 if axis == bazel.NoConfigAxis {
752 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
753 }
754
Liz Kammere6583482021-10-19 13:56:10 -0400755 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
756 if props.crt() != nil {
757 if axis == bazel.NoConfigAxis {
758 la.linkCrt.SetSelectValue(axis, config, props.crt())
759 } else if axis == bazel.ArchConfigurationAxis {
760 ctx.ModuleErrorf("nocrt is not supported for arch variants")
761 }
762 }
763
764 if axisFeatures != nil {
765 la.features.SetSelectValue(axis, config, axisFeatures)
766 }
767}
768
Jingwen Chen55bc8202021-11-02 06:40:51 +0000769func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000770 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
771 if stripProperties, ok := props.(*StripProperties); ok {
772 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
773 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
774 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
775 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
776 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000777 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000778 })
Liz Kammere6583482021-10-19 13:56:10 -0400779}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000780
Jingwen Chen55bc8202021-11-02 06:40:51 +0000781func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000782
Liz Kammer47535c52021-06-02 16:02:22 -0400783 type productVarDep struct {
784 // the name of the corresponding excludes field, if one exists
785 excludesField string
786 // reference to the bazel attribute that should be set for the given product variable config
787 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400788
Jingwen Chen55bc8202021-11-02 06:40:51 +0000789 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400790 }
791
792 productVarToDepFields := map[string]productVarDep{
793 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000794 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
795 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
796 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400797 }
798
Liz Kammer47535c52021-06-02 16:02:22 -0400799 for name, dep := range productVarToDepFields {
800 props, exists := productVariableProps[name]
801 excludeProps, excludesExists := productVariableProps[dep.excludesField]
802 // if neither an include or excludes property exists, then skip it
803 if !exists && !excludesExists {
804 continue
805 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000806 // Collect all the configurations that an include or exclude property exists for.
807 // We want to iterate all configurations rather than either the include or exclude because, for a
808 // particular configuration, we may have either only an include or an exclude to handle.
809 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
810 for p := range props {
811 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400812 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000813 for p := range excludeProps {
814 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400815 }
816
Jingwen Chen25825ca2021-11-15 12:28:43 +0000817 for productConfigProp := range productConfigProps {
818 prop, includesExists := props[productConfigProp]
819 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400820 var includes, excludes []string
821 var ok bool
822 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000823 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400824 ctx.ModuleErrorf("Could not convert product variable %s property", name)
825 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000826 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400827 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
828 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400829
Jingwen Chen58ff6802021-11-17 12:14:41 +0000830 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000831 dep.attribute.SetSelectValue(
832 productConfigProp.ConfigurationAxis(),
833 productConfigProp.SelectKey(),
834 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
835 )
Liz Kammer47535c52021-06-02 16:02:22 -0400836 }
837 }
Liz Kammere6583482021-10-19 13:56:10 -0400838}
Liz Kammer47535c52021-06-02 16:02:22 -0400839
Liz Kammer54309532021-12-14 12:21:22 -0500840func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
841 // if system dynamic deps have the default value, any use of a system dynamic library used will
842 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
843 // from bionic OSes.
844 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
845 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
846 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
847 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
848 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
849 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
850 }
851
Liz Kammere6583482021-10-19 13:56:10 -0400852 la.deps.ResolveExcludes()
853 la.implementationDeps.ResolveExcludes()
854 la.dynamicDeps.ResolveExcludes()
855 la.implementationDynamicDeps.ResolveExcludes()
856 la.wholeArchiveDeps.ResolveExcludes()
857 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -0500858
Jingwen Chen91220d72021-03-24 02:18:33 -0400859}
860
Jingwen Chened9c17d2021-04-13 07:14:55 +0000861// Relativize a list of root-relative paths with respect to the module's
862// directory.
863//
864// include_dirs Soong prop are root-relative (b/183742505), but
865// local_include_dirs, export_include_dirs and export_system_include_dirs are
866// module dir relative. This function makes a list of paths entirely module dir
867// relative.
868//
869// For the `include` attribute, Bazel wants the paths to be relative to the
870// module.
871func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000872 var relativePaths []string
873 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000874 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
875 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
876 if err != nil {
877 panic(err)
878 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000879 relativePaths = append(relativePaths, relativePath)
880 }
881 return relativePaths
882}
883
Liz Kammer5fad5012021-09-09 14:08:21 -0400884// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
885// attributes.
886type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500887 AbsoluteIncludes bazel.StringListAttribute
888 Includes bazel.StringListAttribute
889 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400890}
891
Liz Kammer54549442022-05-11 13:55:06 -0400892func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500893 var exported BazelIncludes
894 if includes != nil {
895 exported = *includes
896 } else {
897 exported = BazelIncludes{}
898 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000899 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
900 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
901 if len(flagExporterProperties.Export_include_dirs) > 0 {
902 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
903 }
904 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
905 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 -0400906 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400907 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000908 })
Liz Kammer1263d9b2021-12-10 14:28:20 -0500909 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400910 exported.Includes.DeduplicateAxesFromBase()
911 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400912
Liz Kammer5fad5012021-09-09 14:08:21 -0400913 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400914}
Chris Parsons953b3562021-09-20 15:14:39 -0400915
Jingwen Chen55bc8202021-11-02 06:40:51 +0000916func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400917 label := android.BazelModuleLabel(ctx, m)
Liz Kammer35ca77e2021-12-22 15:31:40 -0500918 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GenerateCcLibraryStaticOnly(m.Name()) {
919 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -0400920 }
921 return label
922}
923
Jingwen Chen55bc8202021-11-02 06:40:51 +0000924func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400925 // cc_library, at it's root name, propagates the shared library, which depends on the static
926 // library.
927 return android.BazelModuleLabel(ctx, m)
928}
929
Jingwen Chen55bc8202021-11-02 06:40:51 +0000930func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400931 label := bazelLabelForStaticModule(ctx, m)
932 if aModule, ok := m.(android.Module); ok {
933 if android.IsModulePrebuilt(aModule) {
934 label += "_alwayslink"
935 }
936 }
937 return label
938}
939
Jingwen Chen55bc8202021-11-02 06:40:51 +0000940func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400941 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
942}
943
Jingwen Chen55bc8202021-11-02 06:40:51 +0000944func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400945 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
946}
947
Jingwen Chen55bc8202021-11-02 06:40:51 +0000948func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400949 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
950}
951
Jingwen Chen55bc8202021-11-02 06:40:51 +0000952func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400953 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
954}
955
Jingwen Chen55bc8202021-11-02 06:40:51 +0000956func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400957 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
958}
959
Jingwen Chen55bc8202021-11-02 06:40:51 +0000960func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400961 // This is not elegant, but bp2build's shared library targets only propagate
962 // their header information as part of the normal C++ provider.
963 return bazelLabelForSharedDeps(ctx, modules)
964}
965
Jingwen Chen55bc8202021-11-02 06:40:51 +0000966func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400967 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
968}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400969
970type binaryLinkerAttrs struct {
971 Linkshared *bool
972}
973
Jingwen Chen55bc8202021-11-02 06:40:51 +0000974func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400975 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000976 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
977 linkerProps := props.(*BinaryLinkerProperties)
978 staticExecutable := linkerProps.Static_executable
979 if axis == bazel.NoConfigAxis {
980 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
981 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -0400982 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000983 } else if staticExecutable != nil {
984 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
985 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
986 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -0400987 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000988 })
Liz Kammer2b8004b2021-10-04 13:55:44 -0400989
990 return attrs
991}