blob: b205c8e1a954d1543ed39de1e5df16d1f7e71dbd [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"
Spandan Das4242f102023-04-19 22:31:54 +000020 "sync"
Chris Parsons484e50a2021-05-13 15:13:04 -040021
22 "android/soong/android"
23 "android/soong/bazel"
Alix1be00d42022-05-16 22:56:04 +000024 "android/soong/cc/config"
Liz Kammer0db0e342023-07-18 11:39:30 -040025 "android/soong/genrule"
Liz Kammer7a210ac2021-09-22 15:52:58 -040026
Chris Parsons953b3562021-09-20 15:14:39 -040027 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040028
29 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040030)
31
Liz Kammerae3994e2021-10-19 09:45:48 -040032const (
Trevor Radcliffecee4e052022-09-06 19:31:25 +000033 cSrcPartition = "c"
34 asSrcPartition = "as"
35 asmSrcPartition = "asm"
36 lSrcPartition = "l"
37 llSrcPartition = "ll"
38 cppSrcPartition = "cpp"
39 protoSrcPartition = "proto"
40 aidlSrcPartition = "aidl"
41 syspropSrcPartition = "sysprop"
Alixe2667872023-04-24 14:57:32 +000042
43 yaccSrcPartition = "yacc"
44
45 rScriptSrcPartition = "renderScript"
Liz Kammer91487d42022-09-13 11:27:11 -040046
Liz Kammer5f5dbaa2023-07-17 17:44:08 -040047 xsdSrcPartition = "xsd"
48
Liz Kammer0db0e342023-07-18 11:39:30 -040049 genrulePartition = "genrule"
50
Spandan Dasa99348d2023-08-01 23:10:05 +000051 protoFromGenPartition = "proto_gen"
52
Liz Kammer5f5dbaa2023-07-17 17:44:08 -040053 hdrPartition = "hdr"
54
Liz Kammer91487d42022-09-13 11:27:11 -040055 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040056)
57
Liz Kammer2222c6b2021-05-24 15:41:47 -040058// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000059// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040060type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040061 Srcs bazel.LabelListAttribute
62 Srcs_c bazel.LabelListAttribute
63 Srcs_as bazel.LabelListAttribute
64 Srcs_aidl bazel.LabelListAttribute
65 Hdrs bazel.LabelListAttribute
66 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000067
Liz Kammer12615db2021-09-28 09:19:17 -040068 Deps bazel.LabelListAttribute
69 Implementation_deps bazel.LabelListAttribute
70 Dynamic_deps bazel.LabelListAttribute
71 Implementation_dynamic_deps bazel.LabelListAttribute
72 Whole_archive_deps bazel.LabelListAttribute
73 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070074 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040075
76 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050077
78 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080079
Yu Liuf01a0f02022-12-07 15:45:30 -080080 Native_coverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -070081
Liz Kammeraceec252023-03-24 09:46:36 -040082 Apex_available []string
83
Trevor Radcliffea8b44162023-04-14 18:25:24 +000084 Features bazel.StringListAttribute
85
Yu Liufc603162022-03-01 15:44:08 -080086 sdkAttributes
Sam Delmericofb3bb322022-10-21 10:42:24 -040087
88 tidyAttributes
89}
90
91type tidyAttributes struct {
Sam Delmerico63f0c932023-03-14 14:05:28 -040092 Tidy *string
Sam Delmericofb3bb322022-10-21 10:42:24 -040093 Tidy_flags []string
94 Tidy_checks []string
95 Tidy_checks_as_errors []string
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040096 Tidy_disabled_srcs bazel.LabelListAttribute
Sam Delmerico4c902d62022-11-02 14:17:15 -040097 Tidy_timeout_srcs bazel.LabelListAttribute
Sam Delmericofb3bb322022-10-21 10:42:24 -040098}
99
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400100func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
Sam Delmericofb3bb322022-10-21 10:42:24 -0400101 for _, f := range m.features {
102 if tidy, ok := f.(*tidyFeature); ok {
Sam Delmerico63f0c932023-03-14 14:05:28 -0400103 var tidyAttr *string
104 if tidy.Properties.Tidy != nil {
105 if *tidy.Properties.Tidy {
106 tidyAttr = proptools.StringPtr("local")
107 } else {
108 tidyAttr = proptools.StringPtr("never")
109 }
110 }
111 moduleAttrs.Tidy = tidyAttr
Sam Delmericofb3bb322022-10-21 10:42:24 -0400112 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
113 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
114 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
115 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400116
117 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400118 archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
119 for axis, configToProps := range archVariantProps {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800120 for cfg, _props := range configToProps {
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400121 if archProps, ok := _props.(*BaseCompilerProperties); ok {
122 archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800123 moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, cfg, archDisabledSrcs)
Sam Delmerico4c902d62022-11-02 14:17:15 -0400124 archTimeoutSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_timeout_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800125 moduleAttrs.Tidy_timeout_srcs.SetSelectValue(axis, cfg, archTimeoutSrcs)
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400126 }
127 }
Sam Delmericofb3bb322022-10-21 10:42:24 -0400128 }
Jingwen Chen53681ef2021-04-29 08:15:13 +0000129}
130
Spandan Dasa99348d2023-08-01 23:10:05 +0000131// Returns an unchanged label and a bool indicating whether the dep is a genrule that produces .proto files
132func protoFromGenPartitionMapper(pathCtx android.BazelConversionContext) bazel.LabelMapper {
133 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
134 mod, exists := ctx.ModuleFromName(label.OriginalModuleName)
135 if !exists {
136 return label.Label, false
137 }
138 gen, isGen := mod.(*genrule.Module)
139 if !isGen {
140 return label.Label, false
141 }
142 if containsProto(ctx, gen.RawOutputFiles(pathCtx)) {
143 // Return unmodified label + true
144 // True will ensure that this module gets dropped from `srcs` of the generated cc_* target. `srcs` is reserved for .cpp files
145 return label.Label, true
146 }
147 return label.Label, false
148 }
149}
150
151// Returns true if srcs contains only .proto files
152// Raises an exception if there is a combination of .proto and non .proto srcs
153func containsProto(ctx bazel.OtherModuleContext, srcs []string) bool {
154 onlyProtos := false
155 for _, src := range srcs {
156 if strings.HasSuffix(src, ".proto") {
157 onlyProtos = true
158 } else if onlyProtos {
159 // This is not a proto file, and we have encountered a .proto file previously
160 ctx.ModuleErrorf("TOOD: Add bp2build support combination of .proto and non .proto files in outs of genrule")
161 }
162 }
163 return onlyProtos
164}
165
Sam Delmericoc7681022022-02-04 21:01:20 +0000166// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000167func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400168 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
169 // macro.
170 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -0400171 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
172
173 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -0400174 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400175 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
176 return labelStr, false
177 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700178 // If the filegroup is already converted to aidl_library or proto_library,
179 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
180 fg, _ := m.(android.FileGroupAsLibrary)
181 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400182 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000183 }
Liz Kammer12615db2021-09-28 09:19:17 -0400184 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400185 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000186 }
187
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400188 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000189 labels := bazel.LabelPartitions{
190 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500191 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
192 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700193 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400194 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000195 // TODO(http://b/231968910): If there is ever a filegroup target that
196 // contains .l or .ll files we will need to find a way to add a
197 // LabelMapper for these that identifies these filegroups and
198 // converts them appropriately
Spandan Dasa99348d2023-08-01 23:10:05 +0000199 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
200 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
201 rScriptSrcPartition: bazel.LabelPartition{Extensions: []string{".fs", ".rscript"}},
202 xsdSrcPartition: bazel.LabelPartition{LabelMapper: android.XsdLabelMapper(xsdConfigCppTarget)},
203 protoFromGenPartition: bazel.LabelPartition{LabelMapper: protoFromGenPartitionMapper(ctx)},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400204 // C++ is the "catch-all" group, and comprises generated sources because we don't
205 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000206 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
207 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Spandan Dasdf4c2132023-05-09 23:58:52 +0000208 yaccSrcPartition: bazel.LabelPartition{Extensions: []string{".y", "yy"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000209 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000210
Sam Delmericoc7681022022-02-04 21:01:20 +0000211 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000212}
213
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400214func partitionHeaders(ctx android.BazelConversionPathContext, hdrs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
215 labels := bazel.LabelPartitions{
Liz Kammer0db0e342023-07-18 11:39:30 -0400216 xsdSrcPartition: bazel.LabelPartition{LabelMapper: android.XsdLabelMapper(xsdConfigCppTarget)},
217 genrulePartition: bazel.LabelPartition{LabelMapper: genrule.GenruleCcHeaderLabelMapper},
218 hdrPartition: bazel.LabelPartition{Keep_remainder: true},
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400219 }
220 return bazel.PartitionLabelListAttribute(ctx, &hdrs, labels)
221}
222
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000223// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000224func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000225 lib, ok := module.compiler.(*libraryDecorator)
226 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400227 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000228 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000229 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
230}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000231
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000232// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000233func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000234 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000235}
236
237// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000238func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000239 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400240}
241
Liz Kammer7a210ac2021-09-22 15:52:58 -0400242type depsPartition struct {
243 export bazel.LabelList
244 implementation bazel.LabelList
245}
246
Jingwen Chen55bc8202021-11-02 06:40:51 +0000247type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400248
Jingwen Chen55bc8202021-11-02 06:40:51 +0000249func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400250 if !exportsDeps {
251 return depsPartition{
252 implementation: fn(ctx, allDeps),
253 }
254 }
255
Liz Kammer7a210ac2021-09-22 15:52:58 -0400256 implementation, export := android.FilterList(allDeps, exportedDeps)
257
258 return depsPartition{
259 export: fn(ctx, export),
260 implementation: fn(ctx, implementation),
261 }
262}
263
Jingwen Chen55bc8202021-11-02 06:40:51 +0000264type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400265
Jingwen Chen55bc8202021-11-02 06:40:51 +0000266func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400267 if !exportsDeps {
268 return depsPartition{
269 implementation: fn(ctx, allDeps, excludes),
270 }
271 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400272 implementation, export := android.FilterList(allDeps, exportedDeps)
273
274 return depsPartition{
275 export: fn(ctx, export, excludes),
276 implementation: fn(ctx, implementation, excludes),
277 }
278}
279
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000280func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
281 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800282 for cfg, props := range configToProps {
283 parseFunc(axis, cfg, props)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000284 }
285 }
286}
287
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000288// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Liz Kammeraceec252023-03-24 09:46:36 -0400289func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400290 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000291
Liz Kammer9abd62d2021-05-21 08:37:59 -0400292 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000293 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutHiddenVisibility))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000294 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400295 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400296
Liz Kammer2b8004b2021-10-04 13:55:44 -0400297 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400298 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
299 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
300
Liz Kammer2b8004b2021-10-04 13:55:44 -0400301 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400302 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
303 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
304
305 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500306 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000307 }
Liz Kammer135bf552021-08-11 10:46:06 -0400308 // system_dynamic_deps distinguishes between nil/empty list behavior:
309 // nil -> use default values
310 // empty list -> no values specified
311 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000312
Liz Kammeraceec252023-03-24 09:46:36 -0400313 var apexAvailable []string
Jingwen Chenbcf53042021-05-26 04:42:42 +0000314 if isStatic {
Liz Kammeraceec252023-03-24 09:46:36 -0400315 apexAvailable = lib.StaticProperties.Static.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000316 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
317 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
318 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000319 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000320 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000321 } else {
Liz Kammeraceec252023-03-24 09:46:36 -0400322 apexAvailable = lib.SharedProperties.Shared.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000323 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
324 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
325 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000326 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000327 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000328 }
329
Liz Kammerae3994e2021-10-19 09:45:48 -0400330 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
331 attrs.Srcs = partitionedSrcs[cppSrcPartition]
332 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
333 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000334
Spandan Das39b6cc52023-04-12 19:05:49 +0000335 attrs.Apex_available = android.ConvertApexAvailableToTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), apexAvailable)
Liz Kammeraceec252023-03-24 09:46:36 -0400336
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000337 attrs.Features.Append(convertHiddenVisibilityToFeatureStaticOrShared(ctx, module, isStatic))
338
Liz Kammer12615db2021-09-28 09:19:17 -0400339 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
340 // TODO(b/208815215): determine whether this is used and add support if necessary
341 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
342 }
343
Jingwen Chenbcf53042021-05-26 04:42:42 +0000344 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000345}
346
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400347// Convenience struct to hold all attributes parsed from prebuilt properties.
348type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000349 Src bazel.LabelAttribute
350 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400351}
352
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000353func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
354 srcFileError := func() {
355 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
356 }
357 if len(srcs) > 1 {
358 srcFileError()
359 return
360 } else if len(srcs) == 0 {
361 return
362 }
363 if srcLabelAttribute.SelectValue(axis, config) != nil {
364 srcFileError()
365 return
366 }
367 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
368}
369
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000370// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000371func 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 +0000372
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400373 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000374 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
375 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000376 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000377 }
378 })
379
380 var enabledLabelAttribute bazel.BoolAttribute
381 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
382 if props.Enabled != nil {
383 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
384 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000385 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000386 }
387
388 if isStatic {
389 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
390 if staticProperties, ok := props.(*StaticProperties); ok {
391 parseAttrs(axis, config, staticProperties.Static)
392 }
393 })
394 } else {
395 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
396 if sharedProperties, ok := props.(*SharedProperties); ok {
397 parseAttrs(axis, config, sharedProperties.Shared)
398 }
399 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400400 }
401
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400402 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000403 Src: srcLabelAttribute,
404 Enabled: enabledLabelAttribute,
405 }
406}
407
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000408func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
409 var srcLabelAttribute bazel.LabelAttribute
410 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
411 if props, ok := props.(*prebuiltLinkerProperties); ok {
412 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000413 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000414 })
415
416 return prebuiltAttributes{
417 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400418 }
419}
420
Colin Crossc5075e92022-12-05 16:46:39 -0800421func bp2BuildParsePrebuiltObjectProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
422 var srcLabelAttribute bazel.LabelAttribute
423 bp2BuildPropParseHelper(ctx, module, &prebuiltObjectProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
424 if props, ok := props.(*prebuiltObjectProperties); ok {
425 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
426 }
427 })
428
429 return prebuiltAttributes{
430 Src: srcLabelAttribute,
431 }
432}
433
Liz Kammere6583482021-10-19 13:56:10 -0400434type baseAttributes struct {
435 compilerAttributes
436 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400437
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000438 // A combination of compilerAttributes.features and linkerAttributes.features, as well as sanitizer features
Cole Faust5fa4e962022-08-22 14:31:04 -0700439 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400440 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400441 aidlDependency *bazel.LabelAttribute
Yu Liuf01a0f02022-12-07 15:45:30 -0800442 Native_coverage *bool
Liz Kammere6583482021-10-19 13:56:10 -0400443}
444
Jingwen Chen107c0de2021-04-09 10:43:12 +0000445// Convenience struct to hold all attributes parsed from compiler properties.
446type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400447 // Options for all languages
448 copts bazel.StringListAttribute
449 // Assembly options and sources
450 asFlags bazel.StringListAttribute
451 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700452 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400453 // C options and sources
454 conlyFlags bazel.StringListAttribute
455 cSrcs bazel.LabelListAttribute
456 // C++ options and sources
457 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000458 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400459
Liz Kammer084d6a92023-06-22 16:23:53 -0400460 // xsd config sources
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400461 xsdSrcs bazel.LabelListAttribute
462 exportXsdSrcs bazel.LabelListAttribute
Liz Kammer084d6a92023-06-22 16:23:53 -0400463
Liz Kammer0db0e342023-07-18 11:39:30 -0400464 // genrule headers
465 genruleHeaders bazel.LabelListAttribute
466 exportGenruleHeaders bazel.LabelListAttribute
467
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000468 // Lex sources and options
469 lSrcs bazel.LabelListAttribute
470 llSrcs bazel.LabelListAttribute
471 lexopts bazel.StringListAttribute
472
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000473 // Sysprop sources
474 syspropSrcs bazel.LabelListAttribute
475
Spandan Dasdf4c2132023-05-09 23:58:52 +0000476 // Yacc sources
477 yaccSrc *bazel.LabelAttribute
478 yaccFlags bazel.StringListAttribute
479 yaccGenLocationHeader bazel.BoolAttribute
480 yaccGenPositionHeader bazel.BoolAttribute
481
Alixe2667872023-04-24 14:57:32 +0000482 rsSrcs bazel.LabelListAttribute
483
Liz Kammere6583482021-10-19 13:56:10 -0400484 hdrs bazel.LabelListAttribute
485
Chris Parsons2c788392021-08-10 11:58:07 -0400486 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000487
488 // Not affected by arch variants
489 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500490 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000491 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400492
493 localIncludes bazel.StringListAttribute
494 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400495
Liz Kammer1263d9b2021-12-10 14:28:20 -0500496 includes BazelIncludes
497
Alixe2667872023-04-24 14:57:32 +0000498 protoSrcs bazel.LabelListAttribute
499 aidlSrcs bazel.LabelListAttribute
500 rscriptSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000501
502 stubsSymbolFile *string
503 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700504
505 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500506
Spandan Das39ccf932023-05-26 18:03:39 +0000507 stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500508 suffix bazel.StringAttribute
Vinh Tran99270ea2022-11-28 11:15:23 -0500509
510 fdoProfile bazel.LabelAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000511}
512
Liz Kammercac7f692021-12-16 14:19:32 -0500513type filterOutFn func(string) bool
514
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000515// filterOutHiddenVisibility removes the flag specifying hidden visibility as
516// this flag is converted to a toolchain feature
517func filterOutHiddenVisibility(flag string) bool {
518 return flag == config.VisibilityHiddenFlag
519}
520
Liz Kammercac7f692021-12-16 14:19:32 -0500521func filterOutStdFlag(flag string) bool {
522 return strings.HasPrefix(flag, "-std=")
523}
524
Alix1be00d42022-05-16 22:56:04 +0000525func filterOutClangUnknownCflags(flag string) bool {
526 for _, f := range config.ClangUnknownCflags {
527 if f == flag {
528 return true
529 }
530 }
531 return false
532}
533
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000534func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400535 var result []string
536 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000537 skipFlag := false
538 for _, filter := range filterOut {
539 if filter != nil && filter(flag) {
540 skipFlag = true
541 }
542 }
543 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500544 continue
545 }
Liz Kammere6583482021-10-19 13:56:10 -0400546 // Soong's cflags can contain spaces, like `-include header.h`. For
547 // Bazel's copts, split them up to be compatible with the
548 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000549 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400550 }
551 return result
552}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000553
Jingwen Chen55bc8202021-11-02 06:40:51 +0000554func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400555 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
556 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400557 srcsList, ok := parseSrcs(ctx, props)
Liz Kammer084d6a92023-06-22 16:23:53 -0400558
559 if ok {
Liz Kammere6583482021-10-19 13:56:10 -0400560 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400561 }
562
Liz Kammere6583482021-10-19 13:56:10 -0400563 localIncludeDirs := props.Local_include_dirs
564 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500565 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400566 if includeBuildDirectory(props.Include_build_directory) {
567 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400568 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000569 }
570
Liz Kammere6583482021-10-19 13:56:10 -0400571 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
572 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
573
Cole Faust5fa4e962022-08-22 14:31:04 -0700574 instructionSet := proptools.StringDefault(props.Instruction_set, "")
575 if instructionSet == "arm" {
Trevor Radcliffe5f0c2ac2023-05-15 18:00:59 +0000576 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm"})
Cole Faust5fa4e962022-08-22 14:31:04 -0700577 } else if instructionSet != "" && instructionSet != "thumb" {
578 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
579 }
580
Liz Kammercac7f692021-12-16 14:19:32 -0500581 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
582 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
583 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
584 // cases.
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000585 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags, filterOutHiddenVisibility))
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000586 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
587 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
588 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400589 ca.rtti.SetSelectValue(axis, config, props.Rtti)
590}
591
Jingwen Chen55bc8202021-11-02 06:40:51 +0000592func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000593 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
594 if stlProps, ok := props.(*StlProperties); ok {
595 if stlProps.Stl == nil {
596 return
597 }
598 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400599 stl := deduplicateStlInput(*stlProps.Stl)
600 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000601 } else if ca.stl != stlProps.Stl {
602 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 -0400603 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000604 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000605 })
Liz Kammere6583482021-10-19 13:56:10 -0400606}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000607
Jingwen Chen55bc8202021-11-02 06:40:51 +0000608func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400609 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400610 "Cflags": &ca.copts,
611 "Asflags": &ca.asFlags,
Yu Liu93893ba2023-05-01 13:49:52 -0700612 "Cppflags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400613 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400614 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000615 if productConfigProps, exists := productVariableProps[propName]; exists {
616 for productConfigProp, prop := range productConfigProps {
617 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400618 if !ok {
619 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
620 }
Cole Faust150f9a52023-04-26 10:52:24 -0700621 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name())
Jingwen Chen25825ca2021-11-15 12:28:43 +0000622 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400623 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400624 }
625 }
Liz Kammere6583482021-10-19 13:56:10 -0400626}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400627
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400628func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs, exportHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400629 ca.srcs.ResolveExcludes()
630 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400631 partitionedImplHdrs := partitionHeaders(ctx, implementationHdrs)
632 partitionedHdrs := partitionHeaders(ctx, exportHdrs)
Liz Kammere6583482021-10-19 13:56:10 -0400633
Liz Kammer12615db2021-09-28 09:19:17 -0400634 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Spandan Dasa99348d2023-08-01 23:10:05 +0000635 ca.protoSrcs.Append(partitionedSrcs[protoFromGenPartition])
Vinh Tran9f6796a2022-08-16 13:10:31 -0400636 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400637
Liz Kammere6583482021-10-19 13:56:10 -0400638 for p, lla := range partitionedSrcs {
639 // if there are no sources, there is no need for headers
640 if lla.IsEmpty() {
641 continue
642 }
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400643 lla.Append(partitionedImplHdrs[hdrPartition])
Liz Kammere6583482021-10-19 13:56:10 -0400644 partitionedSrcs[p] = lla
645 }
646
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400647 ca.hdrs = partitionedHdrs[hdrPartition]
648
649 ca.includesFromHeaders(ctx, partitionedImplHdrs[hdrPartition], partitionedHdrs[hdrPartition])
650
651 xsdSrcs := bazel.SubtractBazelLabelListAttribute(partitionedSrcs[xsdSrcPartition], partitionedHdrs[xsdSrcPartition])
652 xsdSrcs.Append(partitionedImplHdrs[xsdSrcPartition])
653 ca.exportXsdSrcs = partitionedHdrs[xsdSrcPartition]
654 ca.xsdSrcs = bazel.FirstUniqueBazelLabelListAttribute(xsdSrcs)
655
Liz Kammer0db0e342023-07-18 11:39:30 -0400656 ca.genruleHeaders = partitionedImplHdrs[genrulePartition]
657 ca.exportGenruleHeaders = partitionedHdrs[genrulePartition]
658
Liz Kammere6583482021-10-19 13:56:10 -0400659 ca.srcs = partitionedSrcs[cppSrcPartition]
660 ca.cSrcs = partitionedSrcs[cSrcPartition]
661 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700662 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000663 ca.lSrcs = partitionedSrcs[lSrcPartition]
664 ca.llSrcs = partitionedSrcs[llSrcPartition]
Spandan Dasdf4c2132023-05-09 23:58:52 +0000665 if yacc := partitionedSrcs[yaccSrcPartition]; !yacc.IsEmpty() {
666 if len(yacc.Value.Includes) > 1 {
667 ctx.PropertyErrorf("srcs", "Found multiple yacc (.y/.yy) files in library")
668 }
669 ca.yaccSrc = bazel.MakeLabelAttribute(yacc.Value.Includes[0].Label)
670 }
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000671 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Alixe2667872023-04-24 14:57:32 +0000672 ca.rscriptSrcs = partitionedSrcs[rScriptSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400673
674 ca.absoluteIncludes.DeduplicateAxesFromBase()
675 ca.localIncludes.DeduplicateAxesFromBase()
676}
677
678// Parse srcs from an arch or OS's props value.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400679func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400680 anySrcs := false
681 // Add srcs-like dependencies such as generated files.
682 // First create a LabelList containing these dependencies, then merge the values with srcs.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400683 genSrcs := props.Generated_sources
Spandan Das922171d2023-05-31 23:32:40 +0000684 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, genSrcs, props.Exclude_generated_sources)
Liz Kammere6583482021-10-19 13:56:10 -0400685 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
686 anySrcs = true
687 }
688
689 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400690
Liz Kammere6583482021-10-19 13:56:10 -0400691 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
692 anySrcs = true
693 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400694
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400695 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
Liz Kammere6583482021-10-19 13:56:10 -0400696}
697
Liz Kammera5a29de2022-05-25 23:19:37 -0400698func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
699 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500700 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
701 // Defaults are handled by the toolchain definition.
702 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400703 stdVal := proptools.StringDefault(std, defaultVal)
704 if stdVal == "experimental" || stdVal == defaultVal {
705 if stdVal == "experimental" {
706 stdVal = prefix + "_std_experimental"
707 }
708 if !useGnu {
709 stdVal += "_no_gnu"
710 }
711 } else if !useGnu {
712 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500713 }
714
Liz Kammera5a29de2022-05-25 23:19:37 -0400715 if stdVal == defaultVal {
716 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500717 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400718 return &stdVal
719}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500720
Liz Kammera5a29de2022-05-25 23:19:37 -0400721func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
722 useGnu := useGnuExtensions(gnu_extensions)
723
724 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400725}
726
Liz Kammer1263d9b2021-12-10 14:28:20 -0500727// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
728// is fully-qualified.
729// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
730func packageFromLabel(label string) (string, bool) {
731 split := strings.Split(label, ":")
732 if len(split) != 2 {
733 return "", false
734 }
735 if split[0] == "" {
736 return ".", false
737 }
738 // remove leading "//"
739 return split[0][2:], true
740}
741
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400742// includesFromHeaders gets the include directories needed from generated headers
743func (ca *compilerAttributes) includesFromHeaders(ctx android.BazelConversionPathContext, implHdrs, hdrs bazel.LabelListAttribute) {
744 local, absolute := includesFromLabelListAttribute(implHdrs, ca.localIncludes, ca.absoluteIncludes)
745 localExport, absoluteExport := includesFromLabelListAttribute(hdrs, ca.includes.Includes, ca.includes.AbsoluteIncludes)
746
747 ca.localIncludes = local
748 ca.absoluteIncludes = absolute
749
750 ca.includes.Includes = localExport
751 ca.includes.AbsoluteIncludes = absoluteExport
752}
753
754// includesFromLabelList extracts the packages from a LabelListAttribute that should be includes and
755// combines them with existing local/absolute includes.
756func includesFromLabelListAttribute(attr bazel.LabelListAttribute, existingLocal, existingAbsolute bazel.StringListAttribute) (bazel.StringListAttribute, bazel.StringListAttribute) {
757 localAttr := existingLocal.Clone()
758 absoluteAttr := existingAbsolute.Clone()
759 if !attr.Value.IsEmpty() {
760 l, a := includesFromLabelList(attr.Value, existingLocal.Value, existingAbsolute.Value)
761 localAttr.SetSelectValue(bazel.NoConfigAxis, "", l)
762 absoluteAttr.SetSelectValue(bazel.NoConfigAxis, "", a)
763 }
764 for axis, configToLabels := range attr.ConfigurableValues {
765 for c, labels := range configToLabels {
766 local := existingLocal.SelectValue(axis, c)
767 absolute := existingAbsolute.SelectValue(axis, c)
768 l, a := includesFromLabelList(labels, local, absolute)
769 localAttr.SetSelectValue(axis, c, l)
770 absoluteAttr.SetSelectValue(axis, c, a)
771 }
772 }
773 return *localAttr, *absoluteAttr
774}
775
776// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList.
777func includesFromLabelList(labelList bazel.LabelList, existingRel, existingAbs []string) ([]string, []string) {
778 var relative, absolute []string
Liz Kammer1263d9b2021-12-10 14:28:20 -0500779 for _, hdr := range labelList.Includes {
780 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
781 absolute = append(absolute, pkg)
782 } else if pkg != "" {
783 relative = append(relative, pkg)
784 }
785 }
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400786 if len(relative)+len(existingRel) != 0 {
787 relative = android.FirstUniqueStrings(append(append([]string{}, existingRel...), relative...))
788 }
789 if len(absolute)+len(existingAbs) != 0 {
790 absolute = android.FirstUniqueStrings(append(append([]string{}, existingAbs...), absolute...))
791 }
Liz Kammer1263d9b2021-12-10 14:28:20 -0500792 return relative, absolute
793}
794
Cole Faust7071a052022-07-29 15:58:33 -0700795type YasmAttributes struct {
796 Srcs bazel.LabelListAttribute
797 Flags bazel.StringListAttribute
798 Include_dirs bazel.StringListAttribute
799}
800
801func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
802 if ca.asmSrcs.IsEmpty() {
803 return nil
804 }
805
806 // Yasm needs the include directories from both local_includes and
807 // export_include_dirs. We don't care about actually exporting them from the
808 // yasm rule though, because they will also be present on the cc_ rule that
809 // wraps this yasm rule.
810 includes := ca.localIncludes.Clone()
811 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
812 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
813 if len(flagExporterProperties.Export_include_dirs) > 0 {
814 x := bazel.StringListAttribute{}
815 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
816 includes.Append(x)
817 }
818 }
819 })
820
821 ctx.CreateBazelTargetModule(
822 bazel.BazelTargetModuleProperties{
823 Rule_class: "yasm",
824 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
825 },
826 android.CommonAttributes{Name: m.Name() + "_yasm"},
827 &YasmAttributes{
828 Srcs: ca.asmSrcs,
829 Flags: ca.asFlags,
830 Include_dirs: *includes,
831 })
832
833 // We only want to add a dependency on the _yasm target if there are asm
834 // sources in the current configuration. If there are unconfigured asm
835 // sources, always add the dependency. Otherwise, add the dependency only
836 // on the configuration axes and values that had asm sources.
837 if len(ca.asmSrcs.Value.Includes) > 0 {
838 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
839 }
840
841 ret := &bazel.LabelAttribute{}
842 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800843 for cfg := range ca.asmSrcs.ConfigurableValues[axis] {
844 ret.SetSelectValue(axis, cfg, bazel.Label{Label: ":" + m.Name() + "_yasm"})
Cole Faust7071a052022-07-29 15:58:33 -0700845 }
846 }
847 return ret
848}
849
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000850// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400851func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400852 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
853 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000854 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400855
Liz Kammere6583482021-10-19 13:56:10 -0400856 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
857 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
858 for axis, configMap := range cp {
859 if _, ok := axisToConfigs[axis]; !ok {
860 axisToConfigs[axis] = map[string]bool{}
861 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800862 for cfg := range configMap {
863 axisToConfigs[axis][cfg] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400864 }
865 }
866 }
Liz Kammere6583482021-10-19 13:56:10 -0400867 allAxesAndConfigs(archVariantCompilerProps)
868 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000869 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400870
Liz Kammere6583482021-10-19 13:56:10 -0400871 compilerAttrs := compilerAttributes{}
872 linkerAttrs := linkerAttributes{}
873
Vinh Tran367d89d2023-04-28 11:21:25 -0400874 var aidlLibs bazel.LabelList
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400875 var implementationHdrs, exportHdrs bazel.LabelListAttribute
Vinh Tran367d89d2023-04-28 11:21:25 -0400876
Chris Parsons7b3289b2023-01-26 17:30:44 -0500877 // Iterate through these axes in a deterministic order. This is required
878 // because processing certain dependencies may result in concatenating
879 // elements along other axes. (For example, processing NoConfig may result
880 // in elements being added to InApex). This is thus the only way to ensure
881 // that the order of entries in each list is in a predictable order.
882 for _, axis := range bazel.SortedConfigurationAxes(axisToConfigs) {
883 configs := axisToConfigs[axis]
Sasha Smundak39a301c2022-12-29 17:11:49 -0800884 for cfg := range configs {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400885 var allHdrs []string
Sasha Smundak39a301c2022-12-29 17:11:49 -0800886 if baseCompilerProps, ok := archVariantCompilerProps[axis][cfg].(*BaseCompilerProperties); ok {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400887 allHdrs = baseCompilerProps.Generated_headers
Spandan Das922171d2023-05-31 23:32:40 +0000888
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000889 if baseCompilerProps.Lex != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800890 compilerAttrs.lexopts.SetSelectValue(axis, cfg, baseCompilerProps.Lex.Flags)
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000891 }
Spandan Dasdf4c2132023-05-09 23:58:52 +0000892 if baseCompilerProps.Yacc != nil {
893 compilerAttrs.yaccFlags.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Flags)
894 compilerAttrs.yaccGenLocationHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_location_hh)
895 compilerAttrs.yaccGenPositionHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_position_hh)
896 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800897 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, cfg, baseCompilerProps)
Vinh Tran367d89d2023-04-28 11:21:25 -0400898 aidlLibs.Append(android.BazelLabelForModuleDeps(ctx, baseCompilerProps.Aidl.Libs))
Liz Kammere6583482021-10-19 13:56:10 -0400899 }
900
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400901 var exportedHdrs []string
Liz Kammere6583482021-10-19 13:56:10 -0400902
Sasha Smundak39a301c2022-12-29 17:11:49 -0800903 if baseLinkerProps, ok := archVariantLinkerProps[axis][cfg].(*BaseLinkerProperties); ok {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400904 exportedHdrs = baseLinkerProps.Export_generated_headers
Liz Kammer48cdbeb2023-03-17 10:17:50 -0400905 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module, axis, cfg, baseLinkerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400906 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400907
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400908 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportedHdrs, android.BazelLabelForModuleDeps)
Liz Kammer084d6a92023-06-22 16:23:53 -0400909
Sasha Smundak39a301c2022-12-29 17:11:49 -0800910 implementationHdrs.SetSelectValue(axis, cfg, headers.implementation)
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400911 exportHdrs.SetSelectValue(axis, cfg, headers.export)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000912
Sasha Smundak39a301c2022-12-29 17:11:49 -0800913 if libraryProps, ok := archVariantLibraryProperties[axis][cfg].(*LibraryProperties); ok {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000914 if axis == bazel.NoConfigAxis {
Sam Delmerico75dbca22023-04-20 13:13:25 +0000915 if libraryProps.Stubs.Symbol_file != nil {
916 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
917 versions := android.CopyOf(libraryProps.Stubs.Versions)
918 normalizeVersions(ctx, versions)
919 versions = addCurrentVersionIfNotPresent(versions)
920 compilerAttrs.stubsVersions.SetSelectValue(axis, cfg, versions)
921 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000922 }
Spandan Das39ccf932023-05-26 18:03:39 +0000923 if stem := libraryProps.Stem; stem != nil {
924 compilerAttrs.stem.SetSelectValue(axis, cfg, stem)
925 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500926 if suffix := libraryProps.Suffix; suffix != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800927 compilerAttrs.suffix.SetSelectValue(axis, cfg, suffix)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500928 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000929 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400930
Liz Kammere6583482021-10-19 13:56:10 -0400931 }
932 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400933
Liz Kammere6583482021-10-19 13:56:10 -0400934 compilerAttrs.convertStlProps(ctx, module)
935 (&linkerAttrs).convertStripProps(ctx, module)
936
Yu Liuf01a0f02022-12-07 15:45:30 -0800937 var nativeCoverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -0700938 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
939 !Bool(module.coverage.Properties.Native_coverage) {
Yu Liuf01a0f02022-12-07 15:45:30 -0800940 nativeCoverage = BoolPtr(false)
Yu Liu8d82ac52022-05-17 15:13:28 -0700941 }
942
Cole Faust912bc882023-03-08 12:29:50 -0800943 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammere6583482021-10-19 13:56:10 -0400944
945 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
946 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
947
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400948 (&compilerAttrs).finalize(ctx, implementationHdrs, exportHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500949 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400950
Cole Faust7071a052022-07-29 15:58:33 -0700951 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
952
Liz Kammer0db0e342023-07-18 11:39:30 -0400953 (&linkerAttrs).deps.Append(compilerAttrs.exportGenruleHeaders)
954 (&linkerAttrs).implementationDeps.Append(compilerAttrs.genruleHeaders)
955
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400956 (&linkerAttrs).wholeArchiveDeps.Append(compilerAttrs.exportXsdSrcs)
957 (&linkerAttrs).implementationWholeArchiveDeps.Append(compilerAttrs.xsdSrcs)
958
Liz Kammer12615db2021-09-28 09:19:17 -0400959 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
960
961 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
962 // which. This will add the newly generated proto library to the appropriate attribute and nothing
963 // to the other
964 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
965 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400966
Vinh Tran367d89d2023-04-28 11:21:25 -0400967 aidlDep := bp2buildCcAidlLibrary(
968 ctx, module,
969 compilerAttrs.aidlSrcs,
970 bazel.LabelListAttribute{
971 Value: aidlLibs,
972 },
973 linkerAttrs,
Vinh Trane6842942023-04-28 11:21:25 -0400974 compilerAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -0400975 )
Vinh Tranfde57eb2022-08-29 17:46:58 -0400976 if aidlDep != nil {
977 if lib, ok := module.linker.(*libraryDecorator); ok {
978 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
979 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
980 } else {
981 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
982 }
983 }
984 }
Liz Kammer12615db2021-09-28 09:19:17 -0400985
Spandan Dasdf4c2132023-05-09 23:58:52 +0000986 // Create a cc_yacc_static_library if srcs contains .y/.yy files
987 // This internal target will produce an .a file that will be statically linked to the parent library
988 if yaccDep := bp2buildCcYaccLibrary(ctx, compilerAttrs, linkerAttrs); yaccDep != nil {
989 (&linkerAttrs).implementationWholeArchiveDeps.Add(yaccDep)
990 }
991
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000992 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
993 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
994 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
995
Vinh Tran99270ea2022-11-28 11:15:23 -0500996 if module.afdo != nil && module.afdo.Properties.Afdo {
997 fdoProfileDep := bp2buildFdoProfile(ctx, module)
998 if fdoProfileDep != nil {
999 (&compilerAttrs).fdoProfile.SetValue(*fdoProfileDep)
1000 }
1001 }
1002
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001003 if !compilerAttrs.syspropSrcs.IsEmpty() {
1004 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
1005 }
1006
Zi Wang9f609db2023-01-04 11:06:54 -08001007 linkerAttrs.wholeArchiveDeps.Prepend = true
1008 linkerAttrs.deps.Prepend = true
1009 compilerAttrs.localIncludes.Prepend = true
1010 compilerAttrs.absoluteIncludes.Prepend = true
1011 compilerAttrs.hdrs.Prepend = true
1012
Alixe2667872023-04-24 14:57:32 +00001013 convertedRsSrcs, rsAbsIncludes, rsLocalIncludes := bp2buildRScript(ctx, module, compilerAttrs)
1014 (&compilerAttrs).srcs.Add(&convertedRsSrcs)
1015 (&compilerAttrs).absoluteIncludes.Append(rsAbsIncludes)
1016 (&compilerAttrs).localIncludes.Append(rsLocalIncludes)
1017 (&compilerAttrs).localIncludes.Value = android.FirstUniqueStrings(compilerAttrs.localIncludes.Value)
1018
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001019 features := compilerAttrs.features.Clone().Append(linkerAttrs.features).Append(bp2buildSanitizerFeatures(ctx, module))
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001020 features = features.Append(bp2buildLtoFeatures(ctx, module))
Trevor Radcliffea8b44162023-04-14 18:25:24 +00001021 features = features.Append(convertHiddenVisibilityToFeatureBase(ctx, module))
Cole Faust5fa4e962022-08-22 14:31:04 -07001022 features.DeduplicateAxesFromBase()
1023
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +00001024 addMuslSystemDynamicDeps(ctx, linkerAttrs)
1025
Spandan Dasf3ab29b2023-08-17 00:23:59 +00001026 // Dedupe all deps.
1027 (&linkerAttrs).deps.Value = bazel.FirstUniqueBazelLabelList((&linkerAttrs).deps.Value)
1028 (&linkerAttrs).implementationDeps.Value = bazel.FirstUniqueBazelLabelList((&linkerAttrs).implementationDeps.Value)
1029 (&linkerAttrs).implementationDynamicDeps.Value = bazel.FirstUniqueBazelLabelList((&linkerAttrs).implementationDynamicDeps.Value)
1030 (&linkerAttrs).wholeArchiveDeps.Value = bazel.FirstUniqueBazelLabelList((&linkerAttrs).wholeArchiveDeps.Value)
1031 (&linkerAttrs).implementationWholeArchiveDeps.Value = bazel.FirstUniqueBazelLabelList((&linkerAttrs).implementationWholeArchiveDeps.Value)
1032
Liz Kammere6583482021-10-19 13:56:10 -04001033 return baseAttributes{
1034 compilerAttrs,
1035 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -07001036 *features,
Liz Kammer12615db2021-09-28 09:19:17 -04001037 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -04001038 aidlDep,
Yu Liuf01a0f02022-12-07 15:45:30 -08001039 nativeCoverage,
Jingwen Chen107c0de2021-04-09 10:43:12 +00001040 }
1041}
1042
Spandan Dasdf4c2132023-05-09 23:58:52 +00001043type ccYaccLibraryAttributes struct {
1044 Src bazel.LabelAttribute
1045 Flags bazel.StringListAttribute
1046 Gen_location_hh bazel.BoolAttribute
1047 Gen_position_hh bazel.BoolAttribute
1048 Local_includes bazel.StringListAttribute
1049 Implementation_deps bazel.LabelListAttribute
1050 Implementation_dynamic_deps bazel.LabelListAttribute
1051}
1052
1053func bp2buildCcYaccLibrary(ctx android.Bp2buildMutatorContext, ca compilerAttributes, la linkerAttributes) *bazel.LabelAttribute {
1054 if ca.yaccSrc == nil {
1055 return nil
1056 }
1057 yaccLibraryLabel := ctx.Module().Name() + "_yacc"
1058 ctx.CreateBazelTargetModule(
1059 bazel.BazelTargetModuleProperties{
1060 Rule_class: "cc_yacc_static_library",
1061 Bzl_load_location: "//build/bazel/rules/cc:cc_yacc_library.bzl",
1062 },
1063 android.CommonAttributes{
1064 Name: yaccLibraryLabel,
1065 },
1066 &ccYaccLibraryAttributes{
1067 Src: *ca.yaccSrc,
1068 Flags: ca.yaccFlags,
1069 Gen_location_hh: ca.yaccGenLocationHeader,
1070 Gen_position_hh: ca.yaccGenPositionHeader,
1071 Local_includes: ca.localIncludes,
1072 Implementation_deps: la.implementationDeps,
1073 Implementation_dynamic_deps: la.implementationDynamicDeps,
1074 },
1075 )
1076
1077 yaccLibrary := &bazel.LabelAttribute{
1078 Value: &bazel.Label{
1079 Label: ":" + yaccLibraryLabel,
1080 },
1081 }
1082 return yaccLibrary
1083}
1084
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +00001085// As a workaround for b/261657184, we are manually adding the default value
1086// of system_dynamic_deps for the linux_musl os.
1087// TODO: Solve this properly
1088func addMuslSystemDynamicDeps(ctx android.Bp2buildMutatorContext, attrs linkerAttributes) {
1089 systemDynamicDeps := attrs.systemDynamicDeps.SelectValue(bazel.OsConfigurationAxis, "linux_musl")
1090 if attrs.systemDynamicDeps.HasAxisSpecificValues(bazel.OsConfigurationAxis) && systemDynamicDeps.IsNil() {
1091 attrs.systemDynamicDeps.SetSelectValue(bazel.OsConfigurationAxis, "linux_musl", android.BazelLabelForModuleDeps(ctx, config.MuslDefaultSharedLibraries))
1092 }
1093}
1094
Vinh Tran99270ea2022-11-28 11:15:23 -05001095type fdoProfileAttributes struct {
1096 Absolute_path_profile string
1097}
1098
1099func bp2buildFdoProfile(
1100 ctx android.Bp2buildMutatorContext,
1101 m *Module,
1102) *bazel.Label {
1103 for _, project := range globalAfdoProfileProjects {
Vinh Tranbc9c8b42022-12-09 12:03:52 -05001104 // Ensure handcrafted BUILD file exists in the project
1105 BUILDPath := android.ExistentPathForSource(ctx, project, "BUILD")
1106 if BUILDPath.Valid() {
1107 // We handcraft a BUILD file with fdo_profile targets that use the existing profiles in the project
1108 // This implementation is assuming that every afdo profile in globalAfdoProfileProjects already has
1109 // an associated fdo_profile target declared in the same package.
1110 // TODO(b/260714900): Handle arch-specific afdo profiles (e.g. `<module-name>-arm<64>.afdo`)
1111 path := android.ExistentPathForSource(ctx, project, m.Name()+".afdo")
1112 if path.Valid() {
1113 // FIXME: Some profiles only exist internally and are not released to AOSP.
1114 // When generated BUILD files are checked in, we'll run into merge conflict.
1115 // The cc_library_shared target in AOSP won't have reference to an fdo_profile target because
1116 // the profile doesn't exist. Internally, the same cc_library_shared target will
1117 // have reference to the fdo_profile.
1118 // For more context, see b/258682955#comment2
1119 fdoProfileLabel := "//" + strings.TrimSuffix(project, "/") + ":" + m.Name()
1120 return &bazel.Label{
1121 Label: fdoProfileLabel,
1122 }
Vinh Tran99270ea2022-11-28 11:15:23 -05001123 }
1124 }
1125 }
1126
1127 return nil
1128}
1129
Vinh Tran9f6796a2022-08-16 13:10:31 -04001130func bp2buildCcAidlLibrary(
1131 ctx android.Bp2buildMutatorContext,
1132 m *Module,
Vinh Tran367d89d2023-04-28 11:21:25 -04001133 aidlSrcs bazel.LabelListAttribute,
1134 aidlLibs bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -04001135 linkerAttrs linkerAttributes,
Vinh Trane6842942023-04-28 11:21:25 -04001136 compilerAttrs compilerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -04001137) *bazel.LabelAttribute {
Vinh Tran367d89d2023-04-28 11:21:25 -04001138 var aidlLibsFromSrcs, aidlFiles bazel.LabelListAttribute
1139 apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), ctx.Module())
1140
1141 if !aidlSrcs.IsEmpty() {
1142 aidlLibsFromSrcs, aidlFiles = aidlSrcs.Partition(func(src bazel.Label) bool {
Vinh Trana3b8b782022-09-14 11:40:24 -04001143 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
1144 fg.ShouldConvertToAidlLibrary(ctx) {
1145 return true
1146 }
1147 return false
1148 })
Vinh Tran9f6796a2022-08-16 13:10:31 -04001149
Vinh Tran367d89d2023-04-28 11:21:25 -04001150 if !aidlFiles.IsEmpty() {
Vinh Trana3b8b782022-09-14 11:40:24 -04001151 aidlLibName := m.Name() + "_aidl_library"
1152 ctx.CreateBazelTargetModule(
1153 bazel.BazelTargetModuleProperties{
1154 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -04001155 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Vinh Trana3b8b782022-09-14 11:40:24 -04001156 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001157 android.CommonAttributes{
1158 Name: aidlLibName,
Liz Kammer2b3f56e2023-03-23 11:51:49 -04001159 Tags: apexAvailableTags,
Vinh Trana3b8b782022-09-14 11:40:24 -04001160 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001161 &aidlLibraryAttributes{
1162 Srcs: aidlFiles,
Vinh Trana3b8b782022-09-14 11:40:24 -04001163 },
1164 )
Vinh Tran367d89d2023-04-28 11:21:25 -04001165 aidlLibsFromSrcs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
Vinh Trana3b8b782022-09-14 11:40:24 -04001166 }
Vinh Tran9f6796a2022-08-16 13:10:31 -04001167 }
1168
Vinh Tran367d89d2023-04-28 11:21:25 -04001169 allAidlLibs := aidlLibs.Clone()
1170 allAidlLibs.Append(aidlLibsFromSrcs)
1171
1172 if !allAidlLibs.IsEmpty() {
1173 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
1174 // Since parent cc_library already has these dependencies, we can add them as implementation
1175 // deps so that they don't re-export
1176 implementationDeps := linkerAttrs.deps.Clone()
1177 implementationDeps.Append(linkerAttrs.implementationDeps)
1178 implementationDynamicDeps := linkerAttrs.dynamicDeps.Clone()
1179 implementationDynamicDeps.Append(linkerAttrs.implementationDynamicDeps)
1180
1181 sdkAttrs := bp2BuildParseSdkAttributes(m)
1182
Vinh Trane6842942023-04-28 11:21:25 -04001183 exportedIncludes := bp2BuildParseExportedIncludes(ctx, m, &compilerAttrs.includes)
1184 includeAttrs := includesAttributes{
1185 Export_includes: exportedIncludes.Includes,
1186 Export_absolute_includes: exportedIncludes.AbsoluteIncludes,
1187 Export_system_includes: exportedIncludes.SystemIncludes,
1188 Local_includes: compilerAttrs.localIncludes,
1189 Absolute_includes: compilerAttrs.absoluteIncludes,
1190 }
1191
Vinh Tran367d89d2023-04-28 11:21:25 -04001192 ctx.CreateBazelTargetModule(
1193 bazel.BazelTargetModuleProperties{
1194 Rule_class: "cc_aidl_library",
1195 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
1196 },
1197 android.CommonAttributes{Name: ccAidlLibrarylabel},
1198 &ccAidlLibraryAttributes{
1199 Deps: *allAidlLibs,
1200 Implementation_deps: *implementationDeps,
1201 Implementation_dynamic_deps: *implementationDynamicDeps,
1202 Tags: apexAvailableTags,
1203 sdkAttributes: sdkAttrs,
Vinh Trane6842942023-04-28 11:21:25 -04001204 includesAttributes: includeAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -04001205 },
1206 )
1207 label := &bazel.LabelAttribute{
1208 Value: &bazel.Label{
1209 Label: ":" + ccAidlLibrarylabel,
1210 },
1211 }
1212 return label
1213 }
1214
Vinh Trana3b8b782022-09-14 11:40:24 -04001215 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -04001216}
1217
Yu Liufc603162022-03-01 15:44:08 -08001218func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +00001219 return sdkAttributes{
1220 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -08001221 Min_sdk_version: module.Properties.Min_sdk_version,
1222 }
1223}
1224
1225type sdkAttributes struct {
1226 Sdk_version *string
1227 Min_sdk_version *string
1228}
1229
Jingwen Chen107c0de2021-04-09 10:43:12 +00001230// Convenience struct to hold all attributes parsed from linker properties.
1231type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -05001232 deps bazel.LabelListAttribute
1233 implementationDeps bazel.LabelListAttribute
1234 dynamicDeps bazel.LabelListAttribute
1235 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -07001236 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -05001237 wholeArchiveDeps bazel.LabelListAttribute
1238 implementationWholeArchiveDeps bazel.LabelListAttribute
1239 systemDynamicDeps bazel.LabelListAttribute
Liz Kammerb4928432023-06-02 18:43:36 -04001240 usedSystemDynamicDepAsStaticDep map[string]bool
Liz Kammer54309532021-12-14 12:21:22 -05001241 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -04001242
Rupert Shuttleworth484aa252021-12-10 07:22:53 -05001243 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001244 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -04001245 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001246 stripKeepSymbols bazel.BoolAttribute
1247 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
1248 stripKeepSymbolsList bazel.StringListAttribute
1249 stripAll bazel.BoolAttribute
1250 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -04001251 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -04001252}
1253
Liz Kammer54309532021-12-14 12:21:22 -05001254var (
1255 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -04001256 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -05001257)
1258
Vinh Tran85fb07c2022-09-16 16:17:48 -04001259// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
1260// since all libs are already excluded by default
Liz Kammer748d7072023-01-25 12:07:43 -05001261func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, props *BaseLinkerProperties) {
1262 excludeSharedLibs := bazelLabelForSharedDeps(ctx, props.Target.Apex.Exclude_shared_libs)
1263 sharedExcludes := bazel.LabelList{Excludes: excludeSharedLibs.Includes}
1264 sharedExcludesLabelList := bazel.LabelListAttribute{}
1265 sharedExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, sharedExcludes)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001266
Liz Kammer748d7072023-01-25 12:07:43 -05001267 la.dynamicDeps.Append(sharedExcludesLabelList)
1268 la.implementationDynamicDeps.Append(sharedExcludesLabelList)
1269
1270 excludeStaticLibs := bazelLabelForStaticDeps(ctx, props.Target.Apex.Exclude_static_libs)
1271 staticExcludes := bazel.LabelList{Excludes: excludeStaticLibs.Includes}
1272 staticExcludesLabelList := bazel.LabelListAttribute{}
1273 staticExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, staticExcludes)
1274
1275 la.deps.Append(staticExcludesLabelList)
1276 la.implementationDeps.Append(staticExcludesLabelList)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001277}
1278
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001279func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, module *Module, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
1280 isBinary := module.Binary()
Liz Kammere6583482021-10-19 13:56:10 -04001281 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
1282 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -04001283
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001284 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -04001285 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
1286 if axis == bazel.NoConfigAxis {
1287 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
1288 if proptools.Bool(props.Use_version_lib) {
1289 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
1290 // remove from static libs so there is no duplicate dependency
1291 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
1292 // only add the dep if it is not in progress
1293 if !versionLibAlreadyInDeps {
Yu Liufe978fd2023-04-24 16:37:18 -07001294 wholeStaticLibs = append(wholeStaticLibs, versionLib)
Liz Kammerbaced712022-09-16 09:01:29 -04001295 }
1296 }
1297 }
1298
Liz Kammere6583482021-10-19 13:56:10 -04001299 // Excludes to parallel Soong:
1300 // 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 -04001301 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001302
Liz Kammerb4928432023-06-02 18:43:36 -04001303 if isBinary && module.StaticExecutable() {
1304 usedSystemStatic := android.FilterListPred(staticLibs, func(s string) bool {
1305 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, props.Exclude_static_libs)
1306 })
1307
1308 for _, el := range usedSystemStatic {
1309 if la.usedSystemDynamicDepAsStaticDep == nil {
1310 la.usedSystemDynamicDepAsStaticDep = map[string]bool{}
1311 }
1312 la.usedSystemDynamicDepAsStaticDep[el] = true
1313 }
1314 }
Vinh Tran85fb07c2022-09-16 16:17:48 -04001315 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1316 ctx,
1317 !isBinary,
1318 staticLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001319 props.Exclude_static_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001320 props.Export_static_lib_headers,
1321 bazelLabelForStaticDepsExcludes,
1322 )
Liz Kammer7a210ac2021-09-22 15:52:58 -04001323
Liz Kammere6583482021-10-19 13:56:10 -04001324 headerLibs := android.FirstUniqueStrings(props.Header_libs)
1325 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -04001326
Liz Kammere6583482021-10-19 13:56:10 -04001327 (&hDeps.export).Append(staticDeps.export)
1328 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001329
Liz Kammere6583482021-10-19 13:56:10 -04001330 (&hDeps.implementation).Append(staticDeps.implementation)
1331 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -04001332
Liz Kammere6583482021-10-19 13:56:10 -04001333 systemSharedLibs := props.System_shared_libs
1334 // systemSharedLibs distinguishes between nil/empty list behavior:
1335 // nil -> use default values
1336 // empty list -> no values specified
1337 if len(systemSharedLibs) > 0 {
1338 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
1339 }
1340 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
1341
1342 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -05001343 excludeSharedLibs := props.Exclude_shared_libs
1344 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
1345 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
1346 })
Liz Kammerb4928432023-06-02 18:43:36 -04001347
Liz Kammer54309532021-12-14 12:21:22 -05001348 for _, el := range usedSystem {
1349 if la.usedSystemDynamicDepAsDynamicDep == nil {
1350 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
1351 }
1352 la.usedSystemDynamicDepAsDynamicDep[el] = true
1353 }
1354
Vinh Tran85fb07c2022-09-16 16:17:48 -04001355 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1356 ctx,
1357 !isBinary,
1358 sharedLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001359 props.Exclude_shared_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001360 props.Export_shared_lib_headers,
1361 bazelLabelForSharedDepsExcludes,
1362 )
Liz Kammere6583482021-10-19 13:56:10 -04001363 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
1364 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Liz Kammer748d7072023-01-25 12:07:43 -05001365 la.resolveTargetApexProp(ctx, props)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001366
Wei Li81852ca2022-07-27 00:22:06 -07001367 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
Yu Liu10174ff2023-02-21 12:05:26 -08001368 // If a dependency in la.implementationDynamicDeps or la.dynamicDeps has stubs, its
1369 // stub variant should be used when the dependency is linked in a APEX. The
1370 // dependencies in NoConfigAxis and OsConfigurationAxis/OsAndroid are grouped by
1371 // having stubs or not, so Bazel select() statement can be used to choose
1372 // source/stub variants of them.
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001373 apexAvailable := module.ApexAvailable()
Spandan Dasac693b22023-04-24 00:07:38 +00001374 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.export, &la.dynamicDeps, 0, false)
1375 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.implementation, &la.implementationDynamicDeps, 1, false)
1376 if len(systemSharedLibs) > 0 {
1377 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, bazelLabelForSharedDeps(ctx, systemSharedLibs), &la.systemDynamicDeps, 2, true)
1378 }
Wei Li81852ca2022-07-27 00:22:06 -07001379 }
Liz Kammere6583482021-10-19 13:56:10 -04001380
1381 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1382 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1383 }
1384
1385 if Bool(props.Allow_undefined_symbols) {
1386 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1387 }
1388
1389 var linkerFlags []string
1390 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001391 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001392 // binaries remove static flag if -shared is in the linker flags
1393 if isBinary && android.InList("-shared", linkerFlags) {
1394 axisFeatures = append(axisFeatures, "-static_flag")
1395 }
1396 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001397
Alex Márquez Pérez Muñíz Díaz Puras Thaureaux01ec55e2023-01-30 22:53:04 +00001398 if !props.libCrt() {
1399 axisFeatures = append(axisFeatures, "-use_libcrt")
1400 }
1401 if !props.crt() {
1402 axisFeatures = append(axisFeatures, "-link_crt")
1403 }
1404
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001405 // This must happen before the addition of flags for Version Script and
1406 // Dynamic List, as these flags must be split on spaces and those must not
1407 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1408
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001409 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001410 if props.Version_script != nil {
1411 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001412 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001413 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
Trevor Radcliffef06dd912023-05-19 14:51:41 +00001414 axisFeatures = append(axisFeatures, "android_cfi_exports_map")
Liz Kammere6583482021-10-19 13:56:10 -04001415 }
Alix773adaa2022-04-27 17:49:34 +00001416
1417 if props.Dynamic_list != nil {
1418 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001419 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001420 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1421 }
1422
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001423 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Spandan Dasfb04c412023-05-15 18:35:36 +00001424 if axis == bazel.OsConfigurationAxis && (config == bazel.OsDarwin || config == bazel.OsLinux || config == bazel.OsWindows) {
1425 linkerFlags = append(linkerFlags, props.Host_ldlibs...)
1426 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001427 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001428
1429 if axisFeatures != nil {
1430 la.features.SetSelectValue(axis, config, axisFeatures)
1431 }
Cole Faust6b29f592022-08-09 09:50:56 -07001432
1433 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1434 if !runtimeDeps.IsEmpty() {
1435 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1436 }
Liz Kammere6583482021-10-19 13:56:10 -04001437}
1438
Spandan Das2518c022023-03-17 03:02:32 +00001439var (
1440 apiSurfaceModuleLibCurrentPackage = "@api_surfaces//" + android.ModuleLibApi.String() + "/current:"
1441)
1442
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001443func availableToSameApexes(a, b []string) bool {
1444 if len(a) == 0 && len(b) == 0 {
1445 return true
1446 }
1447 differ, _, _ := android.ListSetDifference(a, b)
1448 return !differ
1449}
1450
Spandan Das4242f102023-04-19 22:31:54 +00001451var (
Spandan Das9cad90f2023-05-04 17:15:44 +00001452 apiDomainConfigSettingKey = android.NewOnceKey("apiDomainConfigSettingKey")
1453 apiDomainConfigSettingLock sync.Mutex
Spandan Das4242f102023-04-19 22:31:54 +00001454)
1455
Spandan Das9cad90f2023-05-04 17:15:44 +00001456func getApiDomainConfigSettingMap(config android.Config) *map[string]bool {
1457 return config.Once(apiDomainConfigSettingKey, func() interface{} {
Spandan Das4242f102023-04-19 22:31:54 +00001458 return &map[string]bool{}
1459 }).(*map[string]bool)
1460}
1461
Spandan Das9cad90f2023-05-04 17:15:44 +00001462var (
1463 testApexNameToApiDomain = map[string]string{
1464 "test_broken_com.android.art": "com.android.art",
1465 }
1466)
1467
Spandan Dasa43ae132023-05-08 18:33:16 +00001468// GetApiDomain returns the canonical name of the apex. This is synonymous to the apex_name definition.
1469// https://cs.android.com/android/_/android/platform/build/soong/+/e3f0281b8897da1fe23b2f4f3a05f1dc87bcc902:apex/prebuilt.go;l=81-83;drc=2dc7244af985a6ad701b22f1271e606cabba527f;bpv=1;bpt=0
1470// For test apexes, it uses a naming convention heuristic to determine the api domain.
1471// TODO (b/281548611): Move this build/soong/android
1472func GetApiDomain(apexName string) string {
Spandan Das9cad90f2023-05-04 17:15:44 +00001473 if apiDomain, exists := testApexNameToApiDomain[apexName]; exists {
1474 return apiDomain
1475 }
1476 // Remove `test_` prefix
1477 return strings.TrimPrefix(apexName, "test_")
1478}
1479
Spandan Das4242f102023-04-19 22:31:54 +00001480// Create a config setting for this apex in build/bazel/rules/apex
1481// The use case for this is stub/impl selection in cc libraries
1482// Long term, these config_setting(s) should be colocated with the respective apex definitions.
1483// Note that this is an anti-pattern: The config_setting should be created from the apex definition
1484// and not from a cc_library.
1485// This anti-pattern is needed today since not all apexes have been allowlisted.
1486func createInApexConfigSetting(ctx android.TopDownMutatorContext, apexName string) {
1487 if apexName == android.AvailableToPlatform || apexName == android.AvailableToAnyApex {
1488 // These correspond to android-non_apex and android-in_apex
1489 return
1490 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001491 apiDomainConfigSettingLock.Lock()
1492 defer apiDomainConfigSettingLock.Unlock()
Spandan Das4242f102023-04-19 22:31:54 +00001493
1494 // Return if a config_setting has already been created
Spandan Dasa43ae132023-05-08 18:33:16 +00001495 apiDomain := GetApiDomain(apexName)
Spandan Das9cad90f2023-05-04 17:15:44 +00001496 acsm := getApiDomainConfigSettingMap(ctx.Config())
1497 if _, exists := (*acsm)[apiDomain]; exists {
Spandan Das4242f102023-04-19 22:31:54 +00001498 return
1499 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001500 (*acsm)[apiDomain] = true
Spandan Das4242f102023-04-19 22:31:54 +00001501
1502 csa := bazel.ConfigSettingAttributes{
1503 Flag_values: bazel.StringMapAttribute{
Spandan Das9cad90f2023-05-04 17:15:44 +00001504 "//build/bazel/rules/apex:api_domain": apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001505 },
Spandan Das9cad90f2023-05-04 17:15:44 +00001506 // Constraint this to android
1507 Constraint_values: bazel.MakeLabelListAttribute(
1508 bazel.MakeLabelList(
1509 []bazel.Label{
1510 bazel.Label{Label: "//build/bazel/platforms/os:android"},
1511 },
1512 ),
1513 ),
Spandan Das4242f102023-04-19 22:31:54 +00001514 }
1515 ca := android.CommonAttributes{
Spandan Das9cad90f2023-05-04 17:15:44 +00001516 Name: apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001517 }
1518 ctx.CreateBazelConfigSetting(
1519 csa,
1520 ca,
1521 "build/bazel/rules/apex",
1522 )
1523}
1524
1525func inApexConfigSetting(apexAvailable string) string {
1526 if apexAvailable == android.AvailableToPlatform {
Spandan Das6d4d9da2023-04-18 06:20:40 +00001527 return bazel.AndroidPlatform
Spandan Das4242f102023-04-19 22:31:54 +00001528 }
1529 if apexAvailable == android.AvailableToAnyApex {
1530 return bazel.AndroidAndInApex
1531 }
Spandan Dasa43ae132023-05-08 18:33:16 +00001532 apiDomain := GetApiDomain(apexAvailable)
Spandan Das9cad90f2023-05-04 17:15:44 +00001533 return "//build/bazel/rules/apex:" + apiDomain
Spandan Das4242f102023-04-19 22:31:54 +00001534}
1535
Spandan Das6d4d9da2023-04-18 06:20:40 +00001536// Inputs to stub vs impl selection.
1537type stubSelectionInfo struct {
1538 // Label of the implementation library (e.g. //bionic/libc:libc)
1539 impl bazel.Label
1540 // Axis containing the implementation library
1541 axis bazel.ConfigurationAxis
1542 // Axis key containing the implementation library
1543 config string
1544 // API domain of the apex
1545 // For test apexes (test_com.android.foo), this will be the source apex (com.android.foo)
1546 apiDomain string
1547 // List of dep labels
1548 dynamicDeps *bazel.LabelListAttribute
1549 // Boolean value for determining if the dep is in the same api domain
1550 // If false, the label will be rewritten to to the stub label
1551 sameApiDomain bool
1552}
1553
1554func useStubOrImplInApexWithName(ssi stubSelectionInfo) {
1555 lib := ssi.impl
1556 if !ssi.sameApiDomain {
1557 lib = bazel.Label{
1558 Label: apiSurfaceModuleLibCurrentPackage + strings.TrimPrefix(lib.OriginalModuleName, ":"),
1559 }
1560 }
1561 // Create a select statement specific to this apex
1562 inApexSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain))
1563 (&inApexSelectValue).Append(bazel.MakeLabelList([]bazel.Label{lib}))
1564 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain), bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1565 // Delete the library from the common config for this apex
1566 implDynamicDeps := ssi.dynamicDeps.SelectValue(ssi.axis, ssi.config)
1567 implDynamicDeps = bazel.SubtractBazelLabelList(implDynamicDeps, bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1568 ssi.dynamicDeps.SetSelectValue(ssi.axis, ssi.config, implDynamicDeps)
1569 if ssi.axis == bazel.NoConfigAxis {
1570 // Set defaults. Defaults (i.e. host) should use impl and not stubs.
1571 defaultSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1572 (&defaultSelectValue).Append(bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1573 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
1574 }
Liz Kammere6583482021-10-19 13:56:10 -04001575}
1576
Yu Liu10174ff2023-02-21 12:05:26 -08001577func setStubsForDynamicDeps(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis,
Spandan Dasac693b22023-04-24 00:07:38 +00001578 config string, apexAvailable []string, dynamicLibs bazel.LabelList, dynamicDeps *bazel.LabelListAttribute, ind int, buildNonApexWithStubs bool) {
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001579
Spandan Das4242f102023-04-19 22:31:54 +00001580 // Create a config_setting for each apex_available.
1581 // This will be used to select impl of a dep if dep is available to the same apex.
1582 for _, aa := range apexAvailable {
1583 createInApexConfigSetting(ctx.(android.TopDownMutatorContext), aa)
1584 }
1585
Spandan Das6d4d9da2023-04-18 06:20:40 +00001586 apiDomainForSelects := []string{}
1587 for _, apex := range apexAvailable {
1588 apiDomainForSelects = append(apiDomainForSelects, GetApiDomain(apex))
1589 }
1590 // Always emit a select statement for the platform variant.
1591 // This ensures that b build //foo --config=android works
1592 // Soong always creates a platform variant even when the library might not be available to platform.
1593 if !android.InList(android.AvailableToPlatform, apiDomainForSelects) {
1594 apiDomainForSelects = append(apiDomainForSelects, android.AvailableToPlatform)
1595 }
1596 apiDomainForSelects = android.SortedUniqueStrings(apiDomainForSelects)
1597
1598 // Create a select for each apex this library could be included in.
1599 for _, l := range dynamicLibs.Includes {
1600 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
1601 if c, ok := dep.(*Module); !ok || !c.HasStubsVariants() {
1602 continue
1603 }
1604 // TODO (b/280339069): Decrease the verbosity of the generated BUILD files
1605 for _, apiDomain := range apiDomainForSelects {
1606 var sameApiDomain bool
1607 if apiDomain == android.AvailableToPlatform {
1608 // Platform variants in Soong use equality of apex_available for stub/impl selection.
1609 // https://cs.android.com/android/_/android/platform/build/soong/+/316b0158fe57ee7764235923e7c6f3d530da39c6:cc/cc.go;l=3393-3404;drc=176271a426496fa2688efe2b40d5c74340c63375;bpv=1;bpt=0
1610 // One of the factors behind this design choice is cc_test
1611 // Tests only have a platform variant, and using equality of apex_available ensures
1612 // that tests of an apex library gets its implementation and not stubs.
1613 // TODO (b/280343104): Discuss if we can drop this special handling for platform variants.
1614 sameApiDomain = availableToSameApexes(apexAvailable, dep.(*Module).ApexAvailable())
Spandan Das6aaab9d2023-05-04 17:27:30 +00001615 if linkable, ok := ctx.Module().(LinkableInterface); ok && linkable.Bootstrap() {
1616 sameApiDomain = true
1617 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001618 } else {
1619 sameApiDomain = android.InList(apiDomain, dep.(*Module).ApexAvailable())
1620 }
1621 ssi := stubSelectionInfo{
1622 impl: l,
1623 axis: axis,
1624 config: config,
1625 apiDomain: apiDomain,
1626 dynamicDeps: dynamicDeps,
1627 sameApiDomain: sameApiDomain,
1628 }
1629 useStubOrImplInApexWithName(ssi)
1630 }
1631 }
Yu Liu10174ff2023-02-21 12:05:26 -08001632}
1633
Jingwen Chen55bc8202021-11-02 06:40:51 +00001634func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001635 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1636 if stripProperties, ok := props.(*StripProperties); ok {
1637 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1638 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1639 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1640 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1641 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001642 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001643 })
Liz Kammere6583482021-10-19 13:56:10 -04001644}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001645
Jingwen Chen55bc8202021-11-02 06:40:51 +00001646func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001647
Liz Kammer47535c52021-06-02 16:02:22 -04001648 type productVarDep struct {
1649 // the name of the corresponding excludes field, if one exists
1650 excludesField string
1651 // reference to the bazel attribute that should be set for the given product variable config
1652 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001653
Jingwen Chen55bc8202021-11-02 06:40:51 +00001654 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001655 }
1656
Zi Wang0a8a1292022-08-30 06:27:01 +00001657 // an intermediate attribute that holds Header_libs info, and will be appended to
1658 // implementationDeps at the end, to solve the confliction that both header_libs
1659 // and static_libs use implementationDeps.
1660 var headerDeps bazel.LabelListAttribute
1661
Liz Kammer47535c52021-06-02 16:02:22 -04001662 productVarToDepFields := map[string]productVarDep{
1663 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001664 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1665 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1666 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001667 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001668 }
1669
Liz Kammer47535c52021-06-02 16:02:22 -04001670 for name, dep := range productVarToDepFields {
1671 props, exists := productVariableProps[name]
1672 excludeProps, excludesExists := productVariableProps[dep.excludesField]
Sasha Smundak39a301c2022-12-29 17:11:49 -08001673 // if neither an include nor excludes property exists, then skip it
Liz Kammer47535c52021-06-02 16:02:22 -04001674 if !exists && !excludesExists {
1675 continue
1676 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001677 // Collect all the configurations that an include or exclude property exists for.
1678 // We want to iterate all configurations rather than either the include or exclude because, for a
1679 // particular configuration, we may have either only an include or an exclude to handle.
Cole Faust150f9a52023-04-26 10:52:24 -07001680 productConfigProps := make(map[android.ProductConfigOrSoongConfigProperty]bool, len(props)+len(excludeProps))
Jingwen Chen25825ca2021-11-15 12:28:43 +00001681 for p := range props {
1682 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001683 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001684 for p := range excludeProps {
1685 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001686 }
1687
Jingwen Chen25825ca2021-11-15 12:28:43 +00001688 for productConfigProp := range productConfigProps {
1689 prop, includesExists := props[productConfigProp]
1690 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001691 var includes, excludes []string
1692 var ok bool
1693 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001694 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001695 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1696 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001697 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001698 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1699 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001700
Jingwen Chen58ff6802021-11-17 12:14:41 +00001701 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001702 dep.attribute.SetSelectValue(
1703 productConfigProp.ConfigurationAxis(),
1704 productConfigProp.SelectKey(),
1705 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1706 )
Liz Kammer47535c52021-06-02 16:02:22 -04001707 }
1708 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001709 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001710}
Liz Kammer47535c52021-06-02 16:02:22 -04001711
Liz Kammer54309532021-12-14 12:21:22 -05001712func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1713 // if system dynamic deps have the default value, any use of a system dynamic library used will
1714 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001715 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001716 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -08001717 toRemove := bazelLabelForSharedDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001718 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001719 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1720 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001721 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001722 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1723 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001724
1725 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001726 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1727 for _, lib := range toRemove.Includes {
Spandan Das2518c022023-03-17 03:02:32 +00001728 stubLabelInApiSurfaces := bazel.Label{
1729 Label: apiSurfaceModuleLibCurrentPackage + lib.OriginalModuleName,
1730 }
1731 stubsToRemove = append(stubsToRemove, stubLabelInApiSurfaces)
Liz Kammer91487d42022-09-13 11:27:11 -04001732 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001733 // system libraries (e.g. libc, libm, libdl) belong the com.android.runtime api domain
1734 // dedupe the stubs of these libraries from the other api domains (platform, other_apexes...)
1735 for _, aa := range ctx.Module().(*Module).ApexAvailable() {
1736 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, inApexConfigSetting(aa), bazel.MakeLabelList(stubsToRemove))
1737 }
1738 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidPlatform, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001739 }
Liz Kammerb4928432023-06-02 18:43:36 -04001740 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsStaticDep) > 0 {
1741 toRemove := bazelLabelForStaticDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsStaticDep))
1742 la.deps.Exclude(bazel.NoConfigAxis, "", toRemove)
1743 la.deps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1744 la.deps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
1745 la.implementationDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
1746 la.implementationDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1747 la.implementationDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
1748 }
Liz Kammer54309532021-12-14 12:21:22 -05001749
Liz Kammere6583482021-10-19 13:56:10 -04001750 la.deps.ResolveExcludes()
1751 la.implementationDeps.ResolveExcludes()
1752 la.dynamicDeps.ResolveExcludes()
1753 la.implementationDynamicDeps.ResolveExcludes()
1754 la.wholeArchiveDeps.ResolveExcludes()
1755 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001756
Jingwen Chen91220d72021-03-24 02:18:33 -04001757}
1758
Jingwen Chened9c17d2021-04-13 07:14:55 +00001759// Relativize a list of root-relative paths with respect to the module's
1760// directory.
1761//
1762// include_dirs Soong prop are root-relative (b/183742505), but
1763// local_include_dirs, export_include_dirs and export_system_include_dirs are
1764// module dir relative. This function makes a list of paths entirely module dir
1765// relative.
1766//
1767// For the `include` attribute, Bazel wants the paths to be relative to the
1768// module.
1769func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001770 var relativePaths []string
1771 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001772 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1773 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1774 if err != nil {
1775 panic(err)
1776 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001777 relativePaths = append(relativePaths, relativePath)
1778 }
1779 return relativePaths
1780}
1781
Liz Kammer5fad5012021-09-09 14:08:21 -04001782// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1783// attributes.
1784type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001785 AbsoluteIncludes bazel.StringListAttribute
1786 Includes bazel.StringListAttribute
1787 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001788}
1789
Liz Kammer54549442022-05-11 13:55:06 -04001790func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001791 var exported BazelIncludes
1792 if includes != nil {
1793 exported = *includes
1794 } else {
1795 exported = BazelIncludes{}
1796 }
Zi Wang1cb11802022-12-09 16:08:54 -08001797
1798 // cc library Export_include_dirs and Export_system_include_dirs are marked
1799 // "variant_prepend" in struct tag, set their prepend property to true to make
1800 // sure bp2build generates correct result.
1801 exported.Includes.Prepend = true
1802 exported.SystemIncludes.Prepend = true
1803
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001804 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1805 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1806 if len(flagExporterProperties.Export_include_dirs) > 0 {
1807 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1808 }
1809 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1810 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 -04001811 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001812 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001813 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001814 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001815 exported.Includes.DeduplicateAxesFromBase()
1816 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001817
Liz Kammer5fad5012021-09-09 14:08:21 -04001818 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001819}
Chris Parsons953b3562021-09-20 15:14:39 -04001820
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001821func BazelLabelNameForStaticModule(baseLabel string) string {
1822 return baseLabel + "_bp2build_cc_library_static"
1823}
1824
Jingwen Chen55bc8202021-11-02 06:40:51 +00001825func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001826 label := android.BazelModuleLabel(ctx, m)
Sasha Smundak39a301c2022-12-29 17:11:49 -08001827 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001828 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001829 }
1830 return label
1831}
1832
Jingwen Chen55bc8202021-11-02 06:40:51 +00001833func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001834 // cc_library, at it's root name, propagates the shared library, which depends on the static
1835 // library.
1836 return android.BazelModuleLabel(ctx, m)
1837}
1838
Jingwen Chen55bc8202021-11-02 06:40:51 +00001839func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001840 label := bazelLabelForStaticModule(ctx, m)
1841 if aModule, ok := m.(android.Module); ok {
1842 if android.IsModulePrebuilt(aModule) {
1843 label += "_alwayslink"
1844 }
1845 }
1846 return label
1847}
1848
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04001849func xsdConfigCppTarget(xsd android.XsdConfigBp2buildTargets) string {
1850 return xsd.CppBp2buildTargetName()
Liz Kammer084d6a92023-06-22 16:23:53 -04001851}
1852
Jingwen Chen55bc8202021-11-02 06:40:51 +00001853func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001854 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1855}
1856
Jingwen Chen55bc8202021-11-02 06:40:51 +00001857func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001858 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1859}
1860
Jingwen Chen55bc8202021-11-02 06:40:51 +00001861func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001862 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1863}
1864
Jingwen Chen55bc8202021-11-02 06:40:51 +00001865func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001866 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1867}
1868
Jingwen Chen55bc8202021-11-02 06:40:51 +00001869func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001870 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1871}
1872
Jingwen Chen55bc8202021-11-02 06:40:51 +00001873func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001874 // This is not elegant, but bp2build's shared library targets only propagate
1875 // their header information as part of the normal C++ provider.
1876 return bazelLabelForSharedDeps(ctx, modules)
1877}
1878
Zi Wang0a8a1292022-08-30 06:27:01 +00001879func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1880 // This is only used when product_variable header_libs is processed, to follow
1881 // the pattern of depResolutionFunc
1882 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1883}
1884
Jingwen Chen55bc8202021-11-02 06:40:51 +00001885func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001886 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1887}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001888
1889type binaryLinkerAttrs struct {
1890 Linkshared *bool
Spandan Das39ccf932023-05-26 18:03:39 +00001891 Stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001892 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001893}
1894
Jingwen Chen55bc8202021-11-02 06:40:51 +00001895func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001896 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001897 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1898 linkerProps := props.(*BinaryLinkerProperties)
1899 staticExecutable := linkerProps.Static_executable
1900 if axis == bazel.NoConfigAxis {
1901 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1902 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001903 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001904 } else if staticExecutable != nil {
1905 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1906 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1907 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001908 }
Spandan Das39ccf932023-05-26 18:03:39 +00001909 if stem := linkerProps.Stem; stem != nil {
1910 attrs.Stem.SetSelectValue(axis, config, stem)
1911 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001912 if suffix := linkerProps.Suffix; suffix != nil {
1913 attrs.Suffix.SetSelectValue(axis, config, suffix)
1914 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001915 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001916
1917 return attrs
1918}
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001919
1920func bp2buildSanitizerFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1921 sanitizerFeatures := bazel.StringListAttribute{}
1922 bp2BuildPropParseHelper(ctx, m, &SanitizeProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1923 var features []string
1924 if sanitizerProps, ok := props.(*SanitizeProperties); ok {
1925 if sanitizerProps.Sanitize.Integer_overflow != nil && *sanitizerProps.Sanitize.Integer_overflow {
1926 features = append(features, "ubsan_integer_overflow")
1927 }
1928 for _, sanitizer := range sanitizerProps.Sanitize.Misc_undefined {
1929 features = append(features, "ubsan_"+sanitizer)
1930 }
Trevor Radcliffeded095c2023-06-12 19:18:28 +00001931 blocklist := sanitizerProps.Sanitize.Blocklist
1932 if blocklist != nil {
1933 // Format the blocklist name to be used in a feature name
1934 blocklistFeatureSuffix := strings.Replace(strings.ToLower(*blocklist), ".", "_", -1)
Trevor Radcliffed7148712023-07-10 18:50:47 +00001935 features = append(features, "sanitizer_blocklist_"+blocklistFeatureSuffix)
Trevor Radcliffeded095c2023-06-12 19:18:28 +00001936 }
Trevor Radcliffe523c5c62023-06-16 20:15:45 +00001937 if sanitizerProps.Sanitize.Cfi != nil && !proptools.Bool(sanitizerProps.Sanitize.Cfi) {
1938 features = append(features, "-android_cfi")
1939 } else if proptools.Bool(sanitizerProps.Sanitize.Cfi) {
Trevor Radcliffe27669c02023-03-28 20:47:10 +00001940 features = append(features, "android_cfi")
1941 if proptools.Bool(sanitizerProps.Sanitize.Config.Cfi_assembly_support) {
1942 features = append(features, "android_cfi_assembly_support")
1943 }
1944 }
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001945 sanitizerFeatures.SetSelectValue(axis, config, features)
1946 }
1947 })
1948 return sanitizerFeatures
1949}
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001950
1951func bp2buildLtoFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1952 lto_feature_name := "android_thin_lto"
1953 ltoBoolFeatures := bazel.BoolAttribute{}
1954 bp2BuildPropParseHelper(ctx, m, &LTOProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1955 if ltoProps, ok := props.(*LTOProperties); ok {
1956 thinProp := ltoProps.Lto.Thin != nil && *ltoProps.Lto.Thin
1957 thinPropSetToFalse := ltoProps.Lto.Thin != nil && !*ltoProps.Lto.Thin
1958 neverProp := ltoProps.Lto.Never != nil && *ltoProps.Lto.Never
1959 if thinProp {
1960 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(true))
1961 return
1962 }
1963 if neverProp || thinPropSetToFalse {
1964 if thinProp {
1965 ctx.ModuleErrorf("lto.thin and lto.never are mutually exclusive but were specified together")
1966 } else {
1967 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(false))
1968 }
1969 return
1970 }
1971 }
1972 ltoBoolFeatures.SetSelectValue(axis, config, nil)
1973 })
1974
1975 props := m.GetArchVariantProperties(ctx, &LTOProperties{})
1976 ltoStringFeatures, err := ltoBoolFeatures.ToStringListAttribute(func(boolPtr *bool, axis bazel.ConfigurationAxis, config string) []string {
1977 if boolPtr == nil {
1978 return []string{}
1979 }
1980 if !*boolPtr {
1981 return []string{"-" + lto_feature_name}
1982 }
1983 features := []string{lto_feature_name}
1984 if ltoProps, ok := props[axis][config].(*LTOProperties); ok {
1985 if ltoProps.Whole_program_vtables != nil && *ltoProps.Whole_program_vtables {
1986 features = append(features, "android_thin_lto_whole_program_vtables")
1987 }
1988 }
1989 return features
1990 })
1991 if err != nil {
1992 ctx.ModuleErrorf("Error processing LTO attributes: %s", err)
1993 }
1994 return ltoStringFeatures
1995}
Trevor Radcliffea8b44162023-04-14 18:25:24 +00001996
1997func convertHiddenVisibilityToFeatureBase(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1998 visibilityHiddenFeature := bazel.StringListAttribute{}
1999 bp2BuildPropParseHelper(ctx, m, &BaseCompilerProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
2000 if baseCompilerProps, ok := props.(*BaseCompilerProperties); ok {
2001 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, baseCompilerProps.Cflags)
2002 }
2003 })
2004 return visibilityHiddenFeature
2005}
2006
2007func convertHiddenVisibilityToFeatureStaticOrShared(ctx android.BazelConversionPathContext, m *Module, isStatic bool) bazel.StringListAttribute {
2008 visibilityHiddenFeature := bazel.StringListAttribute{}
2009 if isStatic {
2010 bp2BuildPropParseHelper(ctx, m, &StaticProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
2011 if staticProps, ok := props.(*StaticProperties); ok {
2012 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, staticProps.Static.Cflags)
2013 }
2014 })
2015 } else {
2016 bp2BuildPropParseHelper(ctx, m, &SharedProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
2017 if sharedProps, ok := props.(*SharedProperties); ok {
2018 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, sharedProps.Shared.Cflags)
2019 }
2020 })
2021 }
2022
2023 return visibilityHiddenFeature
2024}
2025
2026func convertHiddenVisibilityToFeatureHelper(feature *bazel.StringListAttribute, axis bazel.ConfigurationAxis, configString string, cflags []string) {
2027 if inList(config.VisibilityHiddenFlag, cflags) {
2028 feature.SetSelectValue(axis, configString, []string{"visibility_hidden"})
2029 }
2030}