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