blob: f4a2b5441dd0b4e787e509c5286698dffde516ab [file] [log] [blame]
Ivan Lozanoffee3342019-08-27 12:03:00 -07001// Copyright 2019 The Android Open Source Project
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.
14
15package rust
16
17import (
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +020018 "fmt"
Ivan Lozanoad8b18b2019-10-31 19:38:29 -070019 "regexp"
20 "strings"
21
Ivan Lozanoffee3342019-08-27 12:03:00 -070022 "android/soong/android"
Vinh Tranbcb5f572023-08-24 11:10:01 -040023 "android/soong/bazel"
Colin Cross0de8a1e2020-09-18 14:15:30 -070024 "android/soong/cc"
Vinh Tranbcb5f572023-08-24 11:10:01 -040025
26 "github.com/google/blueprint/proptools"
Ivan Lozanoffee3342019-08-27 12:03:00 -070027)
28
Ivan Lozano2b081132020-09-08 12:46:52 -040029var (
Ivan Lozano4df02572023-06-15 14:21:09 -040030 RlibStdlibSuffix = ".rlib-std"
Ivan Lozano2b081132020-09-08 12:46:52 -040031)
32
Ivan Lozanoffee3342019-08-27 12:03:00 -070033func init() {
34 android.RegisterModuleType("rust_library", RustLibraryFactory)
35 android.RegisterModuleType("rust_library_dylib", RustLibraryDylibFactory)
36 android.RegisterModuleType("rust_library_rlib", RustLibraryRlibFactory)
37 android.RegisterModuleType("rust_library_host", RustLibraryHostFactory)
38 android.RegisterModuleType("rust_library_host_dylib", RustLibraryDylibHostFactory)
39 android.RegisterModuleType("rust_library_host_rlib", RustLibraryRlibHostFactory)
Matthew Maurer2ae05132020-06-23 14:28:53 -070040 android.RegisterModuleType("rust_ffi", RustFFIFactory)
41 android.RegisterModuleType("rust_ffi_shared", RustFFISharedFactory)
42 android.RegisterModuleType("rust_ffi_static", RustFFIStaticFactory)
43 android.RegisterModuleType("rust_ffi_host", RustFFIHostFactory)
44 android.RegisterModuleType("rust_ffi_host_shared", RustFFISharedHostFactory)
45 android.RegisterModuleType("rust_ffi_host_static", RustFFIStaticHostFactory)
Ivan Lozanoffee3342019-08-27 12:03:00 -070046}
47
48type VariantLibraryProperties struct {
Matthew Maurerc761eec2020-06-25 00:47:46 -070049 Enabled *bool `android:"arch_variant"`
50 Srcs []string `android:"path,arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -070051}
52
53type LibraryCompilerProperties struct {
Ivan Lozano52767be2019-10-18 14:49:46 -070054 Rlib VariantLibraryProperties `android:"arch_variant"`
55 Dylib VariantLibraryProperties `android:"arch_variant"`
56 Shared VariantLibraryProperties `android:"arch_variant"`
57 Static VariantLibraryProperties `android:"arch_variant"`
Ivan Lozanoffee3342019-08-27 12:03:00 -070058
Ivan Lozano52767be2019-10-18 14:49:46 -070059 // path to include directories to pass to cc_* modules, only relevant for static/shared variants.
60 Include_dirs []string `android:"path,arch_variant"`
Ivan Lozano2b081132020-09-08 12:46:52 -040061
62 // Whether this library is part of the Rust toolchain sysroot.
63 Sysroot *bool
Ivan Lozanoffee3342019-08-27 12:03:00 -070064}
65
66type LibraryMutatedProperties struct {
Ivan Lozanoffee3342019-08-27 12:03:00 -070067 // Build a dylib variant
68 BuildDylib bool `blueprint:"mutated"`
69 // Build an rlib variant
70 BuildRlib bool `blueprint:"mutated"`
Ivan Lozano52767be2019-10-18 14:49:46 -070071 // Build a shared library variant
72 BuildShared bool `blueprint:"mutated"`
73 // Build a static library variant
74 BuildStatic bool `blueprint:"mutated"`
Ivan Lozanoffee3342019-08-27 12:03:00 -070075
76 // This variant is a dylib
77 VariantIsDylib bool `blueprint:"mutated"`
78 // This variant is an rlib
79 VariantIsRlib bool `blueprint:"mutated"`
Ivan Lozano52767be2019-10-18 14:49:46 -070080 // This variant is a shared library
81 VariantIsShared bool `blueprint:"mutated"`
82 // This variant is a static library
83 VariantIsStatic bool `blueprint:"mutated"`
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +020084 // This variant is a source provider
85 VariantIsSource bool `blueprint:"mutated"`
Ivan Lozano26ecd6c2020-07-31 13:40:31 -040086
87 // This variant is disabled and should not be compiled
88 // (used for SourceProvider variants that produce only source)
89 VariantIsDisabled bool `blueprint:"mutated"`
Ivan Lozano2b081132020-09-08 12:46:52 -040090
91 // Whether this library variant should be link libstd via rlibs
92 VariantIsStaticStd bool `blueprint:"mutated"`
Ivan Lozanoffee3342019-08-27 12:03:00 -070093}
94
95type libraryDecorator struct {
96 *baseCompiler
Matthew Maurerbb3add12020-06-25 09:34:12 -070097 *flagExporter
Thiébaud Weksteenfabaff62020-08-27 13:48:36 +020098 stripper Stripper
Ivan Lozanoffee3342019-08-27 12:03:00 -070099
Ivan Lozano8a23fa42020-06-16 10:26:57 -0400100 Properties LibraryCompilerProperties
101 MutatedProperties LibraryMutatedProperties
102 includeDirs android.Paths
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400103 sourceProvider SourceProvider
Ivan Lozano1921e802021-05-20 13:39:16 -0400104
105 collectedSnapshotHeaders android.Paths
Ivan Lozano7b0781d2021-11-03 15:30:18 -0400106
107 // table-of-contents file for cdylib crates to optimize out relinking when possible
108 tocFile android.OptionalPath
Ivan Lozanoffee3342019-08-27 12:03:00 -0700109}
110
111type libraryInterface interface {
112 rlib() bool
113 dylib() bool
Ivan Lozano52767be2019-10-18 14:49:46 -0700114 static() bool
115 shared() bool
Ivan Lozano2b081132020-09-08 12:46:52 -0400116 sysroot() bool
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200117 source() bool
Ivan Lozanoffee3342019-08-27 12:03:00 -0700118
119 // Returns true if the build options for the module have selected a particular build type
120 buildRlib() bool
121 buildDylib() bool
Ivan Lozano52767be2019-10-18 14:49:46 -0700122 buildShared() bool
123 buildStatic() bool
Ivan Lozanoffee3342019-08-27 12:03:00 -0700124
125 // Sets a particular variant type
126 setRlib()
127 setDylib()
Ivan Lozano52767be2019-10-18 14:49:46 -0700128 setShared()
129 setStatic()
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200130 setSource()
Ivan Lozano52767be2019-10-18 14:49:46 -0700131
Ivan Lozano3149e6e2021-06-01 15:09:53 -0400132 // libstd linkage functions
133 rlibStd() bool
Ivan Lozano2b081132020-09-08 12:46:52 -0400134 setRlibStd()
135 setDylibStd()
136
Ivan Lozano52767be2019-10-18 14:49:46 -0700137 // Build a specific library variant
Matthew Maurer2ae05132020-06-23 14:28:53 -0700138 BuildOnlyFFI()
139 BuildOnlyRust()
Ivan Lozano52767be2019-10-18 14:49:46 -0700140 BuildOnlyRlib()
141 BuildOnlyDylib()
142 BuildOnlyStatic()
143 BuildOnlyShared()
Ivan Lozano7b0781d2021-11-03 15:30:18 -0400144
145 toc() android.OptionalPath
Ivan Lozanoffee3342019-08-27 12:03:00 -0700146}
147
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400148func (library *libraryDecorator) nativeCoverage() bool {
149 return true
150}
151
Ivan Lozano7b0781d2021-11-03 15:30:18 -0400152func (library *libraryDecorator) toc() android.OptionalPath {
153 return library.tocFile
154}
155
Ivan Lozanoffee3342019-08-27 12:03:00 -0700156func (library *libraryDecorator) rlib() bool {
157 return library.MutatedProperties.VariantIsRlib
158}
159
Ivan Lozano2b081132020-09-08 12:46:52 -0400160func (library *libraryDecorator) sysroot() bool {
161 return Bool(library.Properties.Sysroot)
162}
163
Ivan Lozanoffee3342019-08-27 12:03:00 -0700164func (library *libraryDecorator) dylib() bool {
165 return library.MutatedProperties.VariantIsDylib
166}
167
Ivan Lozano52767be2019-10-18 14:49:46 -0700168func (library *libraryDecorator) shared() bool {
169 return library.MutatedProperties.VariantIsShared
170}
171
172func (library *libraryDecorator) static() bool {
173 return library.MutatedProperties.VariantIsStatic
174}
175
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200176func (library *libraryDecorator) source() bool {
177 return library.MutatedProperties.VariantIsSource
178}
179
Ivan Lozanoffee3342019-08-27 12:03:00 -0700180func (library *libraryDecorator) buildRlib() bool {
181 return library.MutatedProperties.BuildRlib && BoolDefault(library.Properties.Rlib.Enabled, true)
182}
183
184func (library *libraryDecorator) buildDylib() bool {
185 return library.MutatedProperties.BuildDylib && BoolDefault(library.Properties.Dylib.Enabled, true)
186}
187
Ivan Lozano52767be2019-10-18 14:49:46 -0700188func (library *libraryDecorator) buildShared() bool {
189 return library.MutatedProperties.BuildShared && BoolDefault(library.Properties.Shared.Enabled, true)
190}
191
192func (library *libraryDecorator) buildStatic() bool {
193 return library.MutatedProperties.BuildStatic && BoolDefault(library.Properties.Static.Enabled, true)
194}
195
Ivan Lozanoffee3342019-08-27 12:03:00 -0700196func (library *libraryDecorator) setRlib() {
197 library.MutatedProperties.VariantIsRlib = true
198 library.MutatedProperties.VariantIsDylib = false
Ivan Lozano52767be2019-10-18 14:49:46 -0700199 library.MutatedProperties.VariantIsStatic = false
200 library.MutatedProperties.VariantIsShared = false
Ivan Lozanoffee3342019-08-27 12:03:00 -0700201}
202
203func (library *libraryDecorator) setDylib() {
204 library.MutatedProperties.VariantIsRlib = false
205 library.MutatedProperties.VariantIsDylib = true
Ivan Lozano52767be2019-10-18 14:49:46 -0700206 library.MutatedProperties.VariantIsStatic = false
207 library.MutatedProperties.VariantIsShared = false
208}
209
Ivan Lozano3149e6e2021-06-01 15:09:53 -0400210func (library *libraryDecorator) rlibStd() bool {
211 return library.MutatedProperties.VariantIsStaticStd
212}
213
Ivan Lozano2b081132020-09-08 12:46:52 -0400214func (library *libraryDecorator) setRlibStd() {
215 library.MutatedProperties.VariantIsStaticStd = true
216}
217
218func (library *libraryDecorator) setDylibStd() {
219 library.MutatedProperties.VariantIsStaticStd = false
220}
221
Ivan Lozano52767be2019-10-18 14:49:46 -0700222func (library *libraryDecorator) setShared() {
223 library.MutatedProperties.VariantIsStatic = false
224 library.MutatedProperties.VariantIsShared = true
225 library.MutatedProperties.VariantIsRlib = false
226 library.MutatedProperties.VariantIsDylib = false
227}
228
229func (library *libraryDecorator) setStatic() {
230 library.MutatedProperties.VariantIsStatic = true
231 library.MutatedProperties.VariantIsShared = false
232 library.MutatedProperties.VariantIsRlib = false
233 library.MutatedProperties.VariantIsDylib = false
Ivan Lozanoffee3342019-08-27 12:03:00 -0700234}
235
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200236func (library *libraryDecorator) setSource() {
237 library.MutatedProperties.VariantIsSource = true
238}
239
Liz Kammer356f7d42021-01-26 09:18:53 -0500240func (library *libraryDecorator) autoDep(ctx android.BottomUpMutatorContext) autoDep {
Ivan Lozanoadd122a2023-07-13 11:01:41 -0400241 if library.preferRlib() {
Ivan Lozanoea086132020-12-08 14:43:00 -0500242 return rlibAutoDep
243 } else if library.rlib() || library.static() {
Matthew Maurer0f003b12020-06-29 14:34:06 -0700244 return rlibAutoDep
245 } else if library.dylib() || library.shared() {
246 return dylibAutoDep
247 } else {
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200248 panic(fmt.Errorf("autoDep called on library %q that has no enabled variants.", ctx.ModuleName()))
Matthew Maurer0f003b12020-06-29 14:34:06 -0700249 }
250}
251
Ivan Lozanoea086132020-12-08 14:43:00 -0500252func (library *libraryDecorator) stdLinkage(ctx *depsContext) RustLinkage {
Ivan Lozanoadd122a2023-07-13 11:01:41 -0400253 if library.static() || library.MutatedProperties.VariantIsStaticStd {
Ivan Lozanoea086132020-12-08 14:43:00 -0500254 return RlibLinkage
255 } else if library.baseCompiler.preferRlib() {
256 return RlibLinkage
257 }
258 return DefaultLinkage
259}
260
Ivan Lozanoffee3342019-08-27 12:03:00 -0700261var _ compiler = (*libraryDecorator)(nil)
Ivan Lozano52767be2019-10-18 14:49:46 -0700262var _ libraryInterface = (*libraryDecorator)(nil)
Matthew Maurerbb3add12020-06-25 09:34:12 -0700263var _ exportedFlagsProducer = (*libraryDecorator)(nil)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700264
Martin Geisler67ec0542022-11-18 12:08:55 +0100265// rust_library produces all Rust variants (rust_library_dylib and
266// rust_library_rlib).
Ivan Lozanoffee3342019-08-27 12:03:00 -0700267func RustLibraryFactory() android.Module {
Matthew Maurer2ae05132020-06-23 14:28:53 -0700268 module, library := NewRustLibrary(android.HostAndDeviceSupported)
269 library.BuildOnlyRust()
270 return module.Init()
271}
272
Martin Geisler67ec0542022-11-18 12:08:55 +0100273// rust_ffi produces all FFI variants (rust_ffi_shared and
274// rust_ffi_static).
Matthew Maurer2ae05132020-06-23 14:28:53 -0700275func RustFFIFactory() android.Module {
276 module, library := NewRustLibrary(android.HostAndDeviceSupported)
277 library.BuildOnlyFFI()
Ivan Lozanoffee3342019-08-27 12:03:00 -0700278 return module.Init()
279}
280
Martin Geisler67ec0542022-11-18 12:08:55 +0100281// rust_library_dylib produces a Rust dylib (Rust crate type "dylib").
Ivan Lozanoffee3342019-08-27 12:03:00 -0700282func RustLibraryDylibFactory() android.Module {
283 module, library := NewRustLibrary(android.HostAndDeviceSupported)
284 library.BuildOnlyDylib()
285 return module.Init()
286}
287
Martin Geisler67ec0542022-11-18 12:08:55 +0100288// rust_library_rlib produces an rlib (Rust crate type "rlib").
Ivan Lozanoffee3342019-08-27 12:03:00 -0700289func RustLibraryRlibFactory() android.Module {
290 module, library := NewRustLibrary(android.HostAndDeviceSupported)
291 library.BuildOnlyRlib()
292 return module.Init()
293}
294
Martin Geisler67ec0542022-11-18 12:08:55 +0100295// rust_ffi_shared produces a shared library (Rust crate type
296// "cdylib").
Matthew Maurer2ae05132020-06-23 14:28:53 -0700297func RustFFISharedFactory() android.Module {
Ivan Lozano52767be2019-10-18 14:49:46 -0700298 module, library := NewRustLibrary(android.HostAndDeviceSupported)
299 library.BuildOnlyShared()
300 return module.Init()
301}
302
Martin Geisler67ec0542022-11-18 12:08:55 +0100303// rust_ffi_static produces a static library (Rust crate type
304// "staticlib").
Matthew Maurer2ae05132020-06-23 14:28:53 -0700305func RustFFIStaticFactory() android.Module {
Ivan Lozano52767be2019-10-18 14:49:46 -0700306 module, library := NewRustLibrary(android.HostAndDeviceSupported)
307 library.BuildOnlyStatic()
308 return module.Init()
309}
310
Martin Geisler67ec0542022-11-18 12:08:55 +0100311// rust_library_host produces all Rust variants for the host
312// (rust_library_dylib_host and rust_library_rlib_host).
Ivan Lozanoffee3342019-08-27 12:03:00 -0700313func RustLibraryHostFactory() android.Module {
Matthew Maurer2ae05132020-06-23 14:28:53 -0700314 module, library := NewRustLibrary(android.HostSupported)
315 library.BuildOnlyRust()
316 return module.Init()
317}
318
Martin Geisler67ec0542022-11-18 12:08:55 +0100319// rust_ffi_host produces all FFI variants for the host
320// (rust_ffi_static_host and rust_ffi_shared_host).
Matthew Maurer2ae05132020-06-23 14:28:53 -0700321func RustFFIHostFactory() android.Module {
322 module, library := NewRustLibrary(android.HostSupported)
323 library.BuildOnlyFFI()
Ivan Lozanoffee3342019-08-27 12:03:00 -0700324 return module.Init()
325}
326
Martin Geisler67ec0542022-11-18 12:08:55 +0100327// rust_library_dylib_host produces a dylib for the host (Rust crate
328// type "dylib").
Ivan Lozanoffee3342019-08-27 12:03:00 -0700329func RustLibraryDylibHostFactory() android.Module {
330 module, library := NewRustLibrary(android.HostSupported)
331 library.BuildOnlyDylib()
332 return module.Init()
333}
334
Martin Geisler67ec0542022-11-18 12:08:55 +0100335// rust_library_rlib_host produces an rlib for the host (Rust crate
336// type "rlib").
Ivan Lozanoffee3342019-08-27 12:03:00 -0700337func RustLibraryRlibHostFactory() android.Module {
338 module, library := NewRustLibrary(android.HostSupported)
339 library.BuildOnlyRlib()
340 return module.Init()
341}
342
Martin Geisler67ec0542022-11-18 12:08:55 +0100343// rust_ffi_static_host produces a static library for the host (Rust
344// crate type "staticlib").
Matthew Maurer2ae05132020-06-23 14:28:53 -0700345func RustFFIStaticHostFactory() android.Module {
Ivan Lozano52767be2019-10-18 14:49:46 -0700346 module, library := NewRustLibrary(android.HostSupported)
347 library.BuildOnlyStatic()
348 return module.Init()
349}
350
Martin Geisler67ec0542022-11-18 12:08:55 +0100351// rust_ffi_shared_host produces an shared library for the host (Rust
352// crate type "cdylib").
Matthew Maurer2ae05132020-06-23 14:28:53 -0700353func RustFFISharedHostFactory() android.Module {
Ivan Lozano52767be2019-10-18 14:49:46 -0700354 module, library := NewRustLibrary(android.HostSupported)
355 library.BuildOnlyShared()
356 return module.Init()
357}
358
Matthew Maurer2ae05132020-06-23 14:28:53 -0700359func (library *libraryDecorator) BuildOnlyFFI() {
360 library.MutatedProperties.BuildDylib = false
361 library.MutatedProperties.BuildRlib = false
362 library.MutatedProperties.BuildShared = true
363 library.MutatedProperties.BuildStatic = true
364}
365
366func (library *libraryDecorator) BuildOnlyRust() {
367 library.MutatedProperties.BuildDylib = true
368 library.MutatedProperties.BuildRlib = true
369 library.MutatedProperties.BuildShared = false
370 library.MutatedProperties.BuildStatic = false
371}
372
Ivan Lozanoffee3342019-08-27 12:03:00 -0700373func (library *libraryDecorator) BuildOnlyDylib() {
Matthew Maurer2ae05132020-06-23 14:28:53 -0700374 library.MutatedProperties.BuildDylib = true
Ivan Lozanoffee3342019-08-27 12:03:00 -0700375 library.MutatedProperties.BuildRlib = false
Ivan Lozano52767be2019-10-18 14:49:46 -0700376 library.MutatedProperties.BuildShared = false
377 library.MutatedProperties.BuildStatic = false
Ivan Lozanoffee3342019-08-27 12:03:00 -0700378}
379
380func (library *libraryDecorator) BuildOnlyRlib() {
381 library.MutatedProperties.BuildDylib = false
Matthew Maurer2ae05132020-06-23 14:28:53 -0700382 library.MutatedProperties.BuildRlib = true
Ivan Lozano52767be2019-10-18 14:49:46 -0700383 library.MutatedProperties.BuildShared = false
384 library.MutatedProperties.BuildStatic = false
385}
386
387func (library *libraryDecorator) BuildOnlyStatic() {
Ivan Lozano52767be2019-10-18 14:49:46 -0700388 library.MutatedProperties.BuildRlib = false
389 library.MutatedProperties.BuildDylib = false
Matthew Maurer2ae05132020-06-23 14:28:53 -0700390 library.MutatedProperties.BuildShared = false
391 library.MutatedProperties.BuildStatic = true
Ivan Lozano52767be2019-10-18 14:49:46 -0700392}
393
394func (library *libraryDecorator) BuildOnlyShared() {
Ivan Lozano52767be2019-10-18 14:49:46 -0700395 library.MutatedProperties.BuildRlib = false
396 library.MutatedProperties.BuildDylib = false
Matthew Maurer2ae05132020-06-23 14:28:53 -0700397 library.MutatedProperties.BuildStatic = false
398 library.MutatedProperties.BuildShared = true
Ivan Lozanoffee3342019-08-27 12:03:00 -0700399}
400
401func NewRustLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) {
Ivan Lozano9d1df102020-04-28 10:10:23 -0400402 module := newModule(hod, android.MultilibBoth)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700403
Vinh Tranbcb5f572023-08-24 11:10:01 -0400404 android.InitBazelModule(module)
405
Ivan Lozanoffee3342019-08-27 12:03:00 -0700406 library := &libraryDecorator{
407 MutatedProperties: LibraryMutatedProperties{
Matthew Maurer2ae05132020-06-23 14:28:53 -0700408 BuildDylib: false,
409 BuildRlib: false,
410 BuildShared: false,
411 BuildStatic: false,
Ivan Lozanoffee3342019-08-27 12:03:00 -0700412 },
Chih-Hung Hsieh9a4a7ba2019-12-12 19:36:05 -0800413 baseCompiler: NewBaseCompiler("lib", "lib64", InstallInSystem),
Matthew Maurerbb3add12020-06-25 09:34:12 -0700414 flagExporter: NewFlagExporter(),
Ivan Lozanoffee3342019-08-27 12:03:00 -0700415 }
416
417 module.compiler = library
418
419 return module, library
420}
421
422func (library *libraryDecorator) compilerProps() []interface{} {
423 return append(library.baseCompiler.compilerProps(),
424 &library.Properties,
Thiébaud Weksteenfabaff62020-08-27 13:48:36 +0200425 &library.MutatedProperties,
426 &library.stripper.StripProperties)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700427}
428
Ivan Lozanof1c84332019-09-20 11:00:37 -0700429func (library *libraryDecorator) compilerDeps(ctx DepsContext, deps Deps) Deps {
430 deps = library.baseCompiler.compilerDeps(ctx, deps)
431
Colin Crosse32f0932022-01-23 20:48:36 -0800432 if library.dylib() || library.shared() {
433 if ctx.toolchain().Bionic() {
434 deps = bionicDeps(ctx, deps, false)
435 deps.CrtBegin = []string{"crtbegin_so"}
436 deps.CrtEnd = []string{"crtend_so"}
437 } else if ctx.Os() == android.LinuxMusl {
438 deps = muslDeps(ctx, deps, false)
439 deps.CrtBegin = []string{"libc_musl_crtbegin_so"}
440 deps.CrtEnd = []string{"libc_musl_crtend_so"}
441 }
Ivan Lozanof1c84332019-09-20 11:00:37 -0700442 }
443
444 return deps
445}
Ivan Lozanobec05ea2020-06-09 08:27:49 -0400446
447func (library *libraryDecorator) sharedLibFilename(ctx ModuleContext) string {
448 return library.getStem(ctx) + ctx.toolchain().SharedLibSuffix()
449}
450
Ivan Lozano67eada32021-09-23 11:50:33 -0400451func (library *libraryDecorator) cfgFlags(ctx ModuleContext, flags Flags) Flags {
452 flags = library.baseCompiler.cfgFlags(ctx, flags)
Stephen Crane0dbfc562021-07-07 19:05:02 -0700453 if library.dylib() {
454 // We need to add a dependency on std in order to link crates as dylibs.
455 // The hack to add this dependency is guarded by the following cfg so
456 // that we don't force a dependency when it isn't needed.
457 library.baseCompiler.Properties.Cfgs = append(library.baseCompiler.Properties.Cfgs, "android_dylib")
458 }
Ivan Lozano67eada32021-09-23 11:50:33 -0400459
460 flags.RustFlags = append(flags.RustFlags, library.baseCompiler.cfgsToFlags()...)
461 flags.RustdocFlags = append(flags.RustdocFlags, library.baseCompiler.cfgsToFlags()...)
462
463 return flags
464}
465
466func (library *libraryDecorator) compilerFlags(ctx ModuleContext, flags Flags) Flags {
Ivan Lozanoe0833b12019-11-06 19:15:49 -0800467 flags = library.baseCompiler.compilerFlags(ctx, flags)
Ivan Lozano67eada32021-09-23 11:50:33 -0400468
469 flags.RustFlags = append(flags.RustFlags, "-C metadata="+ctx.ModuleName())
Ivan Lozanoe0833b12019-11-06 19:15:49 -0800470 if library.shared() || library.static() {
471 library.includeDirs = append(library.includeDirs, android.PathsForModuleSrc(ctx, library.Properties.Include_dirs)...)
472 }
Ivan Lozanobec05ea2020-06-09 08:27:49 -0400473 if library.shared() {
A. Cody Schuffelenc183e3a2023-08-14 21:09:47 -0700474 if ctx.Darwin() {
475 flags.LinkFlags = append(
476 flags.LinkFlags,
477 "-dynamic_lib",
478 "-install_name @rpath/"+library.sharedLibFilename(ctx),
479 )
480 } else {
481 flags.LinkFlags = append(flags.LinkFlags, "-Wl,-soname="+library.sharedLibFilename(ctx))
482 }
Ivan Lozanobec05ea2020-06-09 08:27:49 -0400483 }
484
Ivan Lozanoe0833b12019-11-06 19:15:49 -0800485 return flags
486}
Ivan Lozanof1c84332019-09-20 11:00:37 -0700487
Sasha Smundaka76acba2022-04-18 20:12:56 -0700488func (library *libraryDecorator) compile(ctx ModuleContext, flags Flags, deps PathDeps) buildOutput {
489 var outputFile android.ModuleOutPath
490 var ret buildOutput
Thiébaud Weksteenfabaff62020-08-27 13:48:36 +0200491 var fileName string
Sam Delmerico60375c42023-09-11 17:18:08 +0000492 crateRootPath := library.crateRootPath(ctx, deps)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700493
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400494 if library.sourceProvider != nil {
Ivan Lozano9d74a522020-12-01 09:25:22 -0500495 deps.srcProviderFiles = append(deps.srcProviderFiles, library.sourceProvider.Srcs()...)
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400496 }
Ivan Lozanoffee3342019-08-27 12:03:00 -0700497
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400498 // Calculate output filename
499 if library.rlib() {
500 fileName = library.getStem(ctx) + ctx.toolchain().RlibSuffix()
501 outputFile = android.PathForModuleOut(ctx, fileName)
Sasha Smundaka76acba2022-04-18 20:12:56 -0700502 ret.outputFile = outputFile
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400503 } else if library.dylib() {
504 fileName = library.getStem(ctx) + ctx.toolchain().DylibSuffix()
505 outputFile = android.PathForModuleOut(ctx, fileName)
Sasha Smundaka76acba2022-04-18 20:12:56 -0700506 ret.outputFile = outputFile
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400507 } else if library.static() {
508 fileName = library.getStem(ctx) + ctx.toolchain().StaticLibSuffix()
509 outputFile = android.PathForModuleOut(ctx, fileName)
Sasha Smundaka76acba2022-04-18 20:12:56 -0700510 ret.outputFile = outputFile
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400511 } else if library.shared() {
512 fileName = library.sharedLibFilename(ctx)
513 outputFile = android.PathForModuleOut(ctx, fileName)
Sasha Smundaka76acba2022-04-18 20:12:56 -0700514 ret.outputFile = outputFile
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400515 }
516
517 if !library.rlib() && !library.static() && library.stripper.NeedsStrip(ctx) {
518 strippedOutputFile := outputFile
519 outputFile = android.PathForModuleOut(ctx, "unstripped", fileName)
520 library.stripper.StripExecutableOrSharedLib(ctx, outputFile, strippedOutputFile)
521
522 library.baseCompiler.strippedOutputFile = android.OptionalPathForPath(strippedOutputFile)
523 }
524 library.baseCompiler.unstrippedOutputFile = outputFile
525
Ivan Lozanoffee3342019-08-27 12:03:00 -0700526 flags.RustFlags = append(flags.RustFlags, deps.depFlags...)
Ivan Lozano3dfa12d2021-02-04 11:29:41 -0500527 flags.LinkFlags = append(flags.LinkFlags, deps.depLinkFlags...)
Wen-yi Chu41326c12023-09-22 03:58:59 +0000528 flags.LinkFlags = append(flags.LinkFlags, deps.linkObjects.Strings()...)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700529
Matthew Maurer46c46cc2020-01-13 16:34:34 -0800530 if library.dylib() {
Ivan Lozano52767be2019-10-18 14:49:46 -0700531 // We need prefer-dynamic for now to avoid linking in the static stdlib. See:
532 // https://github.com/rust-lang/rust/issues/19680
533 // https://github.com/rust-lang/rust/issues/34909
534 flags.RustFlags = append(flags.RustFlags, "-C prefer-dynamic")
535 }
536
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400537 // Call the appropriate builder for this library type
Ivan Lozanoffee3342019-08-27 12:03:00 -0700538 if library.rlib() {
Wen-yi Chu41326c12023-09-22 03:58:59 +0000539 ret.kytheFile = TransformSrctoRlib(ctx, crateRootPath, deps, flags, outputFile).kytheFile
Ivan Lozanoffee3342019-08-27 12:03:00 -0700540 } else if library.dylib() {
Wen-yi Chu41326c12023-09-22 03:58:59 +0000541 ret.kytheFile = TransformSrctoDylib(ctx, crateRootPath, deps, flags, outputFile).kytheFile
Ivan Lozano52767be2019-10-18 14:49:46 -0700542 } else if library.static() {
Wen-yi Chu41326c12023-09-22 03:58:59 +0000543 ret.kytheFile = TransformSrctoStatic(ctx, crateRootPath, deps, flags, outputFile).kytheFile
Ivan Lozano52767be2019-10-18 14:49:46 -0700544 } else if library.shared() {
Wen-yi Chu41326c12023-09-22 03:58:59 +0000545 ret.kytheFile = TransformSrctoShared(ctx, crateRootPath, deps, flags, outputFile).kytheFile
Ivan Lozanoffee3342019-08-27 12:03:00 -0700546 }
547
Ivan Lozano52767be2019-10-18 14:49:46 -0700548 if library.rlib() || library.dylib() {
Colin Cross0de8a1e2020-09-18 14:15:30 -0700549 library.flagExporter.exportLinkDirs(deps.linkDirs...)
Colin Cross0de8a1e2020-09-18 14:15:30 -0700550 library.flagExporter.exportLinkObjects(deps.linkObjects...)
Peter Collingbournee7c71c32023-03-31 20:21:19 -0700551 library.flagExporter.exportLibDeps(deps.LibDeps...)
Ivan Lozano52767be2019-10-18 14:49:46 -0700552 }
Ivan Lozanoffee3342019-08-27 12:03:00 -0700553
Colin Cross0de8a1e2020-09-18 14:15:30 -0700554 if library.static() || library.shared() {
555 ctx.SetProvider(cc.FlagExporterInfoProvider, cc.FlagExporterInfo{
556 IncludeDirs: library.includeDirs,
557 })
558 }
559
560 if library.shared() {
Ivan Lozano7b0781d2021-11-03 15:30:18 -0400561 // Optimize out relinking against shared libraries whose interface hasn't changed by
562 // depending on a table of contents file instead of the library itself.
563 tocFile := outputFile.ReplaceExtension(ctx, flags.Toolchain.SharedLibSuffix()[1:]+".toc")
564 library.tocFile = android.OptionalPathForPath(tocFile)
565 cc.TransformSharedObjectToToc(ctx, outputFile, tocFile)
566
Colin Cross0de8a1e2020-09-18 14:15:30 -0700567 ctx.SetProvider(cc.SharedLibraryInfoProvider, cc.SharedLibraryInfo{
Ivan Lozano7b0781d2021-11-03 15:30:18 -0400568 TableOfContents: android.OptionalPathForPath(tocFile),
569 SharedLibrary: outputFile,
570 Target: ctx.Target(),
Colin Cross0de8a1e2020-09-18 14:15:30 -0700571 })
572 }
573
574 if library.static() {
Colin Crossc85750b2022-04-21 12:50:51 -0700575 depSet := android.NewDepSetBuilder[android.Path](android.TOPOLOGICAL).Direct(outputFile).Build()
Colin Cross0de8a1e2020-09-18 14:15:30 -0700576 ctx.SetProvider(cc.StaticLibraryInfoProvider, cc.StaticLibraryInfo{
577 StaticLibrary: outputFile,
578
579 TransitiveStaticLibrariesForOrdering: depSet,
580 })
581 }
582
583 library.flagExporter.setProvider(ctx)
584
Ivan Lozano8d10fc32021-11-05 16:36:47 -0400585 return ret
Ivan Lozanoffee3342019-08-27 12:03:00 -0700586}
587
Sam Delmerico60375c42023-09-11 17:18:08 +0000588func (library *libraryDecorator) crateRootPath(ctx ModuleContext, _ PathDeps) android.Path {
Dan Albert06feee92021-03-19 15:06:02 -0700589 if library.sourceProvider != nil {
590 // Assume the first source from the source provider is the library entry point.
591 return library.sourceProvider.Srcs()[0]
Sam Delmerico60375c42023-09-11 17:18:08 +0000592 } else if library.baseCompiler.Properties.Crate_root == nil {
Dan Albert06feee92021-03-19 15:06:02 -0700593 path, _ := srcPathFromModuleSrcs(ctx, library.baseCompiler.Properties.Srcs)
594 return path
Sam Delmerico60375c42023-09-11 17:18:08 +0000595 } else {
596 return android.PathForModuleSrc(ctx, *library.baseCompiler.Properties.Crate_root)
Dan Albert06feee92021-03-19 15:06:02 -0700597 }
598}
599
600func (library *libraryDecorator) rustdoc(ctx ModuleContext, flags Flags,
601 deps PathDeps) android.OptionalPath {
602 // rustdoc has builtin support for documenting config specific information
603 // regardless of the actual config it was given
604 // (https://doc.rust-lang.org/rustdoc/advanced-features.html#cfgdoc-documenting-platform-specific-or-feature-specific-information),
605 // so we generate the rustdoc for only the primary module so that we have a
606 // single set of docs to refer to.
607 if ctx.Module() != ctx.PrimaryModule() {
608 return android.OptionalPath{}
609 }
610
Sam Delmerico60375c42023-09-11 17:18:08 +0000611 return android.OptionalPathForPath(Rustdoc(ctx, library.crateRootPath(ctx, deps),
Dan Albert06feee92021-03-19 15:06:02 -0700612 deps, flags))
613}
614
Ivan Lozanoad8b18b2019-10-31 19:38:29 -0700615func (library *libraryDecorator) getStem(ctx ModuleContext) string {
616 stem := library.baseCompiler.getStemWithoutSuffix(ctx)
617 validateLibraryStem(ctx, stem, library.crateName())
618
619 return stem + String(library.baseCompiler.Properties.Suffix)
620}
621
Ivan Lozano2b081132020-09-08 12:46:52 -0400622func (library *libraryDecorator) install(ctx ModuleContext) {
623 // Only shared and dylib variants make sense to install.
624 if library.shared() || library.dylib() {
625 library.baseCompiler.install(ctx)
626 }
627}
628
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400629func (library *libraryDecorator) Disabled() bool {
630 return library.MutatedProperties.VariantIsDisabled
631}
632
633func (library *libraryDecorator) SetDisabled() {
634 library.MutatedProperties.VariantIsDisabled = true
635}
636
Ivan Lozanoad8b18b2019-10-31 19:38:29 -0700637var validCrateName = regexp.MustCompile("[^a-zA-Z0-9_]+")
638
639func validateLibraryStem(ctx BaseModuleContext, filename string, crate_name string) {
640 if crate_name == "" {
641 ctx.PropertyErrorf("crate_name", "crate_name must be defined.")
642 }
643
644 // crate_names are used for the library output file, and rustc expects these
645 // to be alphanumeric with underscores allowed.
646 if validCrateName.MatchString(crate_name) {
647 ctx.PropertyErrorf("crate_name",
648 "library crate_names must be alphanumeric with underscores allowed")
649 }
650
651 // Libraries are expected to begin with "lib" followed by the crate_name
652 if !strings.HasPrefix(filename, "lib"+crate_name) {
653 ctx.ModuleErrorf("Invalid name or stem property; library filenames must start with lib<crate_name>")
654 }
655}
656
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200657// LibraryMutator mutates the libraries into variants according to the
658// build{Rlib,Dylib} attributes.
Ivan Lozanoffee3342019-08-27 12:03:00 -0700659func LibraryMutator(mctx android.BottomUpMutatorContext) {
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200660 // Only mutate on Rust libraries.
661 m, ok := mctx.Module().(*Module)
662 if !ok || m.compiler == nil {
663 return
664 }
665 library, ok := m.compiler.(libraryInterface)
666 if !ok {
667 return
668 }
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400669
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200670 var variants []string
671 // The source variant is used for SourceProvider modules. The other variants (i.e. rlib and dylib)
672 // depend on this variant. It must be the first variant to be declared.
673 sourceVariant := false
674 if m.sourceProvider != nil {
675 variants = append(variants, "source")
676 sourceVariant = true
677 }
678 if library.buildRlib() {
679 variants = append(variants, rlibVariation)
680 }
681 if library.buildDylib() {
682 variants = append(variants, dylibVariation)
683 }
Ivan Lozano26ecd6c2020-07-31 13:40:31 -0400684
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200685 if len(variants) == 0 {
686 return
687 }
688 modules := mctx.CreateLocalVariations(variants...)
689
690 // The order of the variations (modules) matches the variant names provided. Iterate
691 // through the new variation modules and set their mutated properties.
692 for i, v := range modules {
693 switch variants[i] {
694 case rlibVariation:
695 v.(*Module).compiler.(libraryInterface).setRlib()
696 case dylibVariation:
697 v.(*Module).compiler.(libraryInterface).setDylib()
Ivan Lozanoc08897c2021-04-02 12:41:32 -0400698 if v.(*Module).ModuleBase.ImageVariation().Variation == android.VendorRamdiskVariation {
Ivan Lozano6a884432020-12-02 09:15:16 -0500699 // TODO(b/165791368)
Ivan Lozanoc08897c2021-04-02 12:41:32 -0400700 // Disable dylib Vendor Ramdisk variations until we support these.
Ivan Lozano6a884432020-12-02 09:15:16 -0500701 v.(*Module).Disable()
702 }
Ivan Lozano1921e802021-05-20 13:39:16 -0400703
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200704 case "source":
705 v.(*Module).compiler.(libraryInterface).setSource()
706 // The source variant does not produce any library.
707 // Disable the compilation steps.
708 v.(*Module).compiler.SetDisabled()
Ivan Lozanoffee3342019-08-27 12:03:00 -0700709 }
710 }
Thiébaud Weksteen295c72b2020-09-23 18:10:17 +0200711
712 // If a source variant is created, add an inter-variant dependency
713 // between the other variants and the source variant.
714 if sourceVariant {
715 sv := modules[0]
716 for _, v := range modules[1:] {
717 if !v.Enabled() {
718 continue
719 }
720 mctx.AddInterVariantDependency(sourceDepTag, v, sv)
721 }
722 // Alias the source variation so it can be named directly in "srcs" properties.
723 mctx.AliasVariation("source")
724 }
Ivan Lozanoffee3342019-08-27 12:03:00 -0700725}
Ivan Lozano2b081132020-09-08 12:46:52 -0400726
727func LibstdMutator(mctx android.BottomUpMutatorContext) {
728 if m, ok := mctx.Module().(*Module); ok && m.compiler != nil && !m.compiler.Disabled() {
729 switch library := m.compiler.(type) {
730 case libraryInterface:
731 // Only create a variant if a library is actually being built.
732 if library.rlib() && !library.sysroot() {
733 variants := []string{"rlib-std", "dylib-std"}
734 modules := mctx.CreateLocalVariations(variants...)
735
736 rlib := modules[0].(*Module)
737 dylib := modules[1].(*Module)
738 rlib.compiler.(libraryInterface).setRlibStd()
739 dylib.compiler.(libraryInterface).setDylibStd()
Ivan Lozanoadd122a2023-07-13 11:01:41 -0400740 if dylib.ModuleBase.ImageVariation().Variation == android.VendorRamdiskVariation {
Ivan Lozano6a884432020-12-02 09:15:16 -0500741 // TODO(b/165791368)
Ivan Lozanoadd122a2023-07-13 11:01:41 -0400742 // Disable rlibs that link against dylib-std on vendor ramdisk variations until those dylib
Ivan Lozano6a884432020-12-02 09:15:16 -0500743 // variants are properly supported.
744 dylib.Disable()
745 }
Ivan Lozanoc08897c2021-04-02 12:41:32 -0400746 rlib.Properties.RustSubName += RlibStdlibSuffix
Ivan Lozano2b081132020-09-08 12:46:52 -0400747 }
748 }
749 }
750}
Ivan Lozano1921e802021-05-20 13:39:16 -0400751
752func (l *libraryDecorator) snapshotHeaders() android.Paths {
753 if l.collectedSnapshotHeaders == nil {
754 panic("snapshotHeaders() must be called after collectHeadersForSnapshot()")
755 }
756 return l.collectedSnapshotHeaders
757}
758
759// collectHeadersForSnapshot collects all exported headers from library.
760// It globs header files in the source tree for exported include directories,
761// and tracks generated header files separately.
762//
763// This is to be called from GenerateAndroidBuildActions, and then collected
764// header files can be retrieved by snapshotHeaders().
765func (l *libraryDecorator) collectHeadersForSnapshot(ctx android.ModuleContext, deps PathDeps) {
766 ret := android.Paths{}
767
768 // Glob together the headers from the modules include_dirs property
769 for _, path := range android.CopyOfPaths(l.includeDirs) {
770 dir := path.String()
Liz Kammer0ea79982022-02-07 08:51:47 -0500771 globDir := dir + "/**/*"
772 glob, err := ctx.GlobWithDeps(globDir, nil)
Ivan Lozano1921e802021-05-20 13:39:16 -0400773 if err != nil {
Liz Kammer0ea79982022-02-07 08:51:47 -0500774 ctx.ModuleErrorf("glob of %q failed: %s", globDir, err)
Ivan Lozano1921e802021-05-20 13:39:16 -0400775 return
776 }
777
778 for _, header := range glob {
779 // Filter out only the files with extensions that are headers.
780 found := false
781 for _, ext := range cc.HeaderExts {
782 if strings.HasSuffix(header, ext) {
783 found = true
784 break
785 }
786 }
787 if !found {
788 continue
789 }
790 ret = append(ret, android.PathForSource(ctx, header))
791 }
792 }
793
794 // Glob together the headers from C dependencies as well, starting with non-generated headers.
795 ret = append(ret, cc.GlobHeadersForSnapshot(ctx, append(android.CopyOfPaths(deps.depIncludePaths), deps.depSystemIncludePaths...))...)
796
797 // Collect generated headers from C dependencies.
798 ret = append(ret, cc.GlobGeneratedHeadersForSnapshot(ctx, deps.depGeneratedHeaders)...)
799
800 // TODO(185577950): If support for generated headers is added, they need to be collected here as well.
801 l.collectedSnapshotHeaders = ret
802}
Vinh Tranbcb5f572023-08-24 11:10:01 -0400803
804type rustLibraryAttributes struct {
Vinh Tranb4bb20f2023-08-24 11:10:01 -0400805 Srcs bazel.LabelListAttribute
806 Compile_data bazel.LabelListAttribute
807 Crate_name bazel.StringAttribute
808 Edition bazel.StringAttribute
809 Crate_features bazel.StringListAttribute
810 Deps bazel.LabelListAttribute
811 Rustc_flags bazel.StringListAttribute
812 Proc_macro_deps bazel.LabelListAttribute
Vinh Tranbcb5f572023-08-24 11:10:01 -0400813}
814
Chris Parsons637458d2023-09-19 20:09:00 +0000815func libraryBp2build(ctx android.Bp2buildMutatorContext, m *Module) {
Vinh Tranbcb5f572023-08-24 11:10:01 -0400816 lib := m.compiler.(*libraryDecorator)
Vinh Tran9b846782023-08-24 12:55:12 -0400817
Vinh Tranb4bb20f2023-08-24 11:10:01 -0400818 srcs, compileData := srcsAndCompileDataAttrs(ctx, *lib.baseCompiler)
Vinh Tran9b846782023-08-24 12:55:12 -0400819
Vinh Tranbcb5f572023-08-24 11:10:01 -0400820 deps := android.BazelLabelForModuleDeps(ctx, append(
821 lib.baseCompiler.Properties.Rustlibs,
822 lib.baseCompiler.Properties.Rlibs...,
823 ))
Vinh Tran9b846782023-08-24 12:55:12 -0400824
825 cargoBuildScript := cargoBuildScriptBp2build(ctx, m)
826 if cargoBuildScript != nil {
827 deps.Add(&bazel.Label{
828 Label: ":" + *cargoBuildScript,
829 })
830 }
831
Vinh Tranb4bb20f2023-08-24 11:10:01 -0400832 procMacroDeps := android.BazelLabelForModuleDeps(ctx, lib.baseCompiler.Properties.Proc_macros)
833
834 var rustcFLags []string
835 for _, cfg := range lib.baseCompiler.Properties.Cfgs {
836 rustcFLags = append(rustcFLags, fmt.Sprintf("--cfg=%s", cfg))
837 }
Vinh Tranbcb5f572023-08-24 11:10:01 -0400838
839 attrs := &rustLibraryAttributes{
840 Srcs: bazel.MakeLabelListAttribute(
841 srcs,
842 ),
843 Compile_data: bazel.MakeLabelListAttribute(
844 compileData,
845 ),
846 Crate_name: bazel.StringAttribute{
847 Value: &lib.baseCompiler.Properties.Crate_name,
848 },
849 Edition: bazel.StringAttribute{
850 Value: lib.baseCompiler.Properties.Edition,
851 },
852 Crate_features: bazel.StringListAttribute{
853 Value: lib.baseCompiler.Properties.Features,
854 },
855 Deps: bazel.MakeLabelListAttribute(
856 deps,
857 ),
Vinh Tranb4bb20f2023-08-24 11:10:01 -0400858 Proc_macro_deps: bazel.MakeLabelListAttribute(
859 procMacroDeps,
860 ),
Vinh Tranbcb5f572023-08-24 11:10:01 -0400861 Rustc_flags: bazel.StringListAttribute{
862 Value: append(
863 rustcFLags,
864 lib.baseCompiler.Properties.Flags...,
865 ),
866 },
867 }
868
869 // TODO(b/290790800): Remove the restriction when rust toolchain for android is implemented
870 var restriction bazel.BoolAttribute
871 restriction.SetSelectValue(bazel.OsConfigurationAxis, "android", proptools.BoolPtr(false))
872
873 ctx.CreateBazelTargetModuleWithRestrictions(
874 bazel.BazelTargetModuleProperties{
875 Rule_class: "rust_library",
876 Bzl_load_location: "@rules_rust//rust:defs.bzl",
877 },
878 android.CommonAttributes{
879 Name: m.Name(),
880 },
881 attrs,
882 restriction,
883 )
884}
Vinh Tran9b846782023-08-24 12:55:12 -0400885
886type cargoBuildScriptAttributes struct {
887 Srcs bazel.LabelListAttribute
888 Edition bazel.StringAttribute
889 Version bazel.StringAttribute
890}
891
Chris Parsons637458d2023-09-19 20:09:00 +0000892func cargoBuildScriptBp2build(ctx android.Bp2buildMutatorContext, m *Module) *string {
Vinh Tran9b846782023-08-24 12:55:12 -0400893 // Soong treats some crates like libprotobuf as special in that they have
894 // cargo build script ran to produce an out folder and check it into AOSP
895 // For example, https://cs.android.com/android/platform/superproject/main/+/main:external/rust/crates/protobuf/out/
896 // is produced by cargo build script https://cs.android.com/android/platform/superproject/main/+/main:external/rust/crates/protobuf/build.rs
897 // The out folder is then fed into `rust_library` by a genrule
898 // https://cs.android.com/android/platform/superproject/main/+/main:external/rust/crates/protobuf/Android.bp;l=22
899 // This allows Soong to decouple from cargo completely.
900
901 // Soong decouples from cargo so that it has control over cc compilation.
902 // https://cs.android.com/android/platform/superproject/main/+/main:development/scripts/cargo2android.py;l=1033-1041;drc=8449944a50a0445a5ecaf9b7aed12608c81bf3f1
903 // generates a `cc_library_static` module to have custom cc flags.
904 // Since bp2build will convert the cc modules to cc targets which include the cflags,
905 // Bazel does not need to have this optimization.
906
907 // Performance-wise: rust_library -> cargo_build_script vs rust_library -> genrule (like Soong)
908 // don't have any major difference in build time in Bazel. So using cargo_build_script does not slow
909 // down the build.
910
911 // The benefit of using `cargo_build_script` here is that it would take care of setting correct
912 // `OUT_DIR` for us - similar to what Soong does here
913 // https://cs.android.com/android/platform/superproject/main/+/main:build/soong/rust/builder.go;l=202-218;drc=f29ca58e88c5846bbe8955e5192135e5ab4f14a1
914
915 // TODO(b/297364081): cargo2android.py has logic for when generate/not cc_library_static and out directory
916 // bp2build might be able use the same logic for when to use `cargo_build_script`.
917 // For now, we're building libprotobuf_build_script as a one-off until we have a more principled solution
918 if m.Name() != "libprotobuf" {
919 return nil
920 }
921
922 lib := m.compiler.(*libraryDecorator)
923
924 name := m.Name() + "_build_script"
925 attrs := &cargoBuildScriptAttributes{
926 Srcs: bazel.MakeLabelListAttribute(
927 android.BazelLabelForModuleSrc(ctx, []string{"build.rs"}),
928 ),
929 Edition: bazel.StringAttribute{
930 Value: lib.baseCompiler.Properties.Edition,
931 },
932 Version: bazel.StringAttribute{
933 Value: lib.baseCompiler.Properties.Cargo_pkg_version,
934 },
935 }
936
937 // TODO(b/290790800): Remove the restriction when rust toolchain for android is implemented
938 var restriction bazel.BoolAttribute
939 restriction.SetSelectValue(bazel.OsConfigurationAxis, "android", proptools.BoolPtr(false))
940
941 ctx.CreateBazelTargetModuleWithRestrictions(
942 bazel.BazelTargetModuleProperties{
943 Rule_class: "cargo_build_script",
944 Bzl_load_location: "@rules_rust//cargo:cargo_build_script.bzl",
945 },
946 android.CommonAttributes{
947 Name: name,
948 },
949 attrs,
950 restriction,
951 )
952
953 return &name
954}