blob: 6c1646cbb2d35c73299d5f2237b5d89bf073a48b [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040020
21 "android/soong/android"
22 "android/soong/bazel"
Liz Kammer7a210ac2021-09-22 15:52:58 -040023
Chris Parsons953b3562021-09-20 15:14:39 -040024 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040025
26 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040027)
28
Liz Kammerae3994e2021-10-19 09:45:48 -040029const (
Liz Kammer12615db2021-09-28 09:19:17 -040030 cSrcPartition = "c"
31 asSrcPartition = "as"
32 cppSrcPartition = "cpp"
33 protoSrcPartition = "proto"
Liz Kammerae3994e2021-10-19 09:45:48 -040034)
35
Liz Kammer2222c6b2021-05-24 15:41:47 -040036// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000037// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040038type staticOrSharedAttributes struct {
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000039 Srcs bazel.LabelListAttribute
40 Srcs_c bazel.LabelListAttribute
41 Srcs_as bazel.LabelListAttribute
Liz Kammere6583482021-10-19 13:56:10 -040042 Hdrs bazel.LabelListAttribute
Jingwen Chenc4dc9b42021-06-11 12:51:48 +000043 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000044
Liz Kammer12615db2021-09-28 09:19:17 -040045 Deps bazel.LabelListAttribute
46 Implementation_deps bazel.LabelListAttribute
47 Dynamic_deps bazel.LabelListAttribute
48 Implementation_dynamic_deps bazel.LabelListAttribute
49 Whole_archive_deps bazel.LabelListAttribute
50 Implementation_whole_archive_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040051
52 System_dynamic_deps bazel.LabelListAttribute
Jingwen Chen53681ef2021-04-29 08:15:13 +000053}
54
Jingwen Chen55bc8202021-11-02 06:40:51 +000055func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer12615db2021-09-28 09:19:17 -040056 // Check that a module is a filegroup type
57 isFilegroup := func(m blueprint.Module) bool {
58 return ctx.OtherModuleType(m) == "filegroup"
Jingwen Chen14a8bda2021-06-02 11:10:02 +000059 }
60
Liz Kammer57e2e7a2021-09-20 12:55:02 -040061 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
62 // macro.
63 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Liz Kammer12615db2021-09-28 09:19:17 -040064 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
65 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
66 labelStr := label.Label
67 if !exists || !isFilegroup(m) {
68 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000069 }
Liz Kammer12615db2021-09-28 09:19:17 -040070 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040071 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000072 }
73
Liz Kammer12615db2021-09-28 09:19:17 -040074 isProtoFilegroup := func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
75 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
76 labelStr := label.Label
77 if !exists || !isFilegroup(m) {
78 return labelStr, false
79 }
80 likelyProtos := strings.HasSuffix(labelStr, "proto") || strings.HasSuffix(labelStr, "protos")
81 return labelStr, likelyProtos
82 }
83
Liz Kammer57e2e7a2021-09-20 12:55:02 -040084 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
85 partitioned := bazel.PartitionLabelListAttribute(ctx, &srcs, bazel.LabelPartitions{
Liz Kammerae3994e2021-10-19 09:45:48 -040086 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
87 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040088 // C++ is the "catch-all" group, and comprises generated sources because we don't
89 // know the language of these sources until the genrule is executed.
Liz Kammer12615db2021-09-28 09:19:17 -040090 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
91 protoSrcPartition: bazel.LabelPartition{Extensions: []string{".proto"}, LabelMapper: isProtoFilegroup},
Liz Kammer57e2e7a2021-09-20 12:55:02 -040092 })
Jingwen Chen14a8bda2021-06-02 11:10:02 +000093
Liz Kammerae3994e2021-10-19 09:45:48 -040094 return partitioned
Jingwen Chen14a8bda2021-06-02 11:10:02 +000095}
96
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +000097// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +000098func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +000099 lib, ok := module.compiler.(*libraryDecorator)
100 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400101 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000102 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000103 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
104}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000105
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000106// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000107func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000108 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000109}
110
111// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000112func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000113 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400114}
115
Liz Kammer7a210ac2021-09-22 15:52:58 -0400116type depsPartition struct {
117 export bazel.LabelList
118 implementation bazel.LabelList
119}
120
Jingwen Chen55bc8202021-11-02 06:40:51 +0000121type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400122
Jingwen Chen55bc8202021-11-02 06:40:51 +0000123func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400124 if !exportsDeps {
125 return depsPartition{
126 implementation: fn(ctx, allDeps),
127 }
128 }
129
Liz Kammer7a210ac2021-09-22 15:52:58 -0400130 implementation, export := android.FilterList(allDeps, exportedDeps)
131
132 return depsPartition{
133 export: fn(ctx, export),
134 implementation: fn(ctx, implementation),
135 }
136}
137
Jingwen Chen55bc8202021-11-02 06:40:51 +0000138type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400139
Jingwen Chen55bc8202021-11-02 06:40:51 +0000140func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400141 if !exportsDeps {
142 return depsPartition{
143 implementation: fn(ctx, allDeps, excludes),
144 }
145 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400146 implementation, export := android.FilterList(allDeps, exportedDeps)
147
148 return depsPartition{
149 export: fn(ctx, export, excludes),
150 implementation: fn(ctx, implementation, excludes),
151 }
152}
153
Jingwen Chen55bc8202021-11-02 06:40:51 +0000154func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400155 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000156
Liz Kammer9abd62d2021-05-21 08:37:59 -0400157 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000158 attrs.Copts.SetSelectValue(axis, config, props.Cflags)
159 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400160 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400161
Liz Kammer2b8004b2021-10-04 13:55:44 -0400162 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400163 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
164 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
165
Liz Kammer2b8004b2021-10-04 13:55:44 -0400166 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400167 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
168 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
169
170 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Jingwen Chenbcf53042021-05-26 04:42:42 +0000171 }
Liz Kammer135bf552021-08-11 10:46:06 -0400172 // system_dynamic_deps distinguishes between nil/empty list behavior:
173 // nil -> use default values
174 // empty list -> no values specified
175 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000176
177 if isStatic {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400178 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StaticProperties{}) {
179 for config, props := range configToProps {
180 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
181 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000182 }
183 }
184 }
185 } else {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400186 for axis, configToProps := range module.GetArchVariantProperties(ctx, &SharedProperties{}) {
187 for config, props := range configToProps {
188 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
189 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000190 }
191 }
192 }
193 }
194
Liz Kammerae3994e2021-10-19 09:45:48 -0400195 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
196 attrs.Srcs = partitionedSrcs[cppSrcPartition]
197 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
198 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000199
Liz Kammer12615db2021-09-28 09:19:17 -0400200 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
201 // TODO(b/208815215): determine whether this is used and add support if necessary
202 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
203 }
204
Jingwen Chenbcf53042021-05-26 04:42:42 +0000205 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000206}
207
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400208// Convenience struct to hold all attributes parsed from prebuilt properties.
209type prebuiltAttributes struct {
210 Src bazel.LabelAttribute
211}
212
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000213// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Jingwen Chen55bc8202021-11-02 06:40:51 +0000214func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400215 var srcLabelAttribute bazel.LabelAttribute
216
Liz Kammer9abd62d2021-05-21 08:37:59 -0400217 for axis, configToProps := range module.GetArchVariantProperties(ctx, &prebuiltLinkerProperties{}) {
218 for config, props := range configToProps {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400219 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
220 if len(prebuiltLinkerProperties.Srcs) > 1 {
Liz Kammer9abd62d2021-05-21 08:37:59 -0400221 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most once source file for %s %s\n", axis, config)
222 continue
223 } else if len(prebuiltLinkerProperties.Srcs) == 0 {
224 continue
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400225 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400226 src := android.BazelLabelForModuleSrcSingle(ctx, prebuiltLinkerProperties.Srcs[0])
227 srcLabelAttribute.SetSelectValue(axis, config, src)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400228 }
229 }
230 }
231
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400232 return prebuiltAttributes{
233 Src: srcLabelAttribute,
234 }
235}
236
Liz Kammere6583482021-10-19 13:56:10 -0400237type baseAttributes struct {
238 compilerAttributes
239 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400240
241 protoDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400242}
243
Jingwen Chen107c0de2021-04-09 10:43:12 +0000244// Convenience struct to hold all attributes parsed from compiler properties.
245type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400246 // Options for all languages
247 copts bazel.StringListAttribute
248 // Assembly options and sources
249 asFlags bazel.StringListAttribute
250 asSrcs bazel.LabelListAttribute
251 // C options and sources
252 conlyFlags bazel.StringListAttribute
253 cSrcs bazel.LabelListAttribute
254 // C++ options and sources
255 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000256 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400257
Liz Kammere6583482021-10-19 13:56:10 -0400258 hdrs bazel.LabelListAttribute
259
Chris Parsons2c788392021-08-10 11:58:07 -0400260 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000261
262 // Not affected by arch variants
263 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500264 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000265 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400266
267 localIncludes bazel.StringListAttribute
268 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400269
Liz Kammer1263d9b2021-12-10 14:28:20 -0500270 includes BazelIncludes
271
Liz Kammer12615db2021-09-28 09:19:17 -0400272 protoSrcs bazel.LabelListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000273}
274
Liz Kammere6583482021-10-19 13:56:10 -0400275func parseCommandLineFlags(soongFlags []string) []string {
276 var result []string
277 for _, flag := range soongFlags {
278 // Soong's cflags can contain spaces, like `-include header.h`. For
279 // Bazel's copts, split them up to be compatible with the
280 // no_copts_tokenization feature.
281 result = append(result, strings.Split(flag, " ")...)
282 }
283 return result
284}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000285
Jingwen Chen55bc8202021-11-02 06:40:51 +0000286func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400287 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
288 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
289 if srcsList, ok := parseSrcs(ctx, props); ok {
290 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400291 }
292
Liz Kammere6583482021-10-19 13:56:10 -0400293 localIncludeDirs := props.Local_include_dirs
294 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500295 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400296 if includeBuildDirectory(props.Include_build_directory) {
297 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400298 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000299 }
300
Liz Kammere6583482021-10-19 13:56:10 -0400301 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
302 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
303
304 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags))
305 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags))
306 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags))
307 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags))
308 ca.rtti.SetSelectValue(axis, config, props.Rtti)
309}
310
Jingwen Chen55bc8202021-11-02 06:40:51 +0000311func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Liz Kammere6583482021-10-19 13:56:10 -0400312 stlPropsByArch := module.GetArchVariantProperties(ctx, &StlProperties{})
313 for _, configToProps := range stlPropsByArch {
314 for _, props := range configToProps {
315 if stlProps, ok := props.(*StlProperties); ok {
316 if stlProps.Stl == nil {
317 continue
Liz Kammer9abd62d2021-05-21 08:37:59 -0400318 }
Liz Kammere6583482021-10-19 13:56:10 -0400319 if ca.stl == nil {
320 ca.stl = stlProps.Stl
321 } else if ca.stl != stlProps.Stl {
322 ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
Liz Kammerae3994e2021-10-19 09:45:48 -0400323 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400324 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000325 }
326 }
Liz Kammere6583482021-10-19 13:56:10 -0400327}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000328
Jingwen Chen55bc8202021-11-02 06:40:51 +0000329func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400330 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400331 "Cflags": &ca.copts,
332 "Asflags": &ca.asFlags,
333 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400334 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400335 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000336 if productConfigProps, exists := productVariableProps[propName]; exists {
337 for productConfigProp, prop := range productConfigProps {
338 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400339 if !ok {
340 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
341 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000342 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
343 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400344 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400345 }
346 }
Liz Kammere6583482021-10-19 13:56:10 -0400347}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400348
Jingwen Chen55bc8202021-11-02 06:40:51 +0000349func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400350 ca.srcs.ResolveExcludes()
351 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
352
Liz Kammer12615db2021-09-28 09:19:17 -0400353 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
354
Liz Kammere6583482021-10-19 13:56:10 -0400355 for p, lla := range partitionedSrcs {
356 // if there are no sources, there is no need for headers
357 if lla.IsEmpty() {
358 continue
359 }
360 lla.Append(implementationHdrs)
361 partitionedSrcs[p] = lla
362 }
363
364 ca.srcs = partitionedSrcs[cppSrcPartition]
365 ca.cSrcs = partitionedSrcs[cSrcPartition]
366 ca.asSrcs = partitionedSrcs[asSrcPartition]
367
368 ca.absoluteIncludes.DeduplicateAxesFromBase()
369 ca.localIncludes.DeduplicateAxesFromBase()
370}
371
372// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000373func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400374 anySrcs := false
375 // Add srcs-like dependencies such as generated files.
376 // First create a LabelList containing these dependencies, then merge the values with srcs.
377 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
378 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
379 anySrcs = true
380 }
381
382 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
383 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
384 anySrcs = true
385 }
386 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
387}
388
Chris Parsons79bd2b72021-11-29 17:52:41 -0500389func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
390 var cStdVal, cppStdVal string
391 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
392 // Defaults are handled by the toolchain definition.
393 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammere6583482021-10-19 13:56:10 -0400394 if cpp_std != nil {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500395 cppStdVal = parseCppStd(cpp_std)
Liz Kammere6583482021-10-19 13:56:10 -0400396 } else if gnu_extensions != nil && !*gnu_extensions {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500397 cppStdVal = "c++17"
Liz Kammere6583482021-10-19 13:56:10 -0400398 }
Chris Parsons79bd2b72021-11-29 17:52:41 -0500399 if c_std != nil {
400 cStdVal = parseCStd(c_std)
401 } else if gnu_extensions != nil && !*gnu_extensions {
402 cStdVal = "c99"
403 }
404
405 cStdVal, cppStdVal = maybeReplaceGnuToC(gnu_extensions, cStdVal, cppStdVal)
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500406 var c_std_prop, cpp_std_prop *string
407 if cStdVal != "" {
408 c_std_prop = &cStdVal
409 }
410 if cppStdVal != "" {
411 cpp_std_prop = &cppStdVal
412 }
413
414 return c_std_prop, cpp_std_prop
Liz Kammere6583482021-10-19 13:56:10 -0400415}
416
Liz Kammer1263d9b2021-12-10 14:28:20 -0500417// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
418// is fully-qualified.
419// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
420func packageFromLabel(label string) (string, bool) {
421 split := strings.Split(label, ":")
422 if len(split) != 2 {
423 return "", false
424 }
425 if split[0] == "" {
426 return ".", false
427 }
428 // remove leading "//"
429 return split[0][2:], true
430}
431
432// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
433func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
434 for _, hdr := range labelList.Includes {
435 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
436 absolute = append(absolute, pkg)
437 } else if pkg != "" {
438 relative = append(relative, pkg)
439 }
440 }
441 return relative, absolute
442}
443
Liz Kammere6583482021-10-19 13:56:10 -0400444// bp2BuildParseCompilerProps returns copts, srcs and hdrs and other attributes.
Liz Kammer12615db2021-09-28 09:19:17 -0400445func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400446 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
447 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
448
449 var implementationHdrs bazel.LabelListAttribute
450
451 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
452 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
453 for axis, configMap := range cp {
454 if _, ok := axisToConfigs[axis]; !ok {
455 axisToConfigs[axis] = map[string]bool{}
456 }
457 for config, _ := range configMap {
458 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400459 }
460 }
461 }
Liz Kammere6583482021-10-19 13:56:10 -0400462 allAxesAndConfigs(archVariantCompilerProps)
463 allAxesAndConfigs(archVariantLinkerProps)
Chris Parsonsa967f252021-09-23 16:34:35 -0400464
Liz Kammere6583482021-10-19 13:56:10 -0400465 compilerAttrs := compilerAttributes{}
466 linkerAttrs := linkerAttributes{}
467
468 for axis, configs := range axisToConfigs {
469 for config, _ := range configs {
470 var allHdrs []string
471 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
472 allHdrs = baseCompilerProps.Generated_headers
473
474 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
475 }
476
477 var exportHdrs []string
478
479 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
480 exportHdrs = baseLinkerProps.Export_generated_headers
481
482 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
483 }
484 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
485 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
486 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500487
488 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
489 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
490 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
491
492 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
493 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
494 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
495 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
496 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
497 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
498 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Liz Kammere6583482021-10-19 13:56:10 -0400499 }
500 }
501
502 compilerAttrs.convertStlProps(ctx, module)
503 (&linkerAttrs).convertStripProps(ctx, module)
504
505 productVariableProps := android.ProductVariableProperties(ctx)
506
507 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
508 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
509
510 (&compilerAttrs).finalize(ctx, implementationHdrs)
511 (&linkerAttrs).finalize()
512
Liz Kammer12615db2021-09-28 09:19:17 -0400513 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
514
515 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
516 // which. This will add the newly generated proto library to the appropriate attribute and nothing
517 // to the other
518 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
519 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
520
Liz Kammere6583482021-10-19 13:56:10 -0400521 return baseAttributes{
522 compilerAttrs,
523 linkerAttrs,
Liz Kammer12615db2021-09-28 09:19:17 -0400524 protoDep.protoDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000525 }
526}
527
528// Convenience struct to hold all attributes parsed from linker properties.
529type linkerAttributes struct {
Liz Kammer12615db2021-09-28 09:19:17 -0400530 deps bazel.LabelListAttribute
531 implementationDeps bazel.LabelListAttribute
532 dynamicDeps bazel.LabelListAttribute
533 implementationDynamicDeps bazel.LabelListAttribute
534 wholeArchiveDeps bazel.LabelListAttribute
535 implementationWholeArchiveDeps bazel.LabelListAttribute
536 systemDynamicDeps bazel.LabelListAttribute
Liz Kammer7a210ac2021-09-22 15:52:58 -0400537
Jingwen Chen6ada5892021-09-17 11:38:09 +0000538 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000539 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500540 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000541 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400542 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000543 stripKeepSymbols bazel.BoolAttribute
544 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
545 stripKeepSymbolsList bazel.StringListAttribute
546 stripAll bazel.BoolAttribute
547 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400548 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400549}
550
Jingwen Chen55bc8202021-11-02 06:40:51 +0000551func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400552 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
553 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400554
Liz Kammere6583482021-10-19 13:56:10 -0400555 // Excludes to parallel Soong:
556 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
557 staticLibs := android.FirstUniqueStrings(props.Static_libs)
558 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400559
Liz Kammere6583482021-10-19 13:56:10 -0400560 headerLibs := android.FirstUniqueStrings(props.Header_libs)
561 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400562
Liz Kammere6583482021-10-19 13:56:10 -0400563 (&hDeps.export).Append(staticDeps.export)
564 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000565
Liz Kammere6583482021-10-19 13:56:10 -0400566 (&hDeps.implementation).Append(staticDeps.implementation)
567 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400568
Liz Kammere6583482021-10-19 13:56:10 -0400569 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
570 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
571
572 systemSharedLibs := props.System_shared_libs
573 // systemSharedLibs distinguishes between nil/empty list behavior:
574 // nil -> use default values
575 // empty list -> no values specified
576 if len(systemSharedLibs) > 0 {
577 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
578 }
579 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
580
581 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
582 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
583 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
584 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
585
586 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
587 axisFeatures = append(axisFeatures, "disable_pack_relocations")
588 }
589
590 if Bool(props.Allow_undefined_symbols) {
591 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
592 }
593
594 var linkerFlags []string
595 if len(props.Ldflags) > 0 {
596 linkerFlags = append(linkerFlags, props.Ldflags...)
597 // binaries remove static flag if -shared is in the linker flags
598 if isBinary && android.InList("-shared", linkerFlags) {
599 axisFeatures = append(axisFeatures, "-static_flag")
600 }
601 }
602 if props.Version_script != nil {
603 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
604 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
605 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
606 }
607 la.linkopts.SetSelectValue(axis, config, linkerFlags)
608 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
609
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500610 if axis == bazel.NoConfigAxis {
611 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
612 }
613
Liz Kammere6583482021-10-19 13:56:10 -0400614 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
615 if props.crt() != nil {
616 if axis == bazel.NoConfigAxis {
617 la.linkCrt.SetSelectValue(axis, config, props.crt())
618 } else if axis == bazel.ArchConfigurationAxis {
619 ctx.ModuleErrorf("nocrt is not supported for arch variants")
620 }
621 }
622
623 if axisFeatures != nil {
624 la.features.SetSelectValue(axis, config, axisFeatures)
625 }
626}
627
Jingwen Chen55bc8202021-11-02 06:40:51 +0000628func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000629 for axis, configToProps := range module.GetArchVariantProperties(ctx, &StripProperties{}) {
630 for config, props := range configToProps {
631 if stripProperties, ok := props.(*StripProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400632 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
633 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
634 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
635 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
636 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000637 }
638 }
639 }
Liz Kammere6583482021-10-19 13:56:10 -0400640}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000641
Jingwen Chen55bc8202021-11-02 06:40:51 +0000642func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000643
Liz Kammer47535c52021-06-02 16:02:22 -0400644 type productVarDep struct {
645 // the name of the corresponding excludes field, if one exists
646 excludesField string
647 // reference to the bazel attribute that should be set for the given product variable config
648 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400649
Jingwen Chen55bc8202021-11-02 06:40:51 +0000650 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -0400651 }
652
653 productVarToDepFields := map[string]productVarDep{
654 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +0000655 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
656 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
657 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -0400658 }
659
Liz Kammer47535c52021-06-02 16:02:22 -0400660 for name, dep := range productVarToDepFields {
661 props, exists := productVariableProps[name]
662 excludeProps, excludesExists := productVariableProps[dep.excludesField]
663 // if neither an include or excludes property exists, then skip it
664 if !exists && !excludesExists {
665 continue
666 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000667 // Collect all the configurations that an include or exclude property exists for.
668 // We want to iterate all configurations rather than either the include or exclude because, for a
669 // particular configuration, we may have either only an include or an exclude to handle.
670 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
671 for p := range props {
672 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400673 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000674 for p := range excludeProps {
675 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -0400676 }
677
Jingwen Chen25825ca2021-11-15 12:28:43 +0000678 for productConfigProp := range productConfigProps {
679 prop, includesExists := props[productConfigProp]
680 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -0400681 var includes, excludes []string
682 var ok bool
683 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +0000684 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400685 ctx.ModuleErrorf("Could not convert product variable %s property", name)
686 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000687 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -0400688 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
689 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400690
Jingwen Chen58ff6802021-11-17 12:14:41 +0000691 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +0000692 dep.attribute.SetSelectValue(
693 productConfigProp.ConfigurationAxis(),
694 productConfigProp.SelectKey(),
695 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
696 )
Liz Kammer47535c52021-06-02 16:02:22 -0400697 }
698 }
Liz Kammere6583482021-10-19 13:56:10 -0400699}
Liz Kammer47535c52021-06-02 16:02:22 -0400700
Liz Kammere6583482021-10-19 13:56:10 -0400701func (la *linkerAttributes) finalize() {
702 la.deps.ResolveExcludes()
703 la.implementationDeps.ResolveExcludes()
704 la.dynamicDeps.ResolveExcludes()
705 la.implementationDynamicDeps.ResolveExcludes()
706 la.wholeArchiveDeps.ResolveExcludes()
707 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Jingwen Chen91220d72021-03-24 02:18:33 -0400708}
709
Jingwen Chened9c17d2021-04-13 07:14:55 +0000710// Relativize a list of root-relative paths with respect to the module's
711// directory.
712//
713// include_dirs Soong prop are root-relative (b/183742505), but
714// local_include_dirs, export_include_dirs and export_system_include_dirs are
715// module dir relative. This function makes a list of paths entirely module dir
716// relative.
717//
718// For the `include` attribute, Bazel wants the paths to be relative to the
719// module.
720func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000721 var relativePaths []string
722 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +0000723 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
724 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
725 if err != nil {
726 panic(err)
727 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +0000728 relativePaths = append(relativePaths, relativePath)
729 }
730 return relativePaths
731}
732
Liz Kammer5fad5012021-09-09 14:08:21 -0400733// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
734// attributes.
735type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500736 AbsoluteIncludes bazel.StringListAttribute
737 Includes bazel.StringListAttribute
738 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -0400739}
740
Liz Kammer1263d9b2021-12-10 14:28:20 -0500741func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, existingIncludes BazelIncludes) BazelIncludes {
Jingwen Chen91220d72021-03-24 02:18:33 -0400742 libraryDecorator := module.linker.(*libraryDecorator)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500743 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, &existingIncludes)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400744}
Jingwen Chen91220d72021-03-24 02:18:33 -0400745
Liz Kammer5fad5012021-09-09 14:08:21 -0400746// Bp2buildParseExportedIncludesForPrebuiltLibrary returns a BazelIncludes with Bazel-ified values
747// to export includes from the underlying module's properties.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000748func Bp2BuildParseExportedIncludesForPrebuiltLibrary(ctx android.BazelConversionPathContext, module *Module) BazelIncludes {
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400749 prebuiltLibraryLinker := module.linker.(*prebuiltLibraryLinker)
750 libraryDecorator := prebuiltLibraryLinker.libraryDecorator
Liz Kammer1263d9b2021-12-10 14:28:20 -0500751 return bp2BuildParseExportedIncludesHelper(ctx, module, libraryDecorator, nil)
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400752}
753
754// bp2BuildParseExportedIncludes creates a string list attribute contains the
755// exported included directories of a module.
Liz Kammer1263d9b2021-12-10 14:28:20 -0500756func bp2BuildParseExportedIncludesHelper(ctx android.BazelConversionPathContext, module *Module, libraryDecorator *libraryDecorator, includes *BazelIncludes) BazelIncludes {
757 var exported BazelIncludes
758 if includes != nil {
759 exported = *includes
760 } else {
761 exported = BazelIncludes{}
762 }
Liz Kammer9abd62d2021-05-21 08:37:59 -0400763 for axis, configToProps := range module.GetArchVariantProperties(ctx, &FlagExporterProperties{}) {
764 for config, props := range configToProps {
765 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
Liz Kammer5fad5012021-09-09 14:08:21 -0400766 if len(flagExporterProperties.Export_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500767 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
Liz Kammer5fad5012021-09-09 14:08:21 -0400768 }
769 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
Liz Kammer1263d9b2021-12-10 14:28:20 -0500770 exported.SystemIncludes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.SystemIncludes.SelectValue(axis, config), flagExporterProperties.Export_system_include_dirs...)))
Rupert Shuttleworthc194ffb2021-05-19 06:49:02 -0400771 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400772 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400773 }
774 }
Liz Kammer1263d9b2021-12-10 14:28:20 -0500775 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -0400776 exported.Includes.DeduplicateAxesFromBase()
777 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -0400778
Liz Kammer5fad5012021-09-09 14:08:21 -0400779 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -0400780}
Chris Parsons953b3562021-09-20 15:14:39 -0400781
Jingwen Chen55bc8202021-11-02 06:40:51 +0000782func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400783 label := android.BazelModuleLabel(ctx, m)
784 if aModule, ok := m.(android.Module); ok {
785 if ctx.OtherModuleType(aModule) == "cc_library" && !android.GenerateCcLibraryStaticOnly(m.Name()) {
786 label += "_bp2build_cc_library_static"
787 }
788 }
789 return label
790}
791
Jingwen Chen55bc8202021-11-02 06:40:51 +0000792func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400793 // cc_library, at it's root name, propagates the shared library, which depends on the static
794 // library.
795 return android.BazelModuleLabel(ctx, m)
796}
797
Jingwen Chen55bc8202021-11-02 06:40:51 +0000798func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -0400799 label := bazelLabelForStaticModule(ctx, m)
800 if aModule, ok := m.(android.Module); ok {
801 if android.IsModulePrebuilt(aModule) {
802 label += "_alwayslink"
803 }
804 }
805 return label
806}
807
Jingwen Chen55bc8202021-11-02 06:40:51 +0000808func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400809 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
810}
811
Jingwen Chen55bc8202021-11-02 06:40:51 +0000812func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400813 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
814}
815
Jingwen Chen55bc8202021-11-02 06:40:51 +0000816func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400817 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
818}
819
Jingwen Chen55bc8202021-11-02 06:40:51 +0000820func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400821 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
822}
823
Jingwen Chen55bc8202021-11-02 06:40:51 +0000824func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400825 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
826}
827
Jingwen Chen55bc8202021-11-02 06:40:51 +0000828func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400829 // This is not elegant, but bp2build's shared library targets only propagate
830 // their header information as part of the normal C++ provider.
831 return bazelLabelForSharedDeps(ctx, modules)
832}
833
Jingwen Chen55bc8202021-11-02 06:40:51 +0000834func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400835 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
836}
Liz Kammer2b8004b2021-10-04 13:55:44 -0400837
838type binaryLinkerAttrs struct {
839 Linkshared *bool
840}
841
Jingwen Chen55bc8202021-11-02 06:40:51 +0000842func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400843 attrs := binaryLinkerAttrs{}
844 archVariantProps := m.GetArchVariantProperties(ctx, &BinaryLinkerProperties{})
845 for axis, configToProps := range archVariantProps {
846 for _, p := range configToProps {
847 props := p.(*BinaryLinkerProperties)
848 staticExecutable := props.Static_executable
849 if axis == bazel.NoConfigAxis {
850 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
851 attrs.Linkshared = &linkBinaryShared
852 }
853 } else if staticExecutable != nil {
854 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
855 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
856 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
857 }
858 }
859 }
860
861 return attrs
862}