blob: 165901d26d10c4d6ad993baf85036edd32692de3 [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)
95 buildSharedNativeLibSnapshot(sdkModuleContext, info, builder, member)
96}
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,
118 ExportedGeneratedIncludeDirs: exportedGeneratedIncludeDirs,
119 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
200func buildSharedNativeLibSnapshot(sdkModuleContext android.ModuleContext, info *nativeLibInfo, builder android.SnapshotBuilder, member android.SdkMember) {
201 // a function for emitting include dirs
202 addExportedDirCopyCommandsForNativeLibs := func(lib nativeLibInfoProperties) {
203 // Do not include ExportedGeneratedIncludeDirs in the list of directories whose
204 // contents are copied as they are copied from exportedGeneratedHeaders below.
205 includeDirs := lib.ExportedIncludeDirs
206 includeDirs = append(includeDirs, lib.ExportedSystemIncludeDirs...)
207 for _, dir := range includeDirs {
208 // lib.ArchType is "" for common properties.
209 targetDir := filepath.Join(lib.archType, nativeIncludeDir)
210
211 // TODO(jiyong) copy headers having other suffixes
212 headers, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.h", nil)
213 for _, file := range headers {
214 src := android.PathForSource(sdkModuleContext, file)
215 dest := filepath.Join(targetDir, file)
216 builder.CopyToSnapshot(src, dest)
217 }
218 }
219
220 genHeaders := lib.exportedGeneratedHeaders
221 for _, file := range genHeaders {
222 // lib.ArchType is "" for common properties.
223 targetDir := filepath.Join(lib.archType, nativeGeneratedIncludeDir)
224
225 dest := filepath.Join(targetDir, lib.name, file.Rel())
226 builder.CopyToSnapshot(file, dest)
227 }
228 }
229
230 addExportedDirCopyCommandsForNativeLibs(info.commonProperties)
231
232 // for each architecture
233 for _, av := range info.archVariantProperties {
234 builder.CopyToSnapshot(av.outputFile, nativeLibraryPathFor(av))
235
236 addExportedDirCopyCommandsForNativeLibs(av)
237 }
238
239 info.generatePrebuiltLibrary(sdkModuleContext, builder, member)
240}
241
242func (info *nativeLibInfo) generatePrebuiltLibrary(sdkModuleContext android.ModuleContext, builder android.SnapshotBuilder, member android.SdkMember) {
243
Paul Duffin2f6bc092019-12-13 10:40:56 +0000244 pbm := builder.AddPrebuiltModule(member, info.memberType.prebuiltModuleType)
245
Paul Duffin74fc1902020-01-23 11:45:03 +0000246 addPossiblyArchSpecificProperties(info.commonProperties, pbm)
Paul Duffin2f6bc092019-12-13 10:40:56 +0000247
248 archProperties := pbm.AddPropertySet("arch")
249 for _, av := range info.archVariantProperties {
250 archTypeProperties := archProperties.AddPropertySet(av.archType)
Paul Duffin74fc1902020-01-23 11:45:03 +0000251 // Add any arch specific properties inside the appropriate arch: {<arch>: {...}} block
Paul Duffin2f6bc092019-12-13 10:40:56 +0000252 archTypeProperties.AddProperty("srcs", []string{nativeLibraryPathFor(av)})
253
Paul Duffin74fc1902020-01-23 11:45:03 +0000254 addPossiblyArchSpecificProperties(av, archTypeProperties)
Paul Duffin2f6bc092019-12-13 10:40:56 +0000255 }
256 pbm.AddProperty("stl", "none")
257 pbm.AddProperty("system_shared_libs", []string{})
258}
259
Paul Duffin74fc1902020-01-23 11:45:03 +0000260// Add properties that may, or may not, be arch specific.
261func addPossiblyArchSpecificProperties(libInfo nativeLibInfoProperties, outputProperties android.BpPropertySet) {
262 addExportedDirsForNativeLibs(libInfo, outputProperties, false /*systemInclude*/)
263 addExportedDirsForNativeLibs(libInfo, outputProperties, true /*systemInclude*/)
264}
265
266// a function for emitting include dirs
267func addExportedDirsForNativeLibs(lib nativeLibInfoProperties, properties android.BpPropertySet, systemInclude bool) {
268 includeDirs := nativeIncludeDirPathsFor(lib, systemInclude)
269 if len(includeDirs) == 0 {
270 return
271 }
272 var propertyName string
273 if !systemInclude {
274 propertyName = "export_include_dirs"
275 } else {
276 propertyName = "export_system_include_dirs"
277 }
278 properties.AddProperty(propertyName, includeDirs)
279}
280
Paul Duffin2f6bc092019-12-13 10:40:56 +0000281const (
282 nativeIncludeDir = "include"
283 nativeGeneratedIncludeDir = "include_gen"
284 nativeStubDir = "lib"
285)
286
287// path to the native library. Relative to <sdk_root>/<api_dir>
288func nativeLibraryPathFor(lib nativeLibInfoProperties) string {
289 return filepath.Join(lib.archType,
290 nativeStubDir, lib.outputFile.Base())
291}
292
293// paths to the include dirs of a native shared library. Relative to <sdk_root>/<api_dir>
294func nativeIncludeDirPathsFor(lib nativeLibInfoProperties, systemInclude bool) []string {
295 var result []string
296 var includeDirs []android.Path
297 if !systemInclude {
298 // Include the generated include dirs in the exported include dirs.
299 includeDirs = append(lib.ExportedIncludeDirs, lib.ExportedGeneratedIncludeDirs...)
300 } else {
301 includeDirs = lib.ExportedSystemIncludeDirs
302 }
303 for _, dir := range includeDirs {
304 var path string
305 if isGeneratedHeaderDirectory(dir) {
306 path = filepath.Join(nativeGeneratedIncludeDir, lib.name)
307 } else {
308 path = filepath.Join(nativeIncludeDir, dir.String())
309 }
310
311 // lib.ArchType is "" for common properties.
312 path = filepath.Join(lib.archType, path)
313 result = append(result, path)
314 }
315 return result
316}
317
318// nativeLibInfoProperties represents properties of a native lib
319//
320// The exported (capitalized) fields will be examined and may be changed during common value extraction.
321// The unexported fields will be left untouched.
322type nativeLibInfoProperties struct {
323 // The name of the library, is not exported as this must not be changed during optimization.
324 name string
325
326 // archType is not exported as if set (to a non default value) it is always arch specific.
327 // This is "" for common properties.
328 archType string
329
330 ExportedIncludeDirs android.Paths
331 ExportedGeneratedIncludeDirs android.Paths
332 ExportedSystemIncludeDirs android.Paths
333 ExportedFlags []string
334
335 // exportedGeneratedHeaders is not exported as if set it is always arch specific.
336 exportedGeneratedHeaders android.Paths
337
338 // outputFile is not exported as it is always arch specific.
339 outputFile android.Path
340}
341
342// nativeLibInfo represents a collection of arch-specific modules having the same name
343type nativeLibInfo struct {
344 name string
345 memberType *librarySdkMemberType
346 archVariantProperties []nativeLibInfoProperties
347 commonProperties nativeLibInfoProperties
348}