blob: 6b09c127c66ae231d64418f8843e8815967e7a58 [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
27var SharedLibrarySdkMemberType = &librarySdkMemberType{
28 prebuiltModuleType: "cc_prebuilt_library_shared",
29 linkTypes: []string{"shared"},
30}
31
32var StaticLibrarySdkMemberType = &librarySdkMemberType{
33 prebuiltModuleType: "cc_prebuilt_library_static",
34 linkTypes: []string{"static"},
35}
36
37type librarySdkMemberType struct {
38 prebuiltModuleType string
39
40 // The set of link types supported, set of "static", "shared".
41 linkTypes []string
42}
43
44func (mt *librarySdkMemberType) AddDependencies(mctx android.BottomUpMutatorContext, dependencyTag blueprint.DependencyTag, names []string) {
45 targets := mctx.MultiTargets()
46 for _, lib := range names {
47 for _, target := range targets {
48 name, version := StubsLibNameAndVersion(lib)
49 if version == "" {
50 version = LatestStubsVersionFor(mctx.Config(), name)
51 }
52 for _, linkType := range mt.linkTypes {
53 mctx.AddFarVariationDependencies(append(target.Variations(), []blueprint.Variation{
54 {Mutator: "image", Variation: android.CoreVariation},
55 {Mutator: "link", Variation: linkType},
56 {Mutator: "version", Variation: version},
57 }...), dependencyTag, name)
58 }
59 }
60 }
61}
62
63func (mt *librarySdkMemberType) IsInstance(module android.Module) bool {
64 _, ok := module.(*Module)
65 return ok
66}
67
68// copy exported header files and stub *.so files
69func (mt *librarySdkMemberType) BuildSnapshot(sdkModuleContext android.ModuleContext, builder android.SnapshotBuilder, member android.SdkMember) {
70 info := mt.organizeVariants(member)
71 buildSharedNativeLibSnapshot(sdkModuleContext, info, builder, member)
72}
73
74// Organize the variants by architecture.
75func (mt *librarySdkMemberType) organizeVariants(member android.SdkMember) *nativeLibInfo {
76 memberName := member.Name()
77 info := &nativeLibInfo{
78 name: memberName,
79 memberType: mt,
80 }
81
82 for _, variant := range member.Variants() {
83 ccModule := variant.(*Module)
84
85 // Separate out the generated include dirs (which are arch specific) from the
86 // include dirs (which may not be).
87 exportedIncludeDirs, exportedGeneratedIncludeDirs := android.FilterPathListPredicate(
88 ccModule.ExportedIncludeDirs(), isGeneratedHeaderDirectory)
89
90 info.archVariantProperties = append(info.archVariantProperties, nativeLibInfoProperties{
91 name: memberName,
92 archType: ccModule.Target().Arch.ArchType.String(),
93 ExportedIncludeDirs: exportedIncludeDirs,
94 ExportedGeneratedIncludeDirs: exportedGeneratedIncludeDirs,
95 ExportedSystemIncludeDirs: ccModule.ExportedSystemIncludeDirs(),
96 ExportedFlags: ccModule.ExportedFlags(),
97 exportedGeneratedHeaders: ccModule.ExportedGeneratedHeaders(),
98 outputFile: ccModule.OutputFile().Path(),
99 })
100 }
101
102 // Initialize the unexported properties that will not be set during the
103 // extraction process.
104 info.commonProperties.name = memberName
105
106 // Extract common properties from the arch specific properties.
107 extractCommonProperties(&info.commonProperties, info.archVariantProperties)
108
109 return info
110}
111
112func isGeneratedHeaderDirectory(p android.Path) bool {
113 _, gen := p.(android.WritablePath)
114 return gen
115}
116
117// Extract common properties from a slice of property structures of the same type.
118//
119// All the property structures must be of the same type.
120// commonProperties - must be a pointer to the structure into which common properties will be added.
121// inputPropertiesSlice - must be a slice of input properties structures.
122//
123// Iterates over each exported field (capitalized name) and checks to see whether they
124// have the same value (using DeepEquals) across all the input properties. If it does not then no
125// change is made. Otherwise, the common value is stored in the field in the commonProperties
126// and the field in each of the input properties structure is set to its default value.
127func extractCommonProperties(commonProperties interface{}, inputPropertiesSlice interface{}) {
128 commonStructValue := reflect.ValueOf(commonProperties).Elem()
129 propertiesStructType := commonStructValue.Type()
130
131 // Create an empty structure from which default values for the field can be copied.
132 emptyStructValue := reflect.New(propertiesStructType).Elem()
133
134 for f := 0; f < propertiesStructType.NumField(); f++ {
135 // Check to see if all the structures have the same value for the field. The commonValue
136 // is nil on entry to the loop and if it is nil on exit then there is no common value,
137 // otherwise it points to the common value.
138 var commonValue *reflect.Value
139 sliceValue := reflect.ValueOf(inputPropertiesSlice)
140
141 for i := 0; i < sliceValue.Len(); i++ {
142 structValue := sliceValue.Index(i)
143 fieldValue := structValue.Field(f)
144 if !fieldValue.CanInterface() {
145 // The field is not exported so ignore it.
146 continue
147 }
148
149 if commonValue == nil {
150 // Use the first value as the commonProperties value.
151 commonValue = &fieldValue
152 } else {
153 // If the value does not match the current common value then there is
154 // no value in common so break out.
155 if !reflect.DeepEqual(fieldValue.Interface(), commonValue.Interface()) {
156 commonValue = nil
157 break
158 }
159 }
160 }
161
162 // If the fields all have a common value then store it in the common struct field
163 // and set the input struct's field to the empty value.
164 if commonValue != nil {
165 emptyValue := emptyStructValue.Field(f)
166 commonStructValue.Field(f).Set(*commonValue)
167 for i := 0; i < sliceValue.Len(); i++ {
168 structValue := sliceValue.Index(i)
169 fieldValue := structValue.Field(f)
170 fieldValue.Set(emptyValue)
171 }
172 }
173 }
174}
175
176func buildSharedNativeLibSnapshot(sdkModuleContext android.ModuleContext, info *nativeLibInfo, builder android.SnapshotBuilder, member android.SdkMember) {
177 // a function for emitting include dirs
178 addExportedDirCopyCommandsForNativeLibs := func(lib nativeLibInfoProperties) {
179 // Do not include ExportedGeneratedIncludeDirs in the list of directories whose
180 // contents are copied as they are copied from exportedGeneratedHeaders below.
181 includeDirs := lib.ExportedIncludeDirs
182 includeDirs = append(includeDirs, lib.ExportedSystemIncludeDirs...)
183 for _, dir := range includeDirs {
184 // lib.ArchType is "" for common properties.
185 targetDir := filepath.Join(lib.archType, nativeIncludeDir)
186
187 // TODO(jiyong) copy headers having other suffixes
188 headers, _ := sdkModuleContext.GlobWithDeps(dir.String()+"/**/*.h", nil)
189 for _, file := range headers {
190 src := android.PathForSource(sdkModuleContext, file)
191 dest := filepath.Join(targetDir, file)
192 builder.CopyToSnapshot(src, dest)
193 }
194 }
195
196 genHeaders := lib.exportedGeneratedHeaders
197 for _, file := range genHeaders {
198 // lib.ArchType is "" for common properties.
199 targetDir := filepath.Join(lib.archType, nativeGeneratedIncludeDir)
200
201 dest := filepath.Join(targetDir, lib.name, file.Rel())
202 builder.CopyToSnapshot(file, dest)
203 }
204 }
205
206 addExportedDirCopyCommandsForNativeLibs(info.commonProperties)
207
208 // for each architecture
209 for _, av := range info.archVariantProperties {
210 builder.CopyToSnapshot(av.outputFile, nativeLibraryPathFor(av))
211
212 addExportedDirCopyCommandsForNativeLibs(av)
213 }
214
215 info.generatePrebuiltLibrary(sdkModuleContext, builder, member)
216}
217
218func (info *nativeLibInfo) generatePrebuiltLibrary(sdkModuleContext android.ModuleContext, builder android.SnapshotBuilder, member android.SdkMember) {
219
220 // a function for emitting include dirs
221 addExportedDirsForNativeLibs := func(lib nativeLibInfoProperties, properties android.BpPropertySet, systemInclude bool) {
222 includeDirs := nativeIncludeDirPathsFor(lib, systemInclude)
223 if len(includeDirs) == 0 {
224 return
225 }
226 var propertyName string
227 if !systemInclude {
228 propertyName = "export_include_dirs"
229 } else {
230 propertyName = "export_system_include_dirs"
231 }
232 properties.AddProperty(propertyName, includeDirs)
233 }
234
235 pbm := builder.AddPrebuiltModule(member, info.memberType.prebuiltModuleType)
236
237 addExportedDirsForNativeLibs(info.commonProperties, pbm, false /*systemInclude*/)
238 addExportedDirsForNativeLibs(info.commonProperties, pbm, true /*systemInclude*/)
239
240 archProperties := pbm.AddPropertySet("arch")
241 for _, av := range info.archVariantProperties {
242 archTypeProperties := archProperties.AddPropertySet(av.archType)
243 archTypeProperties.AddProperty("srcs", []string{nativeLibraryPathFor(av)})
244
245 // export_* properties are added inside the arch: {<arch>: {...}} block
246 addExportedDirsForNativeLibs(av, archTypeProperties, false /*systemInclude*/)
247 addExportedDirsForNativeLibs(av, archTypeProperties, true /*systemInclude*/)
248 }
249 pbm.AddProperty("stl", "none")
250 pbm.AddProperty("system_shared_libs", []string{})
251}
252
253const (
254 nativeIncludeDir = "include"
255 nativeGeneratedIncludeDir = "include_gen"
256 nativeStubDir = "lib"
257)
258
259// path to the native library. Relative to <sdk_root>/<api_dir>
260func nativeLibraryPathFor(lib nativeLibInfoProperties) string {
261 return filepath.Join(lib.archType,
262 nativeStubDir, lib.outputFile.Base())
263}
264
265// paths to the include dirs of a native shared library. Relative to <sdk_root>/<api_dir>
266func nativeIncludeDirPathsFor(lib nativeLibInfoProperties, systemInclude bool) []string {
267 var result []string
268 var includeDirs []android.Path
269 if !systemInclude {
270 // Include the generated include dirs in the exported include dirs.
271 includeDirs = append(lib.ExportedIncludeDirs, lib.ExportedGeneratedIncludeDirs...)
272 } else {
273 includeDirs = lib.ExportedSystemIncludeDirs
274 }
275 for _, dir := range includeDirs {
276 var path string
277 if isGeneratedHeaderDirectory(dir) {
278 path = filepath.Join(nativeGeneratedIncludeDir, lib.name)
279 } else {
280 path = filepath.Join(nativeIncludeDir, dir.String())
281 }
282
283 // lib.ArchType is "" for common properties.
284 path = filepath.Join(lib.archType, path)
285 result = append(result, path)
286 }
287 return result
288}
289
290// nativeLibInfoProperties represents properties of a native lib
291//
292// The exported (capitalized) fields will be examined and may be changed during common value extraction.
293// The unexported fields will be left untouched.
294type nativeLibInfoProperties struct {
295 // The name of the library, is not exported as this must not be changed during optimization.
296 name string
297
298 // archType is not exported as if set (to a non default value) it is always arch specific.
299 // This is "" for common properties.
300 archType string
301
302 ExportedIncludeDirs android.Paths
303 ExportedGeneratedIncludeDirs android.Paths
304 ExportedSystemIncludeDirs android.Paths
305 ExportedFlags []string
306
307 // exportedGeneratedHeaders is not exported as if set it is always arch specific.
308 exportedGeneratedHeaders android.Paths
309
310 // outputFile is not exported as it is always arch specific.
311 outputFile android.Path
312}
313
314// nativeLibInfo represents a collection of arch-specific modules having the same name
315type nativeLibInfo struct {
316 name string
317 memberType *librarySdkMemberType
318 archVariantProperties []nativeLibInfoProperties
319 commonProperties nativeLibInfoProperties
320}