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