blob: ff292ebc670e0220c1607caae66d1e6256c4e8c8 [file] [log] [blame]
Paul Duffin2f6bc092019-12-13 10:40:56 +00001// Copyright 2019 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 "path/filepath"
19 "reflect"
20
21 "android/soong/android"
22 "github.com/google/blueprint"
23)
24
25// This file contains support for using cc library modules within an sdk.
26
Paul Duffina0843f62019-12-13 19:50:38 +000027var sharedLibrarySdkMemberType = &librarySdkMemberType{
28 SdkMemberTypeBase: android.SdkMemberTypeBase{
29 PropertyName: "native_shared_libs",
Paul Duffine6029182019-12-16 17:43:48 +000030 SupportsSdk: true,
Paul Duffina0843f62019-12-13 19:50:38 +000031 },
32 prebuiltModuleType: "cc_prebuilt_library_shared",
33 linkTypes: []string{"shared"},
34}
35
36var staticLibrarySdkMemberType = &librarySdkMemberType{
37 SdkMemberTypeBase: android.SdkMemberTypeBase{
38 PropertyName: "native_static_libs",
Paul Duffine6029182019-12-16 17:43:48 +000039 SupportsSdk: true,
Paul Duffina0843f62019-12-13 19:50:38 +000040 },
41 prebuiltModuleType: "cc_prebuilt_library_static",
42 linkTypes: []string{"static"},
43}
44
Paul Duffin255f18e2019-12-13 11:22:16 +000045func init() {
46 // Register sdk member types.
Paul Duffina0843f62019-12-13 19:50:38 +000047 android.RegisterSdkMemberType(sharedLibrarySdkMemberType)
48 android.RegisterSdkMemberType(staticLibrarySdkMemberType)
Paul Duffin2f6bc092019-12-13 10:40:56 +000049}
50
51type librarySdkMemberType struct {
Paul Duffin255f18e2019-12-13 11:22:16 +000052 android.SdkMemberTypeBase
53
Paul Duffin2f6bc092019-12-13 10:40:56 +000054 prebuiltModuleType string
55
56 // The set of link types supported, set of "static", "shared".
57 linkTypes []string
58}
59
60func (mt *librarySdkMemberType) AddDependencies(mctx android.BottomUpMutatorContext, dependencyTag blueprint.DependencyTag, names []string) {
61 targets := mctx.MultiTargets()
62 for _, lib := range names {
63 for _, target := range targets {
64 name, version := StubsLibNameAndVersion(lib)
65 if version == "" {
66 version = LatestStubsVersionFor(mctx.Config(), name)
67 }
68 for _, linkType := range mt.linkTypes {
69 mctx.AddFarVariationDependencies(append(target.Variations(), []blueprint.Variation{
70 {Mutator: "image", Variation: android.CoreVariation},
71 {Mutator: "link", Variation: linkType},
72 {Mutator: "version", Variation: version},
73 }...), dependencyTag, name)
74 }
75 }
76 }
77}
78
79func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
Paul Duffina0843f62019-12-13 19:50:38 +000080 // Check the module to see if it can be used with this module type.
81 if m, ok := module.(*Module); ok {
82 for _, allowableMemberType := range m.sdkMemberTypes {
83 if allowableMemberType == mt {
84 return true
85 }
86 }
87 }
88
89 return false
Paul Duffin2f6bc092019-12-13 10:40:56 +000090}
91
92// copy exported header files and stub *.so files
93func (mt *librarySdkMemberType) BuildSnapshot(sdkModuleContext android.ModuleContext, builder android.SnapshotBuilder, member android.SdkMember) {
94 info := mt.organizeVariants(member)
Paul Duffin64f54b02020-02-20 14:33:54 +000095 info.generatePrebuiltLibrary(sdkModuleContext, builder, member)
Paul Duffin2f6bc092019-12-13 10:40:56 +000096}
97
98// Organize the variants by architecture.
99func (mt *librarySdkMemberType) organizeVariants(member android.SdkMember) *nativeLibInfo {
100 memberName := member.Name()
101 info := &nativeLibInfo{
102 name: memberName,
103 memberType: mt,
104 }
105
106 for _, variant := range member.Variants() {
107 ccModule := variant.(*Module)
108
109 // Separate out the generated include dirs (which are arch specific) from the
110 // include dirs (which may not be).
111 exportedIncludeDirs, exportedGeneratedIncludeDirs := android.FilterPathListPredicate(
112 ccModule.ExportedIncludeDirs(), isGeneratedHeaderDirectory)
113
114 info.archVariantProperties = append(info.archVariantProperties, nativeLibInfoProperties{
115 name: memberName,
116 archType: ccModule.Target().Arch.ArchType.String(),
117 ExportedIncludeDirs: exportedIncludeDirs,
Paul Duffin5efd1982020-02-20 14:33:54 +0000118 exportedGeneratedIncludeDirs: exportedGeneratedIncludeDirs,
Paul Duffin2f6bc092019-12-13 10:40:56 +0000119 ExportedSystemIncludeDirs: ccModule.ExportedSystemIncludeDirs(),
120 ExportedFlags: ccModule.ExportedFlags(),
121 exportedGeneratedHeaders: ccModule.ExportedGeneratedHeaders(),
122 outputFile: ccModule.OutputFile().Path(),
123 })
124 }
125
126 // Initialize the unexported properties that will not be set during the
127 // extraction process.
128 info.commonProperties.name = memberName
129
130 // Extract common properties from the arch specific properties.
131 extractCommonProperties(&info.commonProperties, info.archVariantProperties)
132
133 return info
134}
135
136func isGeneratedHeaderDirectory(p android.Path) bool {
137 _, gen := p.(android.WritablePath)
138 return gen
139}
140
141// Extract common properties from a slice of property structures of the same type.
142//
143// All the property structures must be of the same type.
144// commonProperties - must be a pointer to the structure into which common properties will be added.
145// inputPropertiesSlice - must be a slice of input properties structures.
146//
147// Iterates over each exported field (capitalized name) and checks to see whether they
148// have the same value (using DeepEquals) across all the input properties. If it does not then no
149// change is made. Otherwise, the common value is stored in the field in the commonProperties
150// and the field in each of the input properties structure is set to its default value.
151func extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
152 commonStructValue := reflect.ValueOf(commonProperties).Elem()
153 propertiesStructType := commonStructValue.Type()
154
155 // Create an empty structure from which default values for the field can be copied.
156 emptyStructValue := reflect.New(propertiesStructType).Elem()
157
158 for f := 0; f < propertiesStructType.NumField(); f++ {
159 // Check to see if all the structures have the same value for the field. The commonValue
160 // is nil on entry to the loop and if it is nil on exit then there is no common value,
161 // otherwise it points to the common value.
162 var commonValue *reflect.Value
163 sliceValue := reflect.ValueOf(inputPropertiesSlice)
164
165 for i := 0; i < sliceValue.Len(); i++ {
166 structValue := sliceValue.Index(i)
167 fieldValue := structValue.Field(f)
168 if !fieldValue.CanInterface() {
169 // The field is not exported so ignore it.
170 continue
171 }
172
173 if commonValue == nil {
174 // Use the first value as the commonProperties value.
175 commonValue = &fieldValue
176 } else {
177 // If the value does not match the current common value then there is
178 // no value in common so break out.
179 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
180 commonValue = nil
181 break
182 }
183 }
184 }
185
186 // If the fields all have a common value then store it in the common struct field
187 // and set the input struct's field to the empty value.
188 if commonValue != nil {
189 emptyValue := emptyStructValue.Field(f)
190 commonStructValue.Field(f).Set(*commonValue)
191 for i := 0; i < sliceValue.Len(); i++ {
192 structValue := sliceValue.Index(i)
193 fieldValue := structValue.Field(f)
194 fieldValue.Set(emptyValue)
195 }
196 }
197 }
198}
199
Paul Duffin2f6bc092019-12-13 10:40:56 +0000200func (info *nativeLibInfo) generatePrebuiltLibrary(sdkModuleContext android.ModuleContext, builder android.SnapshotBuilder, member android.SdkMember) {
201
Paul Duffin2f6bc092019-12-13 10:40:56 +0000202 pbm := builder.AddPrebuiltModule(member, info.memberType.prebuiltModuleType)
203
Paul Duffin64f54b02020-02-20 14:33:54 +0000204 addPossiblyArchSpecificProperties(sdkModuleContext, builder, info.commonProperties, pbm)
Paul Duffin2f6bc092019-12-13 10:40:56 +0000205
206 archProperties := pbm.AddPropertySet("arch")
207 for _, av := range info.archVariantProperties {
208 archTypeProperties := archProperties.AddPropertySet(av.archType)
Paul Duffin2f6bc092019-12-13 10:40:56 +0000209
Paul Duffin64f54b02020-02-20 14:33:54 +0000210 // Copy the generated library to the snapshot and add a reference to it in the .bp module.
211 nativeLibraryPath := nativeLibraryPathFor(av)
212 builder.CopyToSnapshot(av.outputFile, nativeLibraryPath)
213 archTypeProperties.AddProperty("srcs", []string{nativeLibraryPath})
214
215 // Add any arch specific properties inside the appropriate arch: {<arch>: {...}} block
216 addPossiblyArchSpecificProperties(sdkModuleContext, builder, av, archTypeProperties)
Paul Duffin2f6bc092019-12-13 10:40:56 +0000217 }
218 pbm.AddProperty("stl", "none")
219 pbm.AddProperty("system_shared_libs", []string{})
220}
221
Paul Duffin64f54b02020-02-20 14:33:54 +0000222type includeDirsProperty struct {
223 // Accessor to retrieve the paths
224 pathsGetter func(libInfo nativeLibInfoProperties) android.Paths
225
226 // The name of the property in the prebuilt library, "" means there is no property.
227 propertyName string
228
229 // The directory within the snapshot directory into which items should be copied.
230 snapshotDir string
231
232 // True if the items on the path should be copied.
233 copy bool
234
235 // True if the paths represent directories, files if they represent files.
236 dirs bool
Paul Duffin74fc1902020-01-23 11:45:03 +0000237}
238
Paul Duffin64f54b02020-02-20 14:33:54 +0000239var includeDirProperties = []includeDirsProperty{
240 {
241 // ExportedIncludeDirs lists directories that contains some header files to be
242 // copied into a directory in the snapshot. The snapshot directories must be added to
243 // the export_include_dirs property in the prebuilt module in the snapshot.
244 pathsGetter: func(libInfo nativeLibInfoProperties) android.Paths { return libInfo.ExportedIncludeDirs },
245 propertyName: "export_include_dirs",
246 snapshotDir: nativeIncludeDir,
247 copy: true,
248 dirs: true,
249 },
250 {
251 // ExportedSystemIncludeDirs lists directories that contains some system header files to
252 // be copied into a directory in the snapshot. The snapshot directories must be added to
253 // the export_system_include_dirs property in the prebuilt module in the snapshot.
254 pathsGetter: func(libInfo nativeLibInfoProperties) android.Paths { return libInfo.ExportedSystemIncludeDirs },
255 propertyName: "export_system_include_dirs",
256 snapshotDir: nativeIncludeDir,
257 copy: true,
258 dirs: true,
259 },
260 {
261 // exportedGeneratedIncludeDirs lists directories that contains some header files
262 // that are explicitly listed in the exportedGeneratedHeaders property. So, the contents
263 // of these directories do not need to be copied, but these directories do need adding to
264 // the export_include_dirs property in the prebuilt module in the snapshot.
265 pathsGetter: func(libInfo nativeLibInfoProperties) android.Paths { return libInfo.exportedGeneratedIncludeDirs },
266 propertyName: "export_include_dirs",
267 snapshotDir: nativeGeneratedIncludeDir,
268 copy: false,
269 dirs: true,
270 },
271 {
272 // exportedGeneratedHeaders lists header files that are in one of the directories
273 // specified in exportedGeneratedIncludeDirs must be copied into the snapshot.
274 // As they are in a directory in exportedGeneratedIncludeDirs they do not need adding to a
275 // property in the prebuilt module in the snapshot.
276 pathsGetter: func(libInfo nativeLibInfoProperties) android.Paths { return libInfo.exportedGeneratedHeaders },
277 propertyName: "",
278 snapshotDir: nativeGeneratedIncludeDir,
279 copy: true,
280 dirs: false,
281 },
282}
283
284// Add properties that may, or may not, be arch specific.
285func addPossiblyArchSpecificProperties(sdkModuleContext android.ModuleContext, builder android.SnapshotBuilder, libInfo nativeLibInfoProperties, outputProperties android.BpPropertySet) {
286
287 // Map from property name to the include dirs to add to the prebuilt module in the snapshot.
288 includeDirs := make(map[string][]string)
289
290 // Iterate over each include directory property, copying files and collating property
291 // values where necessary.
292 for _, propertyInfo := range includeDirProperties {
293 // Calculate the base directory in the snapshot into which the files will be copied.
294 // lib.ArchType is "" for common properties.
295 targetDir := filepath.Join(libInfo.archType, propertyInfo.snapshotDir)
296
297 propertyName := propertyInfo.propertyName
298
299 // Iterate over each path in one of the include directory properties.
300 for _, path := range propertyInfo.pathsGetter(libInfo) {
301
302 // Copy the files/directories when necessary.
303 if propertyInfo.copy {
304 if propertyInfo.dirs {
305 // When copying a directory glob and copy all the headers within it.
306 // TODO(jiyong) copy headers having other suffixes
307 headers, _ := sdkModuleContext.GlobWithDeps(path.String()+"/**/*.h", nil)
308 for _, file := range headers {
309 src := android.PathForSource(sdkModuleContext, file)
310 dest := filepath.Join(targetDir, file)
311 builder.CopyToSnapshot(src, dest)
312 }
313 } else {
314 // Otherwise, just copy the files.
315 dest := filepath.Join(targetDir, libInfo.name, path.Rel())
316 builder.CopyToSnapshot(path, dest)
317 }
318 }
319
320 // Only directories are added to a property.
321 if propertyInfo.dirs {
322 var snapshotPath string
323 if isGeneratedHeaderDirectory(path) {
324 snapshotPath = filepath.Join(targetDir, libInfo.name)
325 } else {
326 snapshotPath = filepath.Join(targetDir, path.String())
327 }
328
329 includeDirs[propertyName] = append(includeDirs[propertyName], snapshotPath)
330 }
331 }
Paul Duffin74fc1902020-01-23 11:45:03 +0000332 }
Paul Duffin64f54b02020-02-20 14:33:54 +0000333
334 // Add the collated include dir properties to the output.
335 for property, dirs := range includeDirs {
336 outputProperties.AddProperty(property, dirs)
Paul Duffin74fc1902020-01-23 11:45:03 +0000337 }
Paul Duffin74fc1902020-01-23 11:45:03 +0000338}
339
Paul Duffin2f6bc092019-12-13 10:40:56 +0000340const (
341 nativeIncludeDir = "include"
342 nativeGeneratedIncludeDir = "include_gen"
343 nativeStubDir = "lib"
344)
345
346// path to the native library. Relative to <sdk_root>/<api_dir>
347func nativeLibraryPathFor(lib nativeLibInfoProperties) string {
348 return filepath.Join(lib.archType,
349 nativeStubDir, lib.outputFile.Base())
350}
351
Paul Duffin2f6bc092019-12-13 10:40:56 +0000352// nativeLibInfoProperties represents properties of a native lib
353//
354// The exported (capitalized) fields will be examined and may be changed during common value extraction.
355// The unexported fields will be left untouched.
356type nativeLibInfoProperties struct {
357 // The name of the library, is not exported as this must not be changed during optimization.
358 name string
359
360 // archType is not exported as if set (to a non default value) it is always arch specific.
361 // This is "" for common properties.
362 archType string
363
Paul Duffin5efd1982020-02-20 14:33:54 +0000364 // The list of possibly common exported include dirs.
365 //
366 // This field is exported as its contents may not be arch specific.
367 ExportedIncludeDirs android.Paths
Paul Duffin2f6bc092019-12-13 10:40:56 +0000368
Paul Duffin5efd1982020-02-20 14:33:54 +0000369 // The list of arch specific exported generated include dirs.
370 //
371 // This field is not exported as its contents are always arch specific.
372 exportedGeneratedIncludeDirs android.Paths
373
374 // The list of arch specific exported generated header files.
375 //
376 // This field is not exported as its contents are is always arch specific.
Paul Duffin2f6bc092019-12-13 10:40:56 +0000377 exportedGeneratedHeaders android.Paths
378
Paul Duffin5efd1982020-02-20 14:33:54 +0000379 // The list of possibly common exported system include dirs.
380 //
381 // This field is exported as its contents may not be arch specific.
382 ExportedSystemIncludeDirs android.Paths
383
384 // The list of possibly common exported flags.
385 //
386 // This field is exported as its contents may not be arch specific.
387 ExportedFlags []string
388
Paul Duffin2f6bc092019-12-13 10:40:56 +0000389 // outputFile is not exported as it is always arch specific.
390 outputFile android.Path
391}
392
393// nativeLibInfo represents a collection of arch-specific modules having the same name
394type nativeLibInfo struct {
395 name string
396 memberType *librarySdkMemberType
397 archVariantProperties []nativeLibInfoProperties
398 commonProperties nativeLibInfoProperties
399}