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