blob: 1284da46a572352d8ccfb0066902f176a4aef374 [file] [log] [blame]
Hao Chen1c8ea5b2023-10-20 23:03:45 +00001// Copyright 2024 Google Inc. All rights reserved.
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 cc
16
17import (
Hao Chen1c8ea5b2023-10-20 23:03:45 +000018 "bytes"
19 _ "embed"
20 "fmt"
21 "path/filepath"
22 "slices"
23 "sort"
24 "strings"
25 "text/template"
26
mrziwangf95cfa62024-06-18 10:11:39 -070027 "android/soong/android"
28
Hao Chen1c8ea5b2023-10-20 23:03:45 +000029 "github.com/google/blueprint"
30 "github.com/google/blueprint/proptools"
31)
32
33const veryVerbose bool = false
34
35//go:embed cmake_main.txt
36var templateCmakeMainRaw string
37var templateCmakeMain *template.Template = parseTemplate(templateCmakeMainRaw)
38
39//go:embed cmake_module_cc.txt
40var templateCmakeModuleCcRaw string
41var templateCmakeModuleCc *template.Template = parseTemplate(templateCmakeModuleCcRaw)
42
43//go:embed cmake_module_aidl.txt
44var templateCmakeModuleAidlRaw string
45var templateCmakeModuleAidl *template.Template = parseTemplate(templateCmakeModuleAidlRaw)
46
47//go:embed cmake_ext_add_aidl_library.txt
48var cmakeExtAddAidlLibrary string
49
50//go:embed cmake_ext_append_flags.txt
51var cmakeExtAppendFlags string
52
53var defaultUnportableFlags []string = []string{
54 "-Wno-class-memaccess",
55 "-Wno-exit-time-destructors",
56 "-Wno-inconsistent-missing-override",
57 "-Wreorder-init-list",
58 "-Wno-reorder-init-list",
59 "-Wno-restrict",
60 "-Wno-stringop-overread",
61 "-Wno-subobject-linkage",
62}
63
64var ignoredSystemLibs []string = []string{
Tomasz Wasilczyk2493fcc2024-06-20 15:29:09 -070065 "crtbegin_dynamic",
66 "crtend_android",
67 "libc",
Hao Chen1c8ea5b2023-10-20 23:03:45 +000068 "libc++",
69 "libc++_static",
Tomasz Wasilczyk2493fcc2024-06-20 15:29:09 -070070 "libdl",
71 "libm",
Hao Chen1c8ea5b2023-10-20 23:03:45 +000072 "prebuilt_libclang_rt.builtins",
73 "prebuilt_libclang_rt.ubsan_minimal",
74}
75
76// Mapping entry between Android's library name and the one used when building outside Android tree.
77type LibraryMappingProperty struct {
78 // Android library name.
79 Android_name string
80
81 // Library name used when building outside Android.
82 Mapped_name string
83
84 // If the make file is already present in Android source tree, specify its location.
85 Package_pregenerated string
86
87 // If the package is expected to be installed on the build host OS, specify its name.
88 Package_system string
89}
90
91type CmakeSnapshotProperties struct {
92 // Modules to add to the snapshot package. Their dependencies are pulled in automatically.
93 Modules []string
94
95 // Host prebuilts to bundle with the snapshot. These are tools needed to build outside Android.
96 Prebuilts []string
97
98 // Global cflags to add when building outside Android.
99 Cflags []string
100
101 // Flags to skip when building outside Android.
102 Cflags_ignored []string
103
104 // Mapping between library names used in Android tree and externally.
105 Library_mapping []LibraryMappingProperty
106
107 // List of cflags that are not portable between compilers that could potentially be used to
108 // build a generated package. If left empty, it's initialized with a default list.
109 Unportable_flags []string
110
111 // Whether to include source code as part of the snapshot package.
112 Include_sources bool
113}
114
115var cmakeSnapshotSourcesProvider = blueprint.NewProvider[android.Paths]()
116
117type CmakeSnapshot struct {
118 android.ModuleBase
119
120 Properties CmakeSnapshotProperties
121
122 zipPath android.WritablePath
123}
124
125type cmakeProcessedProperties struct {
126 LibraryMapping map[string]LibraryMappingProperty
127 PregeneratedPackages []string
128 SystemPackages []string
129}
130
131type cmakeSnapshotDependencyTag struct {
132 blueprint.BaseDependencyTag
133 name string
134}
135
136var (
137 cmakeSnapshotModuleTag = cmakeSnapshotDependencyTag{name: "cmake-snapshot-module"}
138 cmakeSnapshotPrebuiltTag = cmakeSnapshotDependencyTag{name: "cmake-snapshot-prebuilt"}
139)
140
141func parseTemplate(templateContents string) *template.Template {
142 funcMap := template.FuncMap{
143 "setList": func(name string, nameSuffix string, itemPrefix string, items []string) string {
144 var list strings.Builder
145 list.WriteString("set(" + name + nameSuffix)
146 templateListBuilder(&list, itemPrefix, items)
147 return list.String()
148 },
149 "toStrings": func(files android.Paths) []string {
150 strings := make([]string, len(files))
151 for idx, file := range files {
152 strings[idx] = file.String()
153 }
154 return strings
155 },
156 "concat5": func(list1 []string, list2 []string, list3 []string, list4 []string, list5 []string) []string {
157 return append(append(append(append(list1, list2...), list3...), list4...), list5...)
158 },
159 "cflagsList": func(name string, nameSuffix string, flags []string,
160 unportableFlags []string, ignoredFlags []string) string {
161 if len(unportableFlags) == 0 {
162 unportableFlags = defaultUnportableFlags
163 }
164
165 var filteredPortable []string
166 var filteredUnportable []string
167 for _, flag := range flags {
168 if slices.Contains(ignoredFlags, flag) {
169 continue
170 } else if slices.Contains(unportableFlags, flag) {
171 filteredUnportable = append(filteredUnportable, flag)
172 } else {
173 filteredPortable = append(filteredPortable, flag)
174 }
175 }
176
177 var list strings.Builder
178
179 list.WriteString("set(" + name + nameSuffix)
180 templateListBuilder(&list, "", filteredPortable)
181
182 if len(filteredUnportable) > 0 {
183 list.WriteString("\nappend_cxx_flags_if_supported(" + name + nameSuffix)
184 templateListBuilder(&list, "", filteredUnportable)
185 }
186
187 return list.String()
188 },
189 "getSources": func(m *Module) android.Paths {
190 return m.compiler.(CompiledInterface).Srcs()
191 },
192 "getModuleType": getModuleType,
193 "getCompilerProperties": func(m *Module) BaseCompilerProperties {
194 return m.compiler.baseCompilerProps()
195 },
Cole Fauste96c16a2024-06-13 14:51:14 -0700196 "getCflagsProperty": func(ctx android.ModuleContext, m *Module) []string {
197 cflags := m.compiler.baseCompilerProps().Cflags
198 return cflags.GetOrDefault(ctx, nil)
199 },
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000200 "getLinkerProperties": func(m *Module) BaseLinkerProperties {
201 return m.linker.baseLinkerProps()
202 },
203 "getExtraLibs": getExtraLibs,
204 "getIncludeDirs": getIncludeDirs,
Tomasz Wasilczyk1e831bf2024-05-10 15:15:21 -0700205 "mapLibraries": func(ctx android.ModuleContext, m *Module, libs []string, mapping map[string]LibraryMappingProperty) []string {
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000206 var mappedLibs []string
207 for _, lib := range libs {
208 mappedLib, exists := mapping[lib]
209 if exists {
210 lib = mappedLib.Mapped_name
211 } else {
Tomasz Wasilczyk1e831bf2024-05-10 15:15:21 -0700212 if !ctx.OtherModuleExists(lib) {
213 ctx.OtherModuleErrorf(m, "Dependency %s doesn't exist", lib)
214 }
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000215 lib = "android::" + lib
216 }
217 if lib == "" {
218 continue
219 }
220 mappedLibs = append(mappedLibs, lib)
221 }
222 sort.Strings(mappedLibs)
223 mappedLibs = slices.Compact(mappedLibs)
224 return mappedLibs
225 },
Tomasz Wasilczyk1e831bf2024-05-10 15:15:21 -0700226 "getAidlSources": func(m *Module) []string {
227 aidlInterface := m.compiler.baseCompilerProps().AidlInterface
228 aidlRoot := aidlInterface.AidlRoot + string(filepath.Separator)
229 if aidlInterface.AidlRoot == "" {
230 aidlRoot = ""
231 }
232 var sources []string
233 for _, src := range aidlInterface.Sources {
234 if !strings.HasPrefix(src, aidlRoot) {
235 panic(fmt.Sprintf("Aidl source '%v' doesn't start with '%v'", src, aidlRoot))
236 }
237 sources = append(sources, src[len(aidlRoot):])
238 }
239 return sources
240 },
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000241 }
242
243 return template.Must(template.New("").Delims("<<", ">>").Funcs(funcMap).Parse(templateContents))
244}
245
246func sliceWithPrefix(prefix string, slice []string) []string {
247 output := make([]string, len(slice))
248 for i, elem := range slice {
249 output[i] = prefix + elem
250 }
251 return output
252}
253
254func templateListBuilder(builder *strings.Builder, itemPrefix string, items []string) {
255 if len(items) > 0 {
256 builder.WriteString("\n")
257 for _, item := range items {
258 builder.WriteString(" " + itemPrefix + item + "\n")
259 }
260 }
261 builder.WriteString(")")
262}
263
264func executeTemplate(templ *template.Template, buffer *bytes.Buffer, data any) string {
265 buffer.Reset()
266 if err := templ.Execute(buffer, data); err != nil {
267 panic(err)
268 }
269 output := strings.TrimSpace(buffer.String())
270 buffer.Reset()
271 return output
272}
273
274func (m *CmakeSnapshot) DepsMutator(ctx android.BottomUpMutatorContext) {
275 variations := []blueprint.Variation{
276 {"os", "linux_glibc"},
277 {"arch", "x86_64"},
278 }
279 ctx.AddVariationDependencies(variations, cmakeSnapshotModuleTag, m.Properties.Modules...)
Tomasz Wasilczyk2493fcc2024-06-20 15:29:09 -0700280
281 if len(m.Properties.Prebuilts) > 0 {
282 prebuilts := append(m.Properties.Prebuilts, "libc++")
283 ctx.AddVariationDependencies(variations, cmakeSnapshotPrebuiltTag, prebuilts...)
284 }
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000285}
286
287func (m *CmakeSnapshot) GenerateAndroidBuildActions(ctx android.ModuleContext) {
288 var templateBuffer bytes.Buffer
289 var pprop cmakeProcessedProperties
290 m.zipPath = android.PathForModuleOut(ctx, ctx.ModuleName()+".zip")
291
292 // Process Library_mapping for more efficient lookups
293 pprop.LibraryMapping = map[string]LibraryMappingProperty{}
294 for _, elem := range m.Properties.Library_mapping {
295 pprop.LibraryMapping[elem.Android_name] = elem
296
297 if elem.Package_pregenerated != "" {
298 pprop.PregeneratedPackages = append(pprop.PregeneratedPackages, elem.Package_pregenerated)
299 }
300 sort.Strings(pprop.PregeneratedPackages)
301 pprop.PregeneratedPackages = slices.Compact(pprop.PregeneratedPackages)
302
303 if elem.Package_system != "" {
304 pprop.SystemPackages = append(pprop.SystemPackages, elem.Package_system)
305 }
306 sort.Strings(pprop.SystemPackages)
307 pprop.SystemPackages = slices.Compact(pprop.SystemPackages)
308 }
309
310 // Generating CMakeLists.txt rules for all modules in dependency tree
311 moduleDirs := map[string][]string{}
312 sourceFiles := map[string]android.Path{}
313 visitedModules := map[string]bool{}
314 var pregeneratedModules []*Module
315 ctx.WalkDeps(func(dep_a android.Module, parent android.Module) bool {
316 moduleName := ctx.OtherModuleName(dep_a)
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000317 if visited := visitedModules[moduleName]; visited {
318 return false // visit only once
319 }
320 visitedModules[moduleName] = true
Tomasz Wasilczyk1e831bf2024-05-10 15:15:21 -0700321 dep, ok := dep_a.(*Module)
322 if !ok {
323 return false // not a cc module
324 }
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000325 if mapping, ok := pprop.LibraryMapping[moduleName]; ok {
326 if mapping.Package_pregenerated != "" {
327 pregeneratedModules = append(pregeneratedModules, dep)
328 }
329 return false // mapped to system or pregenerated (we'll handle these later)
330 }
331 if ctx.OtherModuleDependencyTag(dep) == cmakeSnapshotPrebuiltTag {
332 return false // we'll handle cmakeSnapshotPrebuiltTag later
333 }
334 if slices.Contains(ignoredSystemLibs, moduleName) {
335 return false // system libs built in-tree for Android
336 }
337 if dep.compiler == nil {
338 return false // unsupported module type (e.g. prebuilt)
339 }
340 isAidlModule := dep.compiler.baseCompilerProps().AidlInterface.Lang != ""
341
342 if !proptools.Bool(dep.Properties.Cmake_snapshot_supported) {
343 ctx.OtherModulePropertyErrorf(dep, "cmake_snapshot_supported",
344 "CMake snapshots not supported, despite being a dependency for %s",
345 ctx.OtherModuleName(parent))
346 return false
347 }
348
349 if veryVerbose {
350 fmt.Println("WalkDeps: " + ctx.OtherModuleName(parent) + " -> " + moduleName)
351 }
352
353 // Generate CMakeLists.txt fragment for this module
354 templateToUse := templateCmakeModuleCc
355 if isAidlModule {
356 templateToUse = templateCmakeModuleAidl
357 }
358 moduleFragment := executeTemplate(templateToUse, &templateBuffer, struct {
359 Ctx *android.ModuleContext
360 M *Module
361 Snapshot *CmakeSnapshot
362 Pprop *cmakeProcessedProperties
363 }{
364 &ctx,
365 dep,
366 m,
367 &pprop,
368 })
369 moduleDir := ctx.OtherModuleDir(dep)
370 moduleDirs[moduleDir] = append(moduleDirs[moduleDir], moduleFragment)
371
372 if m.Properties.Include_sources {
373 files, _ := android.OtherModuleProvider(ctx, dep, cmakeSnapshotSourcesProvider)
374 for _, file := range files {
375 sourceFiles[file.String()] = file
376 }
377 }
378
379 // if it's AIDL module, no need to dive into their dependencies
380 return !isAidlModule
381 })
382
383 // Enumerate sources for pregenerated modules
384 if m.Properties.Include_sources {
385 for _, dep := range pregeneratedModules {
386 if !proptools.Bool(dep.Properties.Cmake_snapshot_supported) {
387 ctx.OtherModulePropertyErrorf(dep, "cmake_snapshot_supported",
388 "Pregenerated CMake snapshots not supported, despite being requested for %s",
389 ctx.ModuleName())
390 continue
391 }
392
393 files, _ := android.OtherModuleProvider(ctx, dep, cmakeSnapshotSourcesProvider)
394 for _, file := range files {
395 sourceFiles[file.String()] = file
396 }
397 }
398 }
399
400 // Merging CMakeLists.txt contents for every module directory
401 var makefilesList android.Paths
402 for moduleDir, fragments := range moduleDirs {
403 moduleCmakePath := android.PathForModuleGen(ctx, moduleDir, "CMakeLists.txt")
404 makefilesList = append(makefilesList, moduleCmakePath)
405 sort.Strings(fragments)
406 android.WriteFileRule(ctx, moduleCmakePath, strings.Join(fragments, "\n\n\n"))
407 }
408
409 // Generating top-level CMakeLists.txt
410 mainCmakePath := android.PathForModuleGen(ctx, "CMakeLists.txt")
411 makefilesList = append(makefilesList, mainCmakePath)
412 mainContents := executeTemplate(templateCmakeMain, &templateBuffer, struct {
413 Ctx *android.ModuleContext
414 M *CmakeSnapshot
415 ModuleDirs map[string][]string
416 Pprop *cmakeProcessedProperties
417 }{
418 &ctx,
419 m,
420 moduleDirs,
421 &pprop,
422 })
423 android.WriteFileRule(ctx, mainCmakePath, mainContents)
424
425 // Generating CMake extensions
426 extPath := android.PathForModuleGen(ctx, "cmake", "AppendCxxFlagsIfSupported.cmake")
427 makefilesList = append(makefilesList, extPath)
428 android.WriteFileRuleVerbatim(ctx, extPath, cmakeExtAppendFlags)
429 extPath = android.PathForModuleGen(ctx, "cmake", "AddAidlLibrary.cmake")
430 makefilesList = append(makefilesList, extPath)
431 android.WriteFileRuleVerbatim(ctx, extPath, cmakeExtAddAidlLibrary)
432
433 // Generating the final zip file
434 zipRule := android.NewRuleBuilder(pctx, ctx)
435 zipCmd := zipRule.Command().
436 BuiltTool("soong_zip").
437 FlagWithOutput("-o ", m.zipPath)
438
439 // Packaging all sources into the zip file
440 if m.Properties.Include_sources {
441 var sourcesList android.Paths
442 for _, file := range sourceFiles {
443 sourcesList = append(sourcesList, file)
444 }
445
446 sourcesRspFile := android.PathForModuleObj(ctx, ctx.ModuleName()+"_sources.rsp")
447 zipCmd.FlagWithRspFileInputList("-r ", sourcesRspFile, sourcesList)
448 }
449
450 // Packaging all make files into the zip file
451 makefilesRspFile := android.PathForModuleObj(ctx, ctx.ModuleName()+"_makefiles.rsp")
452 zipCmd.
453 FlagWithArg("-C ", android.PathForModuleGen(ctx).OutputPath.String()).
454 FlagWithRspFileInputList("-r ", makefilesRspFile, makefilesList)
455
456 // Packaging all prebuilts into the zip file
457 if len(m.Properties.Prebuilts) > 0 {
458 var prebuiltsList android.Paths
459
460 ctx.VisitDirectDepsWithTag(cmakeSnapshotPrebuiltTag, func(dep android.Module) {
461 for _, file := range dep.FilesToInstall() {
462 prebuiltsList = append(prebuiltsList, file)
463 }
464 })
465
466 prebuiltsRspFile := android.PathForModuleObj(ctx, ctx.ModuleName()+"_prebuilts.rsp")
467 zipCmd.
468 FlagWithArg("-C ", android.PathForArbitraryOutput(ctx).String()).
469 FlagWithArg("-P ", "prebuilts").
470 FlagWithRspFileInputList("-r ", prebuiltsRspFile, prebuiltsList)
471 }
472
473 // Finish generating the final zip file
474 zipRule.Build(m.zipPath.String(), "archiving "+ctx.ModuleName())
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000475
mrziwangf95cfa62024-06-18 10:11:39 -0700476 ctx.SetOutputFiles(android.Paths{m.zipPath}, "")
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000477}
478
479func (m *CmakeSnapshot) AndroidMkEntries() []android.AndroidMkEntries {
480 return []android.AndroidMkEntries{{
481 Class: "DATA",
482 OutputFile: android.OptionalPathForPath(m.zipPath),
483 ExtraEntries: []android.AndroidMkExtraEntriesFunc{
484 func(ctx android.AndroidMkExtraEntriesContext, entries *android.AndroidMkEntries) {
485 entries.SetBool("LOCAL_UNINSTALLABLE_MODULE", true)
486 },
487 },
488 }}
489}
490
491func getModuleType(m *Module) string {
492 switch m.linker.(type) {
493 case *binaryDecorator:
494 return "executable"
495 case *libraryDecorator:
496 return "library"
497 case *testBinary:
Tomasz Wasilczykc3177e02024-06-10 14:38:45 -0700498 return "test"
Tomasz Wasilczyk6e2b8c02024-05-30 07:48:40 -0700499 case *benchmarkDecorator:
Tomasz Wasilczykc3177e02024-06-10 14:38:45 -0700500 return "test"
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000501 }
Tomasz Wasilczyk6e2b8c02024-05-30 07:48:40 -0700502 panic(fmt.Sprintf("Unexpected module type: %T", m.linker))
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000503}
504
505func getExtraLibs(m *Module) []string {
506 switch decorator := m.linker.(type) {
507 case *testBinary:
508 if decorator.testDecorator.gtest() {
Tomasz Wasilczyk6e2b8c02024-05-30 07:48:40 -0700509 return []string{
510 "libgtest",
511 "libgtest_main",
512 }
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000513 }
Tomasz Wasilczyk6e2b8c02024-05-30 07:48:40 -0700514 case *benchmarkDecorator:
515 return []string{"libgoogle-benchmark"}
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000516 }
517 return nil
518}
519
520func getIncludeDirs(ctx android.ModuleContext, m *Module) []string {
521 moduleDir := ctx.OtherModuleDir(m) + string(filepath.Separator)
522 switch decorator := m.compiler.(type) {
523 case *libraryDecorator:
Aleks Todorovc9becde2024-06-10 12:51:53 +0100524 return sliceWithPrefix(moduleDir, decorator.flagExporter.Properties.Export_include_dirs.GetOrDefault(ctx, nil))
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000525 }
526 return nil
527}
528
Tomasz Wasilczykd848dcc2024-05-10 09:16:37 -0700529func cmakeSnapshotLoadHook(ctx android.LoadHookContext) {
530 props := struct {
531 Target struct {
532 Darwin struct {
533 Enabled *bool
534 }
535 Windows struct {
536 Enabled *bool
537 }
538 }
539 }{}
540 props.Target.Darwin.Enabled = proptools.BoolPtr(false)
541 props.Target.Windows.Enabled = proptools.BoolPtr(false)
542 ctx.AppendProperties(&props)
543}
544
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000545// cmake_snapshot allows defining source packages for release outside of Android build tree.
546// As a result of cmake_snapshot module build, a zip file is generated with CMake build definitions
547// for selected source modules, their dependencies and optionally also the source code itself.
548func CmakeSnapshotFactory() android.Module {
549 module := &CmakeSnapshot{}
550 module.AddProperties(&module.Properties)
Tomasz Wasilczykd848dcc2024-05-10 09:16:37 -0700551 android.AddLoadHook(module, cmakeSnapshotLoadHook)
552 android.InitAndroidArchModule(module, android.HostSupported, android.MultilibFirst)
Hao Chen1c8ea5b2023-10-20 23:03:45 +0000553 return module
554}
555
556func init() {
557 android.InitRegistrationContext.RegisterModuleType("cc_cmake_snapshot", CmakeSnapshotFactory)
558}