blob: 0749ab3bb2490264f2863f46d1f5f46462fd31f9 [file] [log] [blame]
Jiyong Park48ca7dc2018-10-10 14:01:00 +09001// Copyright (C) 2018 The Android Open Source Project
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 apex
16
17import (
18 "fmt"
19 "io"
20 "path/filepath"
21 "runtime"
Jiyong Parkab3ceb32018-10-10 14:05:29 +090022 "sort"
Jiyong Park48ca7dc2018-10-10 14:01:00 +090023 "strings"
24
25 "android/soong/android"
26 "android/soong/cc"
27 "android/soong/java"
28
29 "github.com/google/blueprint"
30 "github.com/google/blueprint/proptools"
31)
32
33var (
34 pctx = android.NewPackageContext("android/apex")
35
36 // Create a canned fs config file where all files and directories are
37 // by default set to (uid/gid/mode) = (1000/1000/0644)
38 // TODO(b/113082813) make this configurable using config.fs syntax
39 generateFsConfig = pctx.StaticRule("generateFsConfig", blueprint.RuleParams{
40 Command: `echo '/ 1000 1000 0644' > ${out} && ` +
41 `echo '/manifest.json 1000 1000 0644' >> ${out} && ` +
42 `echo ${paths} | tr ' ' '\n' | awk '{print "/"$$1 " 1000 1000 0644"}' >> ${out}`,
43 Description: "fs_config ${out}",
44 }, "paths")
45
46 // TODO(b/113233103): make sure that file_contexts is sane, i.e., validate
47 // against the binary policy using sefcontext_compiler -p <policy>.
48
49 // TODO(b/114327326): automate the generation of file_contexts
50 apexRule = pctx.StaticRule("apexRule", blueprint.RuleParams{
51 Command: `rm -rf ${image_dir} && mkdir -p ${image_dir} && ` +
52 `(${copy_commands}) && ` +
53 `APEXER_TOOL_PATH=${tool_path} ` +
54 `${apexer} --verbose --force --manifest ${manifest} ` +
55 `--file_contexts ${file_contexts} ` +
56 `--canned_fs_config ${canned_fs_config} ` +
57 `--key ${key} ${image_dir} ${out} `,
58 CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
59 "${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
60 "${soong_zip}", "${zipalign}", "${aapt2}"},
61 Description: "APEX ${image_dir} => ${out}",
62 }, "tool_path", "image_dir", "copy_commands", "manifest", "file_contexts", "canned_fs_config", "key")
63)
64
65var apexSuffix = ".apex"
66
67type dependencyTag struct {
68 blueprint.BaseDependencyTag
69 name string
70}
71
72var (
73 sharedLibTag = dependencyTag{name: "sharedLib"}
74 executableTag = dependencyTag{name: "executable"}
75 javaLibTag = dependencyTag{name: "javaLib"}
76 prebuiltTag = dependencyTag{name: "prebuilt"}
77)
78
79func init() {
80 pctx.Import("android/soong/common")
81 pctx.HostBinToolVariable("apexer", "apexer")
82 pctx.HostBinToolVariable("aapt2", "aapt2")
83 pctx.HostBinToolVariable("avbtool", "avbtool")
84 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
85 pctx.HostBinToolVariable("merge_zips", "merge_zips")
86 pctx.HostBinToolVariable("mke2fs", "mke2fs")
87 pctx.HostBinToolVariable("resize2fs", "resize2fs")
88 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
89 pctx.HostBinToolVariable("soong_zip", "soong_zip")
90 pctx.HostBinToolVariable("zipalign", "zipalign")
91
92 android.RegisterModuleType("apex", apexBundleFactory)
93
94 android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
95 ctx.TopDown("apex_deps", apexDepsMutator)
96 ctx.BottomUp("apex", apexMutator)
97 })
98}
99
100// maps a module name to set of apex bundle names that the module should be built for
101func apexBundleNamesFor(config android.Config) map[string]map[string]bool {
102 return config.Once("apexBundleNames", func() interface{} {
103 return make(map[string]map[string]bool)
104 }).(map[string]map[string]bool)
105}
106
107// Mark the direct and transitive dependencies of apex bundles so that they
108// can be built for the apex bundles.
109func apexDepsMutator(mctx android.TopDownMutatorContext) {
110 if _, ok := mctx.Module().(*apexBundle); ok {
111 apexBundleName := mctx.Module().Name()
112 mctx.WalkDeps(func(child, parent android.Module) bool {
113 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
114 moduleName := am.Name()
115 bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]
116 if !ok {
117 bundleNames = make(map[string]bool)
118 apexBundleNamesFor(mctx.Config())[moduleName] = bundleNames
119 }
120 bundleNames[apexBundleName] = true
121 return true
122 } else {
123 return false
124 }
125 })
126 }
127}
128
129// Create apex variations if a module is included in APEX(s).
130func apexMutator(mctx android.BottomUpMutatorContext) {
131 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
132 moduleName := am.Name()
133 if bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]; ok {
134 variations := []string{"platform"}
135 for bn := range bundleNames {
136 variations = append(variations, bn)
137 }
138 modules := mctx.CreateVariations(variations...)
139 for i, m := range modules {
140 if i == 0 {
141 continue // platform
142 }
143 m.(android.ApexModule).BuildForApex(variations[i])
144 }
145 }
146 } else if _, ok := mctx.Module().(*apexBundle); ok {
147 // apex bundle itself is mutated so that it and its modules have same
148 // apex variant.
149 apexBundleName := mctx.ModuleName()
150 mctx.CreateVariations(apexBundleName)
151 }
152}
153
154type apexBundleProperties struct {
155 // Json manifest file describing meta info of this APEX bundle. Default:
156 // "manifest.json"
157 Manifest *string
158
159 // File contexts file for setting security context to each file in this APEX bundle
160 // Default: "file_contexts".
161 File_contexts *string
162
163 // List of native shared libs that are embedded inside this APEX bundle
164 Native_shared_libs []string
165
166 // List of native executables that are embedded inside this APEX bundle
167 Binaries []string
168
169 // List of java libraries that are embedded inside this APEX bundle
170 Java_libs []string
171
172 // List of prebuilt files that are embedded inside this APEX bundle
173 Prebuilts []string
174}
175
176type apexBundle struct {
177 android.ModuleBase
178 android.DefaultableModuleBase
179
180 properties apexBundleProperties
181
182 outputFile android.WritablePath
183 installDir android.OutputPath
184}
185
186func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
187 // Native shared libs are added for all architectures of the device
188 // i.e., native_shared_lib_modules: ["libc"] adds both 64 and 32 variation
189 // of the module
190 arches := ctx.DeviceConfig().Arches()
191 if len(arches) == 0 {
192 panic("device build with no primary arch")
193 }
194
195 for _, arch := range ctx.MultiTargets() {
196 // Use *FarVariation* to be able to depend on modules having
197 // conflicting variations with this module. This is required since
198 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
199 // for native shared libs.
200 ctx.AddFarVariationDependencies([]blueprint.Variation{
201 {Mutator: "arch", Variation: arch.String()},
202 {Mutator: "image", Variation: "core"},
203 {Mutator: "link", Variation: "shared"},
204 }, sharedLibTag, a.properties.Native_shared_libs...)
205
206 ctx.AddFarVariationDependencies([]blueprint.Variation{
207 {Mutator: "arch", Variation: arch.String()},
208 {Mutator: "image", Variation: "core"},
209 }, executableTag, a.properties.Binaries...)
210
211 ctx.AddFarVariationDependencies([]blueprint.Variation{
212 {Mutator: "arch", Variation: "android_common"},
213 }, javaLibTag, a.properties.Java_libs...)
214
215 ctx.AddFarVariationDependencies([]blueprint.Variation{
216 {Mutator: "arch", Variation: "android_common"},
217 }, prebuiltTag, a.properties.Prebuilts...)
218 }
219
220}
221
222func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
223 // Decide the APEX-local directory by the multilib of the library
224 // In the future, we may query this to the module.
225 switch cc.Arch().ArchType.Multilib {
226 case "lib32":
227 dirInApex = "lib"
228 case "lib64":
229 dirInApex = "lib64"
230 }
231 if !cc.Arch().Native {
232 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
233 }
234
235 fileToCopy = cc.OutputFile().Path()
236 return
237}
238
239func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
240 dirInApex = "bin"
241 fileToCopy = cc.OutputFile().Path()
242 return
243}
244
245func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
246 dirInApex = "javalib"
247 fileToCopy = java.Srcs()[0]
248 return
249}
250
251func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
252 dirInApex = filepath.Join("etc", prebuilt.SubDir())
253 fileToCopy = prebuilt.OutputFile()
254 return
255}
256
257func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
258 // files to copy -> dir in apex
259 copyManifest := make(map[android.Path]string)
260
261 ctx.WalkDeps(func(child, parent android.Module) bool {
262 if _, ok := parent.(*apexBundle); ok {
263 // direct dependencies
264 depTag := ctx.OtherModuleDependencyTag(child)
265 switch depTag {
266 case sharedLibTag:
267 if cc, ok := child.(*cc.Module); ok {
268 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
269 copyManifest[fileToCopy] = dirInApex
270 return true
271 }
272 case executableTag:
273 if cc, ok := child.(*cc.Module); ok {
274 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
275 copyManifest[fileToCopy] = dirInApex
276 return true
277 }
278 case javaLibTag:
279 if java, ok := child.(*java.Library); ok {
280 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
281 copyManifest[fileToCopy] = dirInApex
282 return true
283 }
284 case prebuiltTag:
285 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
286 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
287 copyManifest[fileToCopy] = dirInApex
288 return true
289 }
290 }
291 } else {
292 // indirect dependencies
293 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
294 if cc, ok := child.(*cc.Module); ok {
295 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
296 copyManifest[fileToCopy] = dirInApex
297 return true
298 }
299 }
300 }
301 return false
302 })
303
304 // files and dirs that will be created in apex
305 var pathsInApex []string
306 for fileToCopy, dirInApex := range copyManifest {
307 pathInApex := filepath.Join(dirInApex, fileToCopy.Base())
308 pathsInApex = append(pathsInApex, pathInApex)
309 if !android.InList(dirInApex, pathsInApex) {
310 pathsInApex = append(pathsInApex, dirInApex)
311 }
312 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900313 sort.Strings(pathsInApex)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900314 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
315 ctx.ModuleBuild(pctx, android.ModuleBuildParams{
316 Rule: generateFsConfig,
317 Output: cannedFsConfig,
318 Args: map[string]string{
319 "paths": strings.Join(pathsInApex, " "),
320 },
321 })
322
323 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "manifest.json"))
324 fileContexts := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.File_contexts, "file_contexts"))
325 // TODO(b/114488804) make this customizable
326 key := android.PathForSource(ctx, "system/apex/apexer/testdata/testkey.pem")
327
328 a.outputFile = android.PathForModuleOut(ctx, a.ModuleBase.Name()+apexSuffix)
329
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900330 filesToCopy := []android.Path{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900331 for file := range copyManifest {
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900332 filesToCopy = append(filesToCopy, file)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900333 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900334 sort.Slice(filesToCopy, func(i, j int) bool {
335 return filesToCopy[i].String() < filesToCopy[j].String()
336 })
337
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900338 copyCommands := []string{}
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900339 for _, src := range filesToCopy {
340 dest := filepath.Join(copyManifest[src], src.Base())
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900341 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image").String(), dest)
342 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
343 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
344 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900345 implicitInputs := append(android.Paths(nil), filesToCopy...)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900346 implicitInputs = append(implicitInputs, cannedFsConfig, manifest, fileContexts, key)
347 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
348 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
349 ctx.ModuleBuild(pctx, android.ModuleBuildParams{
350 Rule: apexRule,
351 Implicits: implicitInputs,
352 Output: a.outputFile,
353 Args: map[string]string{
354 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
355 "image_dir": android.PathForModuleOut(ctx, "image").String(),
356 "copy_commands": strings.Join(copyCommands, " && "),
357 "manifest": manifest.String(),
358 "file_contexts": fileContexts.String(),
359 "canned_fs_config": cannedFsConfig.String(),
360 "key": key.String(),
361 },
362 })
363
364 a.installDir = android.PathForModuleInstall(ctx, "apex")
365}
366
367func (a *apexBundle) AndroidMk() android.AndroidMkData {
368 return android.AndroidMkData{
369 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
370 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
371 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
372 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
373 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
374 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
375 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
376 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexSuffix)
377 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
378 }}
379}
380
381func apexBundleFactory() android.Module {
382 module := &apexBundle{}
383 module.AddProperties(&module.properties)
384 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
385 android.InitDefaultableModule(module)
386 return module
387}