blob: 1fcce3859e4a6f8755841beff5b22326f92351bd [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 (
Ivan Lozano1776a2a2020-11-11 10:59:52 -050018 "path/filepath"
Ivan Lozanoffee3342019-08-27 12:03:00 -070019 "strings"
20
21 "github.com/google/blueprint"
22
23 "android/soong/android"
Thiébaud Weksteen71512f32020-11-03 15:17:51 +010024 "android/soong/rust/config"
Ivan Lozanoffee3342019-08-27 12:03:00 -070025)
26
27var (
28 _ = pctx.SourcePathVariable("rustcCmd", "${config.RustBin}/rustc")
29 rustc = pctx.AndroidStaticRule("rustc",
30 blueprint.RuleParams{
Ivan Lozano43845682020-07-09 21:03:28 -040031 Command: "$envVars $rustcCmd " +
Ivan Lozanoffee3342019-08-27 12:03:00 -070032 "-C linker=${config.RustLinker} " +
Ivan Lozanof1c84332019-09-20 11:00:37 -070033 "-C link-args=\"${crtBegin} ${config.RustLinkerArgs} ${linkFlags} ${crtEnd}\" " +
Chih-Hung Hsieh29aa9fd2020-08-13 15:46:21 -070034 "--emit link -o $out --emit dep-info=$out.d.raw $in ${libFlags} $rustcFlags" +
35 " && grep \"^$out:\" $out.d.raw > $out.d",
Ivan Lozanoffee3342019-08-27 12:03:00 -070036 CommandDeps: []string{"$rustcCmd"},
Ivan Lozanob2df9f82019-11-05 12:16:46 -080037 // Rustc deps-info writes out make compatible dep files: https://github.com/rust-lang/rust/issues/7633
Chih-Hung Hsieh29aa9fd2020-08-13 15:46:21 -070038 // Rustc emits unneeded dependency lines for the .d and input .rs files.
39 // Those extra lines cause ninja warning:
40 // "warning: depfile has multiple output paths"
41 // For ninja, we keep/grep only the dependency rule for the rust $out file.
Ivan Lozanob2df9f82019-11-05 12:16:46 -080042 Deps: blueprint.DepsGCC,
43 Depfile: "$out.d",
Ivan Lozanoffee3342019-08-27 12:03:00 -070044 },
Ivan Lozano43845682020-07-09 21:03:28 -040045 "rustcFlags", "linkFlags", "libFlags", "crtBegin", "crtEnd", "envVars")
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -040046
Dan Albert06feee92021-03-19 15:06:02 -070047 _ = pctx.SourcePathVariable("rustdocCmd", "${config.RustBin}/rustdoc")
48 rustdoc = pctx.AndroidStaticRule("rustdoc",
49 blueprint.RuleParams{
50 Command: "rm -rf $outDir && " +
51 "$envVars $rustdocCmd $rustdocFlags $in -o $outDir && " +
52 "touch $out",
53 CommandDeps: []string{"$rustdocCmd"},
54 },
55 "rustdocFlags", "outDir", "envVars")
56
Thiébaud Weksteen92f703b2020-06-22 13:28:02 +020057 _ = pctx.SourcePathVariable("clippyCmd", "${config.RustBin}/clippy-driver")
58 clippyDriver = pctx.AndroidStaticRule("clippy",
59 blueprint.RuleParams{
Ivan Lozanobae62be2020-07-21 13:28:27 -040060 Command: "$envVars $clippyCmd " +
Thiébaud Weksteen92f703b2020-06-22 13:28:02 +020061 // Because clippy-driver uses rustc as backend, we need to have some output even during the linting.
62 // Use the metadata output as it has the smallest footprint.
Thiébaud Weksteen94c83252021-04-07 16:00:19 +020063 "--emit metadata -o $out --emit dep-info=$out.d.raw $in ${libFlags} " +
64 "$rustcFlags $clippyFlags" +
65 " && grep \"^$out:\" $out.d.raw > $out.d",
Thiébaud Weksteen92f703b2020-06-22 13:28:02 +020066 CommandDeps: []string{"$clippyCmd"},
Thiébaud Weksteen94c83252021-04-07 16:00:19 +020067 Deps: blueprint.DepsGCC,
68 Depfile: "$out.d",
Thiébaud Weksteen92f703b2020-06-22 13:28:02 +020069 },
Ivan Lozanobae62be2020-07-21 13:28:27 -040070 "rustcFlags", "libFlags", "clippyFlags", "envVars")
Thiébaud Weksteen92f703b2020-06-22 13:28:02 +020071
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -040072 zip = pctx.AndroidStaticRule("zip",
73 blueprint.RuleParams{
74 Command: "cat $out.rsp | tr ' ' '\\n' | tr -d \\' | sort -u > ${out}.tmp && ${SoongZipCmd} -o ${out} -C $$OUT_DIR -l ${out}.tmp",
75 CommandDeps: []string{"${SoongZipCmd}"},
76 Rspfile: "$out.rsp",
77 RspfileContent: "$in",
78 })
Ivan Lozano43845682020-07-09 21:03:28 -040079
80 cp = pctx.AndroidStaticRule("cp",
81 blueprint.RuleParams{
82 Command: "cp `cat $outDir.rsp` $outDir",
83 Rspfile: "${outDir}.rsp",
84 RspfileContent: "$in",
85 },
86 "outDir")
Ivan Lozanoffee3342019-08-27 12:03:00 -070087)
88
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -040089type buildOutput struct {
Joel Galensonfa049382021-01-14 16:03:18 -080090 outputFile android.Path
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -040091}
Ivan Lozanoffee3342019-08-27 12:03:00 -070092
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -040093func init() {
94 pctx.HostBinToolVariable("SoongZipCmd", "soong_zip")
Ivan Lozanoffee3342019-08-27 12:03:00 -070095}
96
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +020097func TransformSrcToBinary(ctx ModuleContext, mainSrc android.Path, deps PathDeps, flags Flags,
Dan Albert06feee92021-03-19 15:06:02 -070098 outputFile android.WritablePath) buildOutput {
Ivan Lozano6cd99e62020-02-11 08:24:25 -050099 flags.GlobalRustFlags = append(flags.GlobalRustFlags, "-C lto")
Ivan Lozano31b095d2019-11-20 10:14:33 -0800100
Dan Albert06feee92021-03-19 15:06:02 -0700101 return transformSrctoCrate(ctx, mainSrc, deps, flags, outputFile, "bin")
Ivan Lozanoffee3342019-08-27 12:03:00 -0700102}
103
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +0200104func TransformSrctoRlib(ctx ModuleContext, mainSrc android.Path, deps PathDeps, flags Flags,
Dan Albert06feee92021-03-19 15:06:02 -0700105 outputFile android.WritablePath) buildOutput {
106 return transformSrctoCrate(ctx, mainSrc, deps, flags, outputFile, "rlib")
Ivan Lozanoffee3342019-08-27 12:03:00 -0700107}
108
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +0200109func TransformSrctoDylib(ctx ModuleContext, mainSrc android.Path, deps PathDeps, flags Flags,
Dan Albert06feee92021-03-19 15:06:02 -0700110 outputFile android.WritablePath) buildOutput {
111 return transformSrctoCrate(ctx, mainSrc, deps, flags, outputFile, "dylib")
Ivan Lozanoffee3342019-08-27 12:03:00 -0700112}
113
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +0200114func TransformSrctoStatic(ctx ModuleContext, mainSrc android.Path, deps PathDeps, flags Flags,
Dan Albert06feee92021-03-19 15:06:02 -0700115 outputFile android.WritablePath) buildOutput {
Ivan Lozano6cd99e62020-02-11 08:24:25 -0500116 flags.GlobalRustFlags = append(flags.GlobalRustFlags, "-C lto")
Dan Albert06feee92021-03-19 15:06:02 -0700117 return transformSrctoCrate(ctx, mainSrc, deps, flags, outputFile, "staticlib")
Ivan Lozano52767be2019-10-18 14:49:46 -0700118}
119
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +0200120func TransformSrctoShared(ctx ModuleContext, mainSrc android.Path, deps PathDeps, flags Flags,
Dan Albert06feee92021-03-19 15:06:02 -0700121 outputFile android.WritablePath) buildOutput {
Ivan Lozano6cd99e62020-02-11 08:24:25 -0500122 flags.GlobalRustFlags = append(flags.GlobalRustFlags, "-C lto")
Dan Albert06feee92021-03-19 15:06:02 -0700123 return transformSrctoCrate(ctx, mainSrc, deps, flags, outputFile, "cdylib")
Ivan Lozano52767be2019-10-18 14:49:46 -0700124}
125
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +0200126func TransformSrctoProcMacro(ctx ModuleContext, mainSrc android.Path, deps PathDeps,
Dan Albert06feee92021-03-19 15:06:02 -0700127 flags Flags, outputFile android.WritablePath) buildOutput {
128 return transformSrctoCrate(ctx, mainSrc, deps, flags, outputFile, "proc-macro")
Ivan Lozanoffee3342019-08-27 12:03:00 -0700129}
130
131func rustLibsToPaths(libs RustLibraries) android.Paths {
132 var paths android.Paths
133 for _, lib := range libs {
134 paths = append(paths, lib.Path)
135 }
136 return paths
137}
138
Dan Albert06feee92021-03-19 15:06:02 -0700139func makeLibFlags(deps PathDeps) []string {
140 var libFlags []string
141
142 // Collect library/crate flags
143 for _, lib := range deps.RLibs {
144 libFlags = append(libFlags, "--extern "+lib.CrateName+"="+lib.Path.String())
145 }
146 for _, lib := range deps.DyLibs {
147 libFlags = append(libFlags, "--extern "+lib.CrateName+"="+lib.Path.String())
148 }
149 for _, proc_macro := range deps.ProcMacros {
150 libFlags = append(libFlags, "--extern "+proc_macro.CrateName+"="+proc_macro.Path.String())
151 }
152
153 for _, path := range deps.linkDirs {
154 libFlags = append(libFlags, "-L "+path)
155 }
156
157 return libFlags
158}
159
160func rustEnvVars(ctx ModuleContext, deps PathDeps) []string {
161 var envVars []string
162
163 // libstd requires a specific environment variable to be set. This is
164 // not officially documented and may be removed in the future. See
165 // https://github.com/rust-lang/rust/blob/master/library/std/src/env.rs#L866.
166 if ctx.RustModule().CrateName() == "std" {
167 envVars = append(envVars, "STD_ENV_ARCH="+config.StdEnvArch[ctx.RustModule().Arch().ArchType])
168 }
169
170 if len(deps.SrcDeps) > 0 {
171 moduleGenDir := ctx.RustModule().compiler.CargoOutDir()
172 // We must calculate an absolute path for OUT_DIR since Rust's include! macro (which normally consumes this)
173 // assumes that paths are relative to the source file.
174 var outDirPrefix string
175 if !filepath.IsAbs(moduleGenDir.String()) {
176 // If OUT_DIR is not absolute, we use $$PWD to generate an absolute path (os.Getwd() returns '/')
177 outDirPrefix = "$$PWD/"
178 } else {
179 // If OUT_DIR is absolute, then moduleGenDir will be an absolute path, so we don't need to set this to anything.
180 outDirPrefix = ""
181 }
182 envVars = append(envVars, "OUT_DIR="+filepath.Join(outDirPrefix, moduleGenDir.String()))
183 }
184
185 return envVars
186}
187
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +0200188func transformSrctoCrate(ctx ModuleContext, main android.Path, deps PathDeps, flags Flags,
Dan Albert06feee92021-03-19 15:06:02 -0700189 outputFile android.WritablePath, crate_type string) buildOutput {
Ivan Lozanoffee3342019-08-27 12:03:00 -0700190
191 var inputs android.Paths
Ivan Lozanob2df9f82019-11-05 12:16:46 -0800192 var implicits android.Paths
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400193 var output buildOutput
Dan Albert06feee92021-03-19 15:06:02 -0700194 var rustcFlags, linkFlags []string
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400195 var implicitOutputs android.WritablePaths
196
197 output.outputFile = outputFile
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800198 crateName := ctx.RustModule().CrateName()
Thiébaud Weksteen1f7f70f2020-06-24 11:32:48 +0200199 targetTriple := ctx.toolchain().RustTriple()
Ivan Lozanoffee3342019-08-27 12:03:00 -0700200
Dan Albert06feee92021-03-19 15:06:02 -0700201 envVars := rustEnvVars(ctx, deps)
Thiébaud Weksteen71512f32020-11-03 15:17:51 +0100202
Ivan Lozanoffee3342019-08-27 12:03:00 -0700203 inputs = append(inputs, main)
204
205 // Collect rustc flags
Ivan Lozanof1c84332019-09-20 11:00:37 -0700206 rustcFlags = append(rustcFlags, flags.GlobalRustFlags...)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700207 rustcFlags = append(rustcFlags, flags.RustFlags...)
208 rustcFlags = append(rustcFlags, "--crate-type="+crate_type)
Jaewoong Jung18aefc12020-12-21 09:11:10 -0800209 if crateName != "" {
210 rustcFlags = append(rustcFlags, "--crate-name="+crateName)
Ivan Lozanoad8b18b2019-10-31 19:38:29 -0700211 }
Ivan Lozanoffee3342019-08-27 12:03:00 -0700212 if targetTriple != "" {
213 rustcFlags = append(rustcFlags, "--target="+targetTriple)
Ivan Lozanof1c84332019-09-20 11:00:37 -0700214 linkFlags = append(linkFlags, "-target "+targetTriple)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700215 }
Matthew Maurerbb3add12020-06-25 09:34:12 -0700216
217 // Suppress an implicit sysroot
218 rustcFlags = append(rustcFlags, "--sysroot=/dev/null")
219
Ivan Lozanof1c84332019-09-20 11:00:37 -0700220 // Collect linker flags
221 linkFlags = append(linkFlags, flags.GlobalLinkFlags...)
222 linkFlags = append(linkFlags, flags.LinkFlags...)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700223
Dan Albert06feee92021-03-19 15:06:02 -0700224 libFlags := makeLibFlags(deps)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700225
226 // Collect dependencies
Ivan Lozanob2df9f82019-11-05 12:16:46 -0800227 implicits = append(implicits, rustLibsToPaths(deps.RLibs)...)
228 implicits = append(implicits, rustLibsToPaths(deps.DyLibs)...)
229 implicits = append(implicits, rustLibsToPaths(deps.ProcMacros)...)
230 implicits = append(implicits, deps.StaticLibs...)
Ivan Lozanoec6e9912021-01-21 15:23:29 -0500231 implicits = append(implicits, deps.SharedLibDeps...)
Ivan Lozano9d74a522020-12-01 09:25:22 -0500232 implicits = append(implicits, deps.srcProviderFiles...)
Ivan Lozano43845682020-07-09 21:03:28 -0400233
Ivan Lozanob2df9f82019-11-05 12:16:46 -0800234 if deps.CrtBegin.Valid() {
235 implicits = append(implicits, deps.CrtBegin.Path(), deps.CrtEnd.Path())
Ivan Lozanof1c84332019-09-20 11:00:37 -0700236 }
Ivan Lozanoffee3342019-08-27 12:03:00 -0700237
Ivan Lozano43845682020-07-09 21:03:28 -0400238 if len(deps.SrcDeps) > 0 {
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100239 moduleGenDir := ctx.RustModule().compiler.CargoOutDir()
Ivan Lozano43845682020-07-09 21:03:28 -0400240 var outputs android.WritablePaths
241
242 for _, genSrc := range deps.SrcDeps {
Ivan Lozano10735d92020-07-22 09:14:47 -0400243 if android.SuffixInList(outputs.Strings(), genSubDir+genSrc.Base()) {
Ivan Lozano43845682020-07-09 21:03:28 -0400244 ctx.PropertyErrorf("srcs",
245 "multiple source providers generate the same filename output: "+genSrc.Base())
246 }
Ivan Lozano10735d92020-07-22 09:14:47 -0400247 outputs = append(outputs, android.PathForModuleOut(ctx, genSubDir+genSrc.Base()))
Ivan Lozano43845682020-07-09 21:03:28 -0400248 }
249
250 ctx.Build(pctx, android.BuildParams{
251 Rule: cp,
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100252 Description: "cp " + moduleGenDir.Path().Rel(),
Ivan Lozano43845682020-07-09 21:03:28 -0400253 Outputs: outputs,
254 Inputs: deps.SrcDeps,
255 Args: map[string]string{
256 "outDir": moduleGenDir.String(),
257 },
258 })
259 implicits = append(implicits, outputs.Paths()...)
Ivan Lozano43845682020-07-09 21:03:28 -0400260 }
261
Thiébaud Weksteen9997ea72021-02-22 10:52:22 +0100262 envVars = append(envVars, "ANDROID_RUST_VERSION="+config.RustDefaultVersion)
263
Ivan Lozanobae62be2020-07-21 13:28:27 -0400264 if flags.Clippy {
265 clippyFile := android.PathForModuleOut(ctx, outputFile.Base()+".clippy")
266 ctx.Build(pctx, android.BuildParams{
267 Rule: clippyDriver,
268 Description: "clippy " + main.Rel(),
269 Output: clippyFile,
270 ImplicitOutputs: nil,
271 Inputs: inputs,
272 Implicits: implicits,
273 Args: map[string]string{
274 "rustcFlags": strings.Join(rustcFlags, " "),
275 "libFlags": strings.Join(libFlags, " "),
276 "clippyFlags": strings.Join(flags.ClippyFlags, " "),
277 "envVars": strings.Join(envVars, " "),
278 },
279 })
280 // Declare the clippy build as an implicit dependency of the original crate.
281 implicits = append(implicits, clippyFile)
282 }
283
Ivan Lozanoffee3342019-08-27 12:03:00 -0700284 ctx.Build(pctx, android.BuildParams{
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400285 Rule: rustc,
286 Description: "rustc " + main.Rel(),
287 Output: outputFile,
288 ImplicitOutputs: implicitOutputs,
289 Inputs: inputs,
290 Implicits: implicits,
Ivan Lozanoffee3342019-08-27 12:03:00 -0700291 Args: map[string]string{
292 "rustcFlags": strings.Join(rustcFlags, " "),
Ivan Lozanof1c84332019-09-20 11:00:37 -0700293 "linkFlags": strings.Join(linkFlags, " "),
Ivan Lozanoffee3342019-08-27 12:03:00 -0700294 "libFlags": strings.Join(libFlags, " "),
Ivan Lozanob2df9f82019-11-05 12:16:46 -0800295 "crtBegin": deps.CrtBegin.String(),
296 "crtEnd": deps.CrtEnd.String(),
Ivan Lozano43845682020-07-09 21:03:28 -0400297 "envVars": strings.Join(envVars, " "),
Ivan Lozanoffee3342019-08-27 12:03:00 -0700298 },
299 })
300
Ivan Lozanoa0cd8f92020-04-09 09:56:02 -0400301 return output
302}
Dan Albert06feee92021-03-19 15:06:02 -0700303
304func Rustdoc(ctx ModuleContext, main android.Path, deps PathDeps,
305 flags Flags) android.ModuleOutPath {
306
307 rustdocFlags := append([]string{}, flags.RustdocFlags...)
308 rustdocFlags = append(rustdocFlags, "--sysroot=/dev/null")
309
310 targetTriple := ctx.toolchain().RustTriple()
311
312 // Collect rustc flags
313 if targetTriple != "" {
314 rustdocFlags = append(rustdocFlags, "--target="+targetTriple)
315 }
316
317 crateName := ctx.RustModule().CrateName()
318 if crateName != "" {
319 rustdocFlags = append(rustdocFlags, "--crate-name "+crateName)
320 }
321
322 rustdocFlags = append(rustdocFlags, makeLibFlags(deps)...)
323 docTimestampFile := android.PathForModuleOut(ctx, "rustdoc.timestamp")
324 docDir := android.PathForOutput(ctx, "rustdoc", ctx.ModuleName())
325
326 ctx.Build(pctx, android.BuildParams{
327 Rule: rustdoc,
328 Description: "rustdoc " + main.Rel(),
329 Output: docTimestampFile,
330 Input: main,
331 Implicit: ctx.RustModule().unstrippedOutputFile.Path(),
332 Args: map[string]string{
333 "rustdocFlags": strings.Join(rustdocFlags, " "),
334 "outDir": docDir.String(),
335 "envVars": strings.Join(rustEnvVars(ctx, deps), " "),
336 },
337 })
338
339 return docTimestampFile
340}