blob: 5a2514e47bb23cb2e071abbfc6dd0b9c0a0f3dd6 [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
32 rustModuleTypes := []string{
33 "rust_binary",
34 "rust_binary_host",
35 "rust_library",
36 "rust_library_dylib",
37 "rust_library_rlib",
38 "rust_library_host",
39 "rust_library_host_dylib",
40 "rust_library_host_rlib",
41 "rust_proc_macro",
42 }
43
44 rustAllowedPaths := []string{
45 "external/rust/crates",
46 "external/crosvm",
47 "external/adhd",
48 }
49
50 android.AddNeverAllowRules(
51 android.NeverAllow().
52 NotIn(rustAllowedPaths...).
53 ModuleType(rustModuleTypes...))
54
55 android.RegisterModuleType("rust_defaults", defaultsFactory)
56 android.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
57 ctx.BottomUp("rust_libraries", LibraryMutator).Parallel()
58 })
59 pctx.Import("android/soong/rust/config")
60}
61
62type Flags struct {
63 GlobalFlags []string // Flags that apply globally
64 RustFlags []string // Flags that apply to rust
65 LinkFlags []string // Flags that apply to linker
66 RustFlagsDeps android.Paths // Files depended on by compiler flags
67 Toolchain config.Toolchain
68}
69
70type BaseProperties struct {
71 AndroidMkRlibs []string
72 AndroidMkDylibs []string
73 AndroidMkProcMacroLibs []string
74 AndroidMkSharedLibs []string
75 AndroidMkStaticLibs []string
76}
77
78type Module struct {
79 android.ModuleBase
80 android.DefaultableModuleBase
81
82 Properties BaseProperties
83
84 hod android.HostOrDeviceSupported
85 multilib android.Multilib
86
87 compiler compiler
88 cachedToolchain config.Toolchain
89 subAndroidMkOnce map[subAndroidMkProvider]bool
90 outputFile android.OptionalPath
91}
92
93type Deps struct {
94 Dylibs []string
95 Rlibs []string
96 ProcMacros []string
97 SharedLibs []string
98 StaticLibs []string
99
100 CrtBegin, CrtEnd string
101}
102
103type PathDeps struct {
104 DyLibs RustLibraries
105 RLibs RustLibraries
106 SharedLibs android.Paths
107 StaticLibs android.Paths
108 ProcMacros RustLibraries
109 linkDirs []string
110 depFlags []string
111 //ReexportedDeps android.Paths
112}
113
114type RustLibraries []RustLibrary
115
116type RustLibrary struct {
117 Path android.Path
118 CrateName string
119}
120
121type compiler interface {
122 compilerFlags(ctx ModuleContext, flags Flags) Flags
123 compilerProps() []interface{}
124 compile(ctx ModuleContext, flags Flags, deps PathDeps) android.Path
125 compilerDeps(ctx DepsContext, deps Deps) Deps
126 crateName() string
127
128 install(ctx ModuleContext, path android.Path)
129 relativeInstallPath() string
130}
131
132func defaultsFactory() android.Module {
133 return DefaultsFactory()
134}
135
136type Defaults struct {
137 android.ModuleBase
138 android.DefaultsModuleBase
139}
140
141func DefaultsFactory(props ...interface{}) android.Module {
142 module := &Defaults{}
143
144 module.AddProperties(props...)
145 module.AddProperties(
146 &BaseProperties{},
147 &BaseCompilerProperties{},
148 &BinaryCompilerProperties{},
149 &LibraryCompilerProperties{},
150 &ProcMacroCompilerProperties{},
151 &PrebuiltProperties{},
152 )
153
154 android.InitDefaultsModule(module)
155 return module
156}
157
158func (mod *Module) CrateName() string {
159 if mod.compiler != nil && mod.compiler.crateName() != "" {
160 return mod.compiler.crateName()
161 }
162 // Default crate names replace '-' in the name to '_'
163 return strings.Replace(mod.BaseModuleName(), "-", "_", -1)
164}
165
166func (mod *Module) Init() android.Module {
167 mod.AddProperties(&mod.Properties)
168
169 if mod.compiler != nil {
170 mod.AddProperties(mod.compiler.compilerProps()...)
171 }
172 android.InitAndroidArchModule(mod, mod.hod, mod.multilib)
173
174 android.InitDefaultableModule(mod)
175
176 return mod
177}
178
179func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
180 return &Module{
181 hod: hod,
182 multilib: multilib,
183 }
184}
185func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
186 module := newBaseModule(hod, multilib)
187 return module
188}
189
190type ModuleContext interface {
191 android.ModuleContext
192 ModuleContextIntf
193}
194
195type BaseModuleContext interface {
196 android.BaseModuleContext
197 ModuleContextIntf
198}
199
200type DepsContext interface {
201 android.BottomUpMutatorContext
202 ModuleContextIntf
203}
204
205type ModuleContextIntf interface {
206 toolchain() config.Toolchain
207 baseModuleName() string
208 CrateName() string
209}
210
211type depsContext struct {
212 android.BottomUpMutatorContext
213 moduleContextImpl
214}
215
216type moduleContext struct {
217 android.ModuleContext
218 moduleContextImpl
219}
220
221type moduleContextImpl struct {
222 mod *Module
223 ctx BaseModuleContext
224}
225
226func (ctx *moduleContextImpl) toolchain() config.Toolchain {
227 return ctx.mod.toolchain(ctx.ctx)
228}
229
230func (mod *Module) toolchain(ctx android.BaseModuleContext) config.Toolchain {
231 if mod.cachedToolchain == nil {
232 mod.cachedToolchain = config.FindToolchain(ctx.Os(), ctx.Arch())
233 }
234 return mod.cachedToolchain
235}
236
237func (d *Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
238}
239
240func (mod *Module) GenerateAndroidBuildActions(actx android.ModuleContext) {
241 ctx := &moduleContext{
242 ModuleContext: actx,
243 moduleContextImpl: moduleContextImpl{
244 mod: mod,
245 },
246 }
247 ctx.ctx = ctx
248
249 toolchain := mod.toolchain(ctx)
250
251 if !toolchain.Supported() {
252 // This toolchain's unsupported, there's nothing to do for this mod.
253 return
254 }
255
256 deps := mod.depsToPaths(ctx)
257 flags := Flags{
258 Toolchain: toolchain,
259 }
260
261 if mod.compiler != nil {
262 flags = mod.compiler.compilerFlags(ctx, flags)
263 outputFile := mod.compiler.compile(ctx, flags, deps)
264 mod.outputFile = android.OptionalPathForPath(outputFile)
265 mod.compiler.install(ctx, mod.outputFile.Path())
266 }
267}
268
269func (mod *Module) deps(ctx DepsContext) Deps {
270 deps := Deps{}
271
272 if mod.compiler != nil {
273 deps = mod.compiler.compilerDeps(ctx, deps)
274 }
275
276 deps.Rlibs = android.LastUniqueStrings(deps.Rlibs)
277 deps.Dylibs = android.LastUniqueStrings(deps.Dylibs)
278 deps.ProcMacros = android.LastUniqueStrings(deps.ProcMacros)
279 deps.SharedLibs = android.LastUniqueStrings(deps.SharedLibs)
280 deps.StaticLibs = android.LastUniqueStrings(deps.StaticLibs)
281
282 return deps
283
284}
285
286func (ctx *moduleContextImpl) baseModuleName() string {
287 return ctx.mod.ModuleBase.BaseModuleName()
288}
289
290func (ctx *moduleContextImpl) CrateName() string {
291 return ctx.mod.CrateName()
292}
293
294type dependencyTag struct {
295 blueprint.BaseDependencyTag
296 name string
297 library bool
298 proc_macro bool
299}
300
301var (
302 rlibDepTag = dependencyTag{name: "rlibTag", library: true}
303 dylibDepTag = dependencyTag{name: "dylib", library: true}
304 procMacroDepTag = dependencyTag{name: "procMacro", proc_macro: true}
305)
306
307func (mod *Module) depsToPaths(ctx android.ModuleContext) PathDeps {
308 var depPaths PathDeps
309
310 directRlibDeps := []*Module{}
311 directDylibDeps := []*Module{}
312 directProcMacroDeps := []*Module{}
313 directSharedLibDeps := []*(cc.Module){}
314 directStaticLibDeps := []*(cc.Module){}
315
316 ctx.VisitDirectDeps(func(dep android.Module) {
317 depName := ctx.OtherModuleName(dep)
318 depTag := ctx.OtherModuleDependencyTag(dep)
319 if dep.Target().Os != ctx.Os() {
320 ctx.ModuleErrorf("OS mismatch between %q and %q", ctx.ModuleName(), depName)
321 return
322 }
323 if dep.Target().Arch.ArchType != ctx.Arch().ArchType {
324 ctx.ModuleErrorf("Arch mismatch between %q and %q", ctx.ModuleName(), depName)
325 return
326 }
327
328 if rustDep, ok := dep.(*Module); ok {
329 //Handle Rust Modules
330 linkFile := rustDep.outputFile
331 if !linkFile.Valid() {
332 ctx.ModuleErrorf("Invalid output file when adding dep %q to %q", depName, ctx.ModuleName())
333 }
334
335 switch depTag {
336 case dylibDepTag:
337 dylib, ok := rustDep.compiler.(libraryInterface)
338 if !ok || !dylib.dylib() {
339 ctx.ModuleErrorf("mod %q not an dylib library", depName)
340 return
341 }
342 directDylibDeps = append(directDylibDeps, rustDep)
343 mod.Properties.AndroidMkDylibs = append(mod.Properties.AndroidMkDylibs, depName)
344 case rlibDepTag:
345 rlib, ok := rustDep.compiler.(libraryInterface)
346 if !ok || !rlib.rlib() {
347 ctx.ModuleErrorf("mod %q not an rlib library", depName)
348 return
349 }
350 directRlibDeps = append(directRlibDeps, rustDep)
351 mod.Properties.AndroidMkRlibs = append(mod.Properties.AndroidMkRlibs, depName)
352 case procMacroDepTag:
353 directProcMacroDeps = append(directProcMacroDeps, rustDep)
354 mod.Properties.AndroidMkProcMacroLibs = append(mod.Properties.AndroidMkProcMacroLibs, depName)
355 }
356
357 //Append the dependencies exportedDirs
358 if lib, ok := rustDep.compiler.(*libraryDecorator); ok {
359 depPaths.linkDirs = append(depPaths.linkDirs, lib.exportedDirs()...)
360 depPaths.depFlags = append(depPaths.depFlags, lib.exportedDepFlags()...)
361 } else if procMacro, ok := rustDep.compiler.(*libraryDecorator); ok {
362 depPaths.linkDirs = append(depPaths.linkDirs, procMacro.exportedDirs()...)
363 depPaths.depFlags = append(depPaths.depFlags, procMacro.exportedDepFlags()...)
364 }
365
366 // Append this dependencies output to this mod's linkDirs so they can be exported to dependencies
367 // This can be probably be refactored by defining a common exporter interface similar to cc's
368 if depTag == dylibDepTag || depTag == rlibDepTag || depTag == procMacroDepTag {
369 linkDir := linkPathFromFilePath(linkFile.Path())
370 if lib, ok := mod.compiler.(*libraryDecorator); ok {
371 lib.linkDirs = append(lib.linkDirs, linkDir)
372 } else if procMacro, ok := mod.compiler.(*procMacroDecorator); ok {
373 procMacro.linkDirs = append(procMacro.linkDirs, linkDir)
374 }
375 }
376
377 } else if ccDep, ok := dep.(*cc.Module); ok {
378
379 //Handle C dependencies
380 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...)
482 actx.AddDependency(mod, procMacroDepTag, deps.ProcMacros...)
483}
484
485func (mod *Module) Name() string {
486 name := mod.ModuleBase.Name()
487 if p, ok := mod.compiler.(interface {
488 Name(string) string
489 }); ok {
490 name = p.Name(name)
491 }
492 return name
493}
494
495var Bool = proptools.Bool
496var BoolDefault = proptools.BoolDefault
497var String = proptools.String
498var StringPtr = proptools.StringPtr