blob: 2120916629652569b8896fecf3527797289e93d5 [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 (
18 "strings"
19
20 "github.com/google/blueprint"
21 "github.com/google/blueprint/proptools"
22
23 "android/soong/android"
24 "android/soong/cc"
25 "android/soong/rust/config"
26)
27
28var pctx = android.NewPackageContext("android/soong/rust")
29
30func init() {
31 // Only allow rust modules to be defined for certain projects
Ivan Lozanoffee3342019-08-27 12:03:00 -070032
33 android.AddNeverAllowRules(
34 android.NeverAllow().
Ivan Lozanoe169ad72019-09-18 08:42:54 -070035 NotIn(config.RustAllowedPaths...).
36 ModuleType(config.RustModuleTypes...))
Ivan Lozanoffee3342019-08-27 12:03:00 -070037
38 android.RegisterModuleType("rust_defaults", defaultsFactory)
39 android.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
40 ctx.BottomUp("rust_libraries", LibraryMutator).Parallel()
41 })
42 pctx.Import("android/soong/rust/config")
43}
44
45type Flags struct {
46 GlobalFlags []string // Flags that apply globally
47 RustFlags []string // Flags that apply to rust
48 LinkFlags []string // Flags that apply to linker
49 RustFlagsDeps android.Paths // Files depended on by compiler flags
50 Toolchain config.Toolchain
51}
52
53type BaseProperties struct {
54 AndroidMkRlibs []string
55 AndroidMkDylibs []string
56 AndroidMkProcMacroLibs []string
57 AndroidMkSharedLibs []string
58 AndroidMkStaticLibs []string
59}
60
61type Module struct {
62 android.ModuleBase
63 android.DefaultableModuleBase
64
65 Properties BaseProperties
66
67 hod android.HostOrDeviceSupported
68 multilib android.Multilib
69
70 compiler compiler
71 cachedToolchain config.Toolchain
72 subAndroidMkOnce map[subAndroidMkProvider]bool
73 outputFile android.OptionalPath
74}
75
76type Deps struct {
77 Dylibs []string
78 Rlibs []string
79 ProcMacros []string
80 SharedLibs []string
81 StaticLibs []string
82
83 CrtBegin, CrtEnd string
84}
85
86type PathDeps struct {
87 DyLibs RustLibraries
88 RLibs RustLibraries
89 SharedLibs android.Paths
90 StaticLibs android.Paths
91 ProcMacros RustLibraries
92 linkDirs []string
93 depFlags []string
94 //ReexportedDeps android.Paths
95}
96
97type RustLibraries []RustLibrary
98
99type RustLibrary struct {
100 Path android.Path
101 CrateName string
102}
103
104type compiler interface {
105 compilerFlags(ctx ModuleContext, flags Flags) Flags
106 compilerProps() []interface{}
107 compile(ctx ModuleContext, flags Flags, deps PathDeps) android.Path
108 compilerDeps(ctx DepsContext, deps Deps) Deps
109 crateName() string
110
111 install(ctx ModuleContext, path android.Path)
112 relativeInstallPath() string
113}
114
115func defaultsFactory() android.Module {
116 return DefaultsFactory()
117}
118
119type Defaults struct {
120 android.ModuleBase
121 android.DefaultsModuleBase
122}
123
124func DefaultsFactory(props ...interface{}) android.Module {
125 module := &Defaults{}
126
127 module.AddProperties(props...)
128 module.AddProperties(
129 &BaseProperties{},
130 &BaseCompilerProperties{},
131 &BinaryCompilerProperties{},
132 &LibraryCompilerProperties{},
133 &ProcMacroCompilerProperties{},
134 &PrebuiltProperties{},
135 )
136
137 android.InitDefaultsModule(module)
138 return module
139}
140
141func (mod *Module) CrateName() string {
142 if mod.compiler != nil && mod.compiler.crateName() != "" {
143 return mod.compiler.crateName()
144 }
145 // Default crate names replace '-' in the name to '_'
146 return strings.Replace(mod.BaseModuleName(), "-", "_", -1)
147}
148
149func (mod *Module) Init() android.Module {
150 mod.AddProperties(&mod.Properties)
151
152 if mod.compiler != nil {
153 mod.AddProperties(mod.compiler.compilerProps()...)
154 }
155 android.InitAndroidArchModule(mod, mod.hod, mod.multilib)
156
157 android.InitDefaultableModule(mod)
158
Ivan Lozanode252912019-09-06 15:29:52 -0700159 // Explicitly disable unsupported targets.
160 android.AddLoadHook(mod, func(ctx android.LoadHookContext) {
161 disableTargets := struct {
162 Target struct {
163 Darwin struct {
164 Enabled *bool
165 }
166 Linux_bionic struct {
167 Enabled *bool
168 }
169 }
170 }{}
171 disableTargets.Target.Darwin.Enabled = proptools.BoolPtr(false)
172 disableTargets.Target.Linux_bionic.Enabled = proptools.BoolPtr(false)
173
174 ctx.AppendProperties(&disableTargets)
175 })
176
Ivan Lozanoffee3342019-08-27 12:03:00 -0700177 return mod
178}
179
180func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
181 return &Module{
182 hod: hod,
183 multilib: multilib,
184 }
185}
186func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
187 module := newBaseModule(hod, multilib)
188 return module
189}
190
191type ModuleContext interface {
192 android.ModuleContext
193 ModuleContextIntf
194}
195
196type BaseModuleContext interface {
197 android.BaseModuleContext
198 ModuleContextIntf
199}
200
201type DepsContext interface {
202 android.BottomUpMutatorContext
203 ModuleContextIntf
204}
205
206type ModuleContextIntf interface {
207 toolchain() config.Toolchain
208 baseModuleName() string
209 CrateName() string
210}
211
212type depsContext struct {
213 android.BottomUpMutatorContext
214 moduleContextImpl
215}
216
217type moduleContext struct {
218 android.ModuleContext
219 moduleContextImpl
220}
221
222type moduleContextImpl struct {
223 mod *Module
224 ctx BaseModuleContext
225}
226
227func (ctx *moduleContextImpl) toolchain() config.Toolchain {
228 return ctx.mod.toolchain(ctx.ctx)
229}
230
231func (mod *Module) toolchain(ctx android.BaseModuleContext) config.Toolchain {
232 if mod.cachedToolchain == nil {
233 mod.cachedToolchain = config.FindToolchain(ctx.Os(), ctx.Arch())
234 }
235 return mod.cachedToolchain
236}
237
238func (d *Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
239}
240
241func (mod *Module) GenerateAndroidBuildActions(actx android.ModuleContext) {
242 ctx := &moduleContext{
243 ModuleContext: actx,
244 moduleContextImpl: moduleContextImpl{
245 mod: mod,
246 },
247 }
248 ctx.ctx = ctx
249
250 toolchain := mod.toolchain(ctx)
251
252 if !toolchain.Supported() {
253 // This toolchain's unsupported, there's nothing to do for this mod.
254 return
255 }
256
257 deps := mod.depsToPaths(ctx)
258 flags := Flags{
259 Toolchain: toolchain,
260 }
261
262 if mod.compiler != nil {
263 flags = mod.compiler.compilerFlags(ctx, flags)
264 outputFile := mod.compiler.compile(ctx, flags, deps)
265 mod.outputFile = android.OptionalPathForPath(outputFile)
266 mod.compiler.install(ctx, mod.outputFile.Path())
267 }
268}
269
270func (mod *Module) deps(ctx DepsContext) Deps {
271 deps := Deps{}
272
273 if mod.compiler != nil {
274 deps = mod.compiler.compilerDeps(ctx, deps)
275 }
276
277 deps.Rlibs = android.LastUniqueStrings(deps.Rlibs)
278 deps.Dylibs = android.LastUniqueStrings(deps.Dylibs)
279 deps.ProcMacros = android.LastUniqueStrings(deps.ProcMacros)
280 deps.SharedLibs = android.LastUniqueStrings(deps.SharedLibs)
281 deps.StaticLibs = android.LastUniqueStrings(deps.StaticLibs)
282
283 return deps
284
285}
286
287func (ctx *moduleContextImpl) baseModuleName() string {
288 return ctx.mod.ModuleBase.BaseModuleName()
289}
290
291func (ctx *moduleContextImpl) CrateName() string {
292 return ctx.mod.CrateName()
293}
294
295type dependencyTag struct {
296 blueprint.BaseDependencyTag
297 name string
298 library bool
299 proc_macro bool
300}
301
302var (
303 rlibDepTag = dependencyTag{name: "rlibTag", library: true}
304 dylibDepTag = dependencyTag{name: "dylib", library: true}
305 procMacroDepTag = dependencyTag{name: "procMacro", proc_macro: true}
306)
307
308func (mod *Module) depsToPaths(ctx android.ModuleContext) PathDeps {
309 var depPaths PathDeps
310
311 directRlibDeps := []*Module{}
312 directDylibDeps := []*Module{}
313 directProcMacroDeps := []*Module{}
314 directSharedLibDeps := []*(cc.Module){}
315 directStaticLibDeps := []*(cc.Module){}
316
317 ctx.VisitDirectDeps(func(dep android.Module) {
318 depName := ctx.OtherModuleName(dep)
319 depTag := ctx.OtherModuleDependencyTag(dep)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700320
321 if rustDep, ok := dep.(*Module); ok {
322 //Handle Rust Modules
Ivan Lozano70e0a072019-09-13 14:23:15 -0700323
324 if rustDep.Target().Os != ctx.Os() {
325 ctx.ModuleErrorf("OS mismatch between %q and %q", ctx.ModuleName(), depName)
326 return
327 }
328 if rustDep.Target().Arch.ArchType != ctx.Arch().ArchType {
329 ctx.ModuleErrorf("Arch mismatch between %q and %q", ctx.ModuleName(), depName)
330 return
331 }
332
Ivan Lozanoffee3342019-08-27 12:03:00 -0700333 linkFile := rustDep.outputFile
334 if !linkFile.Valid() {
335 ctx.ModuleErrorf("Invalid output file when adding dep %q to %q", depName, ctx.ModuleName())
336 }
337
338 switch depTag {
339 case dylibDepTag:
340 dylib, ok := rustDep.compiler.(libraryInterface)
341 if !ok || !dylib.dylib() {
342 ctx.ModuleErrorf("mod %q not an dylib library", depName)
343 return
344 }
345 directDylibDeps = append(directDylibDeps, rustDep)
346 mod.Properties.AndroidMkDylibs = append(mod.Properties.AndroidMkDylibs, depName)
347 case rlibDepTag:
348 rlib, ok := rustDep.compiler.(libraryInterface)
349 if !ok || !rlib.rlib() {
350 ctx.ModuleErrorf("mod %q not an rlib library", depName)
351 return
352 }
353 directRlibDeps = append(directRlibDeps, rustDep)
354 mod.Properties.AndroidMkRlibs = append(mod.Properties.AndroidMkRlibs, depName)
355 case procMacroDepTag:
356 directProcMacroDeps = append(directProcMacroDeps, rustDep)
357 mod.Properties.AndroidMkProcMacroLibs = append(mod.Properties.AndroidMkProcMacroLibs, depName)
358 }
359
360 //Append the dependencies exportedDirs
361 if lib, ok := rustDep.compiler.(*libraryDecorator); ok {
362 depPaths.linkDirs = append(depPaths.linkDirs, lib.exportedDirs()...)
363 depPaths.depFlags = append(depPaths.depFlags, lib.exportedDepFlags()...)
364 } else if procMacro, ok := rustDep.compiler.(*libraryDecorator); ok {
365 depPaths.linkDirs = append(depPaths.linkDirs, procMacro.exportedDirs()...)
366 depPaths.depFlags = append(depPaths.depFlags, procMacro.exportedDepFlags()...)
367 }
368
369 // Append this dependencies output to this mod's linkDirs so they can be exported to dependencies
370 // This can be probably be refactored by defining a common exporter interface similar to cc's
371 if depTag == dylibDepTag || depTag == rlibDepTag || depTag == procMacroDepTag {
372 linkDir := linkPathFromFilePath(linkFile.Path())
373 if lib, ok := mod.compiler.(*libraryDecorator); ok {
374 lib.linkDirs = append(lib.linkDirs, linkDir)
375 } else if procMacro, ok := mod.compiler.(*procMacroDecorator); ok {
376 procMacro.linkDirs = append(procMacro.linkDirs, linkDir)
377 }
378 }
379
380 } else if ccDep, ok := dep.(*cc.Module); ok {
Ivan Lozanoffee3342019-08-27 12:03:00 -0700381 //Handle C dependencies
Ivan Lozano70e0a072019-09-13 14:23:15 -0700382
383 if ccDep.Target().Os != ctx.Os() {
384 ctx.ModuleErrorf("OS mismatch between %q and %q", ctx.ModuleName(), depName)
385 return
386 }
387 if ccDep.Target().Arch.ArchType != ctx.Arch().ArchType {
388 ctx.ModuleErrorf("Arch mismatch between %q and %q", ctx.ModuleName(), depName)
389 return
390 }
391
Ivan Lozanoffee3342019-08-27 12:03:00 -0700392 linkFile := ccDep.OutputFile()
393 linkPath := linkPathFromFilePath(linkFile.Path())
394 libName := libNameFromFilePath(linkFile.Path())
395 if !linkFile.Valid() {
396 ctx.ModuleErrorf("Invalid output file when adding dep %q to %q", depName, ctx.ModuleName())
397 }
398
399 exportDep := false
400
401 switch depTag {
402 case cc.StaticDepTag():
403 depPaths.linkDirs = append(depPaths.linkDirs, linkPath)
404 depPaths.depFlags = append(depPaths.depFlags, "-l"+libName)
405 directStaticLibDeps = append(directStaticLibDeps, ccDep)
406 mod.Properties.AndroidMkStaticLibs = append(mod.Properties.AndroidMkStaticLibs, depName)
407 case cc.SharedDepTag():
408 depPaths.linkDirs = append(depPaths.linkDirs, linkPath)
409 depPaths.depFlags = append(depPaths.depFlags, "-l"+libName)
410 directSharedLibDeps = append(directSharedLibDeps, ccDep)
411 mod.Properties.AndroidMkSharedLibs = append(mod.Properties.AndroidMkSharedLibs, depName)
412 exportDep = true
413 }
414
415 // Make sure these dependencies are propagated
416 if lib, ok := mod.compiler.(*libraryDecorator); ok && (exportDep || lib.rlib()) {
417 lib.linkDirs = append(lib.linkDirs, linkPath)
418 lib.depFlags = append(lib.depFlags, "-l"+libName)
419 } else if procMacro, ok := mod.compiler.(*procMacroDecorator); ok && exportDep {
420 procMacro.linkDirs = append(procMacro.linkDirs, linkPath)
421 procMacro.depFlags = append(procMacro.depFlags, "-l"+libName)
422 }
423
424 }
425 })
426
427 var rlibDepFiles RustLibraries
428 for _, dep := range directRlibDeps {
429 rlibDepFiles = append(rlibDepFiles, RustLibrary{Path: dep.outputFile.Path(), CrateName: dep.CrateName()})
430 }
431 var dylibDepFiles RustLibraries
432 for _, dep := range directDylibDeps {
433 dylibDepFiles = append(dylibDepFiles, RustLibrary{Path: dep.outputFile.Path(), CrateName: dep.CrateName()})
434 }
435 var procMacroDepFiles RustLibraries
436 for _, dep := range directProcMacroDeps {
437 procMacroDepFiles = append(procMacroDepFiles, RustLibrary{Path: dep.outputFile.Path(), CrateName: dep.CrateName()})
438 }
439
440 var staticLibDepFiles android.Paths
441 for _, dep := range directStaticLibDeps {
442 staticLibDepFiles = append(staticLibDepFiles, dep.OutputFile().Path())
443 }
444
445 var sharedLibDepFiles android.Paths
446 for _, dep := range directSharedLibDeps {
447 sharedLibDepFiles = append(sharedLibDepFiles, dep.OutputFile().Path())
448 }
449
450 depPaths.RLibs = append(depPaths.RLibs, rlibDepFiles...)
451 depPaths.DyLibs = append(depPaths.DyLibs, dylibDepFiles...)
452 depPaths.SharedLibs = append(depPaths.SharedLibs, sharedLibDepFiles...)
453 depPaths.StaticLibs = append(depPaths.StaticLibs, staticLibDepFiles...)
454 depPaths.ProcMacros = append(depPaths.ProcMacros, procMacroDepFiles...)
455
456 // Dedup exported flags from dependencies
457 depPaths.linkDirs = android.FirstUniqueStrings(depPaths.linkDirs)
458 depPaths.depFlags = android.FirstUniqueStrings(depPaths.depFlags)
459
460 return depPaths
461}
462
463func linkPathFromFilePath(filepath android.Path) string {
464 return strings.Split(filepath.String(), filepath.Base())[0]
465}
466func libNameFromFilePath(filepath android.Path) string {
467 libName := strings.Split(filepath.Base(), filepath.Ext())[0]
468 if strings.Contains(libName, "lib") {
469 libName = strings.Split(libName, "lib")[1]
470 }
471 return libName
472}
473func (mod *Module) DepsMutator(actx android.BottomUpMutatorContext) {
474 ctx := &depsContext{
475 BottomUpMutatorContext: actx,
476 moduleContextImpl: moduleContextImpl{
477 mod: mod,
478 },
479 }
480 ctx.ctx = ctx
481
482 deps := mod.deps(ctx)
483
484 actx.AddVariationDependencies([]blueprint.Variation{{Mutator: "rust_libraries", Variation: "rlib"}}, rlibDepTag, deps.Rlibs...)
485 actx.AddVariationDependencies([]blueprint.Variation{{Mutator: "rust_libraries", Variation: "dylib"}}, dylibDepTag, deps.Dylibs...)
486
487 ccDepVariations := []blueprint.Variation{}
488 ccDepVariations = append(ccDepVariations, blueprint.Variation{Mutator: "version", Variation: ""})
489 if !mod.Host() {
490 ccDepVariations = append(ccDepVariations, blueprint.Variation{Mutator: "image", Variation: "core"})
491 }
492 actx.AddVariationDependencies(append(ccDepVariations, blueprint.Variation{Mutator: "link", Variation: "shared"}), cc.SharedDepTag(), deps.SharedLibs...)
493 actx.AddVariationDependencies(append(ccDepVariations, blueprint.Variation{Mutator: "link", Variation: "static"}), cc.StaticDepTag(), deps.StaticLibs...)
494 actx.AddDependency(mod, procMacroDepTag, deps.ProcMacros...)
495}
496
497func (mod *Module) Name() string {
498 name := mod.ModuleBase.Name()
499 if p, ok := mod.compiler.(interface {
500 Name(string) string
501 }); ok {
502 name = p.Name(name)
503 }
504 return name
505}
506
507var Bool = proptools.Bool
508var BoolDefault = proptools.BoolDefault
509var String = proptools.String
510var StringPtr = proptools.StringPtr