blob: 359e126d98404bdf4ed7ecabd3cc3d962628858b [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
Ivan Lozanoffee3342019-08-27 12:03:00 -0700324 linkFile := rustDep.outputFile
325 if !linkFile.Valid() {
326 ctx.ModuleErrorf("Invalid output file when adding dep %q to %q", depName, ctx.ModuleName())
327 }
328
329 switch depTag {
330 case dylibDepTag:
331 dylib, ok := rustDep.compiler.(libraryInterface)
332 if !ok || !dylib.dylib() {
333 ctx.ModuleErrorf("mod %q not an dylib library", depName)
334 return
335 }
336 directDylibDeps = append(directDylibDeps, rustDep)
337 mod.Properties.AndroidMkDylibs = append(mod.Properties.AndroidMkDylibs, depName)
338 case rlibDepTag:
339 rlib, ok := rustDep.compiler.(libraryInterface)
340 if !ok || !rlib.rlib() {
341 ctx.ModuleErrorf("mod %q not an rlib library", depName)
342 return
343 }
344 directRlibDeps = append(directRlibDeps, rustDep)
345 mod.Properties.AndroidMkRlibs = append(mod.Properties.AndroidMkRlibs, depName)
346 case procMacroDepTag:
347 directProcMacroDeps = append(directProcMacroDeps, rustDep)
348 mod.Properties.AndroidMkProcMacroLibs = append(mod.Properties.AndroidMkProcMacroLibs, depName)
349 }
350
351 //Append the dependencies exportedDirs
352 if lib, ok := rustDep.compiler.(*libraryDecorator); ok {
353 depPaths.linkDirs = append(depPaths.linkDirs, lib.exportedDirs()...)
354 depPaths.depFlags = append(depPaths.depFlags, lib.exportedDepFlags()...)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700355 }
356
357 // Append this dependencies output to this mod's linkDirs so they can be exported to dependencies
358 // This can be probably be refactored by defining a common exporter interface similar to cc's
359 if depTag == dylibDepTag || depTag == rlibDepTag || depTag == procMacroDepTag {
360 linkDir := linkPathFromFilePath(linkFile.Path())
361 if lib, ok := mod.compiler.(*libraryDecorator); ok {
362 lib.linkDirs = append(lib.linkDirs, linkDir)
363 } else if procMacro, ok := mod.compiler.(*procMacroDecorator); ok {
364 procMacro.linkDirs = append(procMacro.linkDirs, linkDir)
365 }
366 }
367
368 } else if ccDep, ok := dep.(*cc.Module); ok {
Ivan Lozanoffee3342019-08-27 12:03:00 -0700369 //Handle C dependencies
Ivan Lozano70e0a072019-09-13 14:23:15 -0700370
371 if ccDep.Target().Os != ctx.Os() {
372 ctx.ModuleErrorf("OS mismatch between %q and %q", ctx.ModuleName(), depName)
373 return
374 }
375 if ccDep.Target().Arch.ArchType != ctx.Arch().ArchType {
376 ctx.ModuleErrorf("Arch mismatch between %q and %q", ctx.ModuleName(), depName)
377 return
378 }
379
Ivan Lozanoffee3342019-08-27 12:03:00 -0700380 linkFile := ccDep.OutputFile()
381 linkPath := linkPathFromFilePath(linkFile.Path())
382 libName := libNameFromFilePath(linkFile.Path())
383 if !linkFile.Valid() {
384 ctx.ModuleErrorf("Invalid output file when adding dep %q to %q", depName, ctx.ModuleName())
385 }
386
387 exportDep := false
388
389 switch depTag {
390 case cc.StaticDepTag():
391 depPaths.linkDirs = append(depPaths.linkDirs, linkPath)
392 depPaths.depFlags = append(depPaths.depFlags, "-l"+libName)
393 directStaticLibDeps = append(directStaticLibDeps, ccDep)
394 mod.Properties.AndroidMkStaticLibs = append(mod.Properties.AndroidMkStaticLibs, depName)
395 case cc.SharedDepTag():
396 depPaths.linkDirs = append(depPaths.linkDirs, linkPath)
397 depPaths.depFlags = append(depPaths.depFlags, "-l"+libName)
398 directSharedLibDeps = append(directSharedLibDeps, ccDep)
399 mod.Properties.AndroidMkSharedLibs = append(mod.Properties.AndroidMkSharedLibs, depName)
400 exportDep = true
401 }
402
403 // Make sure these dependencies are propagated
404 if lib, ok := mod.compiler.(*libraryDecorator); ok && (exportDep || lib.rlib()) {
405 lib.linkDirs = append(lib.linkDirs, linkPath)
406 lib.depFlags = append(lib.depFlags, "-l"+libName)
407 } else if procMacro, ok := mod.compiler.(*procMacroDecorator); ok && exportDep {
408 procMacro.linkDirs = append(procMacro.linkDirs, linkPath)
409 procMacro.depFlags = append(procMacro.depFlags, "-l"+libName)
410 }
411
412 }
413 })
414
415 var rlibDepFiles RustLibraries
416 for _, dep := range directRlibDeps {
417 rlibDepFiles = append(rlibDepFiles, RustLibrary{Path: dep.outputFile.Path(), CrateName: dep.CrateName()})
418 }
419 var dylibDepFiles RustLibraries
420 for _, dep := range directDylibDeps {
421 dylibDepFiles = append(dylibDepFiles, RustLibrary{Path: dep.outputFile.Path(), CrateName: dep.CrateName()})
422 }
423 var procMacroDepFiles RustLibraries
424 for _, dep := range directProcMacroDeps {
425 procMacroDepFiles = append(procMacroDepFiles, RustLibrary{Path: dep.outputFile.Path(), CrateName: dep.CrateName()})
426 }
427
428 var staticLibDepFiles android.Paths
429 for _, dep := range directStaticLibDeps {
430 staticLibDepFiles = append(staticLibDepFiles, dep.OutputFile().Path())
431 }
432
433 var sharedLibDepFiles android.Paths
434 for _, dep := range directSharedLibDeps {
435 sharedLibDepFiles = append(sharedLibDepFiles, dep.OutputFile().Path())
436 }
437
438 depPaths.RLibs = append(depPaths.RLibs, rlibDepFiles...)
439 depPaths.DyLibs = append(depPaths.DyLibs, dylibDepFiles...)
440 depPaths.SharedLibs = append(depPaths.SharedLibs, sharedLibDepFiles...)
441 depPaths.StaticLibs = append(depPaths.StaticLibs, staticLibDepFiles...)
442 depPaths.ProcMacros = append(depPaths.ProcMacros, procMacroDepFiles...)
443
444 // Dedup exported flags from dependencies
445 depPaths.linkDirs = android.FirstUniqueStrings(depPaths.linkDirs)
446 depPaths.depFlags = android.FirstUniqueStrings(depPaths.depFlags)
447
448 return depPaths
449}
450
451func linkPathFromFilePath(filepath android.Path) string {
452 return strings.Split(filepath.String(), filepath.Base())[0]
453}
454func libNameFromFilePath(filepath android.Path) string {
455 libName := strings.Split(filepath.Base(), filepath.Ext())[0]
456 if strings.Contains(libName, "lib") {
457 libName = strings.Split(libName, "lib")[1]
458 }
459 return libName
460}
461func (mod *Module) DepsMutator(actx android.BottomUpMutatorContext) {
462 ctx := &depsContext{
463 BottomUpMutatorContext: actx,
464 moduleContextImpl: moduleContextImpl{
465 mod: mod,
466 },
467 }
468 ctx.ctx = ctx
469
470 deps := mod.deps(ctx)
471
472 actx.AddVariationDependencies([]blueprint.Variation{{Mutator: "rust_libraries", Variation: "rlib"}}, rlibDepTag, deps.Rlibs...)
473 actx.AddVariationDependencies([]blueprint.Variation{{Mutator: "rust_libraries", Variation: "dylib"}}, dylibDepTag, deps.Dylibs...)
474
475 ccDepVariations := []blueprint.Variation{}
476 ccDepVariations = append(ccDepVariations, blueprint.Variation{Mutator: "version", Variation: ""})
477 if !mod.Host() {
478 ccDepVariations = append(ccDepVariations, blueprint.Variation{Mutator: "image", Variation: "core"})
479 }
480 actx.AddVariationDependencies(append(ccDepVariations, blueprint.Variation{Mutator: "link", Variation: "shared"}), cc.SharedDepTag(), deps.SharedLibs...)
481 actx.AddVariationDependencies(append(ccDepVariations, blueprint.Variation{Mutator: "link", Variation: "static"}), cc.StaticDepTag(), deps.StaticLibs...)
Ivan Lozano5ca5ef62019-09-23 10:10:40 -0700482
483 // proc_macros are compiler plugins, and so we need the host arch variant as a dependendcy.
484 actx.AddFarVariationDependencies([]blueprint.Variation{{Mutator: "arch", Variation: ctx.Config().BuildOsVariant}}, procMacroDepTag, deps.ProcMacros...)
Ivan Lozanoffee3342019-08-27 12:03:00 -0700485}
486
487func (mod *Module) Name() string {
488 name := mod.ModuleBase.Name()
489 if p, ok := mod.compiler.(interface {
490 Name(string) string
491 }); ok {
492 name = p.Name(name)
493 }
494 return name
495}
496
497var Bool = proptools.Bool
498var BoolDefault = proptools.BoolDefault
499var String = proptools.String
500var StringPtr = proptools.StringPtr