blob: 619ac331abb88ae3f0364c129acf92c533e8bea7 [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"}
Jiyong Parkff1458f2018-10-12 21:49:38 +090078 keyTag = dependencyTag{name: "key"}
Jiyong Park48ca7dc2018-10-10 14:01:00 +090079)
80
81func init() {
82 pctx.Import("android/soong/common")
83 pctx.HostBinToolVariable("apexer", "apexer")
84 pctx.HostBinToolVariable("aapt2", "aapt2")
85 pctx.HostBinToolVariable("avbtool", "avbtool")
86 pctx.HostBinToolVariable("e2fsdroid", "e2fsdroid")
87 pctx.HostBinToolVariable("merge_zips", "merge_zips")
88 pctx.HostBinToolVariable("mke2fs", "mke2fs")
89 pctx.HostBinToolVariable("resize2fs", "resize2fs")
90 pctx.HostBinToolVariable("sefcontext_compile", "sefcontext_compile")
91 pctx.HostBinToolVariable("soong_zip", "soong_zip")
92 pctx.HostBinToolVariable("zipalign", "zipalign")
93
94 android.RegisterModuleType("apex", apexBundleFactory)
95
96 android.PostDepsMutators(func(ctx android.RegisterMutatorsContext) {
97 ctx.TopDown("apex_deps", apexDepsMutator)
98 ctx.BottomUp("apex", apexMutator)
99 })
100}
101
102// maps a module name to set of apex bundle names that the module should be built for
103func apexBundleNamesFor(config android.Config) map[string]map[string]bool {
104 return config.Once("apexBundleNames", func() interface{} {
105 return make(map[string]map[string]bool)
106 }).(map[string]map[string]bool)
107}
108
109// Mark the direct and transitive dependencies of apex bundles so that they
110// can be built for the apex bundles.
111func apexDepsMutator(mctx android.TopDownMutatorContext) {
112 if _, ok := mctx.Module().(*apexBundle); ok {
113 apexBundleName := mctx.Module().Name()
114 mctx.WalkDeps(func(child, parent android.Module) bool {
115 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() {
116 moduleName := am.Name()
117 bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]
118 if !ok {
119 bundleNames = make(map[string]bool)
120 apexBundleNamesFor(mctx.Config())[moduleName] = bundleNames
121 }
122 bundleNames[apexBundleName] = true
123 return true
124 } else {
125 return false
126 }
127 })
128 }
129}
130
131// Create apex variations if a module is included in APEX(s).
132func apexMutator(mctx android.BottomUpMutatorContext) {
133 if am, ok := mctx.Module().(android.ApexModule); ok && am.CanHaveApexVariants() {
134 moduleName := am.Name()
135 if bundleNames, ok := apexBundleNamesFor(mctx.Config())[moduleName]; ok {
136 variations := []string{"platform"}
137 for bn := range bundleNames {
138 variations = append(variations, bn)
139 }
140 modules := mctx.CreateVariations(variations...)
141 for i, m := range modules {
142 if i == 0 {
143 continue // platform
144 }
145 m.(android.ApexModule).BuildForApex(variations[i])
146 }
147 }
148 } else if _, ok := mctx.Module().(*apexBundle); ok {
149 // apex bundle itself is mutated so that it and its modules have same
150 // apex variant.
151 apexBundleName := mctx.ModuleName()
152 mctx.CreateVariations(apexBundleName)
153 }
154}
155
156type apexBundleProperties struct {
157 // Json manifest file describing meta info of this APEX bundle. Default:
158 // "manifest.json"
159 Manifest *string
160
161 // File contexts file for setting security context to each file in this APEX bundle
162 // Default: "file_contexts".
163 File_contexts *string
164
165 // List of native shared libs that are embedded inside this APEX bundle
166 Native_shared_libs []string
167
168 // List of native executables that are embedded inside this APEX bundle
169 Binaries []string
170
171 // List of java libraries that are embedded inside this APEX bundle
172 Java_libs []string
173
174 // List of prebuilt files that are embedded inside this APEX bundle
175 Prebuilts []string
Jiyong Parkff1458f2018-10-12 21:49:38 +0900176
177 // Name of the apex_key module that provides the private key to sign APEX
178 Key *string
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900179}
180
181type apexBundle struct {
182 android.ModuleBase
183 android.DefaultableModuleBase
184
185 properties apexBundleProperties
186
187 outputFile android.WritablePath
188 installDir android.OutputPath
189}
190
191func (a *apexBundle) DepsMutator(ctx android.BottomUpMutatorContext) {
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900192 for _, arch := range ctx.MultiTargets() {
193 // Use *FarVariation* to be able to depend on modules having
194 // conflicting variations with this module. This is required since
195 // arch variant of an APEX bundle is 'common' but it is 'arm' or 'arm64'
196 // for native shared libs.
197 ctx.AddFarVariationDependencies([]blueprint.Variation{
198 {Mutator: "arch", Variation: arch.String()},
199 {Mutator: "image", Variation: "core"},
200 {Mutator: "link", Variation: "shared"},
201 }, sharedLibTag, a.properties.Native_shared_libs...)
202
203 ctx.AddFarVariationDependencies([]blueprint.Variation{
204 {Mutator: "arch", Variation: arch.String()},
205 {Mutator: "image", Variation: "core"},
206 }, executableTag, a.properties.Binaries...)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900207 }
208
Jiyong Parkff1458f2018-10-12 21:49:38 +0900209 ctx.AddFarVariationDependencies([]blueprint.Variation{
210 {Mutator: "arch", Variation: "android_common"},
211 }, javaLibTag, a.properties.Java_libs...)
212
213 ctx.AddFarVariationDependencies([]blueprint.Variation{
214 {Mutator: "arch", Variation: "android_common"},
215 }, prebuiltTag, a.properties.Prebuilts...)
216
217 if String(a.properties.Key) == "" {
218 ctx.ModuleErrorf("key is missing")
219 return
220 }
221 ctx.AddDependency(ctx.Module(), keyTag, String(a.properties.Key))
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900222}
223
224func getCopyManifestForNativeLibrary(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
225 // Decide the APEX-local directory by the multilib of the library
226 // In the future, we may query this to the module.
227 switch cc.Arch().ArchType.Multilib {
228 case "lib32":
229 dirInApex = "lib"
230 case "lib64":
231 dirInApex = "lib64"
232 }
233 if !cc.Arch().Native {
234 dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
235 }
236
237 fileToCopy = cc.OutputFile().Path()
238 return
239}
240
241func getCopyManifestForExecutable(cc *cc.Module) (fileToCopy android.Path, dirInApex string) {
242 dirInApex = "bin"
243 fileToCopy = cc.OutputFile().Path()
244 return
245}
246
247func getCopyManifestForJavaLibrary(java *java.Library) (fileToCopy android.Path, dirInApex string) {
248 dirInApex = "javalib"
249 fileToCopy = java.Srcs()[0]
250 return
251}
252
253func getCopyManifestForPrebuiltEtc(prebuilt *android.PrebuiltEtc) (fileToCopy android.Path, dirInApex string) {
254 dirInApex = filepath.Join("etc", prebuilt.SubDir())
255 fileToCopy = prebuilt.OutputFile()
256 return
257}
258
259func (a *apexBundle) GenerateAndroidBuildActions(ctx android.ModuleContext) {
260 // files to copy -> dir in apex
261 copyManifest := make(map[android.Path]string)
262
Jiyong Parkff1458f2018-10-12 21:49:38 +0900263 var keyFile android.Path
264
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900265 ctx.WalkDeps(func(child, parent android.Module) bool {
266 if _, ok := parent.(*apexBundle); ok {
267 // direct dependencies
268 depTag := ctx.OtherModuleDependencyTag(child)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900269 depName := ctx.OtherModuleName(child)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900270 switch depTag {
271 case sharedLibTag:
272 if cc, ok := child.(*cc.Module); ok {
273 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
274 copyManifest[fileToCopy] = dirInApex
275 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900276 } else {
277 ctx.PropertyErrorf("native_shared_libs", "%q is not a cc_library or cc_library_shared module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900278 }
279 case executableTag:
280 if cc, ok := child.(*cc.Module); ok {
281 fileToCopy, dirInApex := getCopyManifestForExecutable(cc)
282 copyManifest[fileToCopy] = dirInApex
283 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900284 } else {
285 ctx.PropertyErrorf("binaries", "%q is not a cc_binary module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900286 }
287 case javaLibTag:
288 if java, ok := child.(*java.Library); ok {
289 fileToCopy, dirInApex := getCopyManifestForJavaLibrary(java)
290 copyManifest[fileToCopy] = dirInApex
291 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900292 } else {
293 ctx.PropertyErrorf("java_libs", "%q is not a java_library module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900294 }
295 case prebuiltTag:
296 if prebuilt, ok := child.(*android.PrebuiltEtc); ok {
297 fileToCopy, dirInApex := getCopyManifestForPrebuiltEtc(prebuilt)
298 copyManifest[fileToCopy] = dirInApex
299 return true
Jiyong Parkff1458f2018-10-12 21:49:38 +0900300 } else {
301 ctx.PropertyErrorf("prebuilts", "%q is not a prebuilt_etc module", depName)
302 }
303 case keyTag:
304 if key, ok := child.(*apexKey); ok {
305 keyFile = key.private_key_file
306 return false
307 } else {
308 ctx.PropertyErrorf("key", "%q is not an apex_key module", depName)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900309 }
310 }
311 } else {
312 // indirect dependencies
313 if am, ok := child.(android.ApexModule); ok && am.CanHaveApexVariants() && am.IsInstallableToApex() {
314 if cc, ok := child.(*cc.Module); ok {
315 fileToCopy, dirInApex := getCopyManifestForNativeLibrary(cc)
316 copyManifest[fileToCopy] = dirInApex
317 return true
318 }
319 }
320 }
321 return false
322 })
323
324 // files and dirs that will be created in apex
Jiyong Park92905d62018-10-11 13:23:09 +0900325 var readOnlyPaths []string
326 var executablePaths []string // this also includes dirs
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900327 for fileToCopy, dirInApex := range copyManifest {
328 pathInApex := filepath.Join(dirInApex, fileToCopy.Base())
Jiyong Park92905d62018-10-11 13:23:09 +0900329 if dirInApex == "bin" {
330 executablePaths = append(executablePaths, pathInApex)
331 } else {
332 readOnlyPaths = append(readOnlyPaths, pathInApex)
333 }
334 if !android.InList(dirInApex, executablePaths) {
335 executablePaths = append(executablePaths, dirInApex)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900336 }
337 }
Jiyong Park92905d62018-10-11 13:23:09 +0900338 sort.Strings(readOnlyPaths)
339 sort.Strings(executablePaths)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900340 cannedFsConfig := android.PathForModuleOut(ctx, "canned_fs_config")
341 ctx.ModuleBuild(pctx, android.ModuleBuildParams{
342 Rule: generateFsConfig,
343 Output: cannedFsConfig,
344 Args: map[string]string{
Jiyong Park92905d62018-10-11 13:23:09 +0900345 "ro_paths": strings.Join(readOnlyPaths, " "),
346 "exec_paths": strings.Join(executablePaths, " "),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900347 },
348 })
349
350 manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "manifest.json"))
351 fileContexts := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.File_contexts, "file_contexts"))
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900352
353 a.outputFile = android.PathForModuleOut(ctx, a.ModuleBase.Name()+apexSuffix)
354
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900355 filesToCopy := []android.Path{}
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900356 for file := range copyManifest {
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900357 filesToCopy = append(filesToCopy, file)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900358 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900359 sort.Slice(filesToCopy, func(i, j int) bool {
360 return filesToCopy[i].String() < filesToCopy[j].String()
361 })
362
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900363 copyCommands := []string{}
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900364 for _, src := range filesToCopy {
365 dest := filepath.Join(copyManifest[src], src.Base())
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900366 dest_path := filepath.Join(android.PathForModuleOut(ctx, "image").String(), dest)
367 copyCommands = append(copyCommands, "mkdir -p "+filepath.Dir(dest_path))
368 copyCommands = append(copyCommands, "cp "+src.String()+" "+dest_path)
369 }
Jiyong Parkab3ceb32018-10-10 14:05:29 +0900370 implicitInputs := append(android.Paths(nil), filesToCopy...)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900371 implicitInputs = append(implicitInputs, cannedFsConfig, manifest, fileContexts, keyFile)
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900372 outHostBinDir := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "bin").String()
373 prebuiltSdkToolsBinDir := filepath.Join("prebuilts", "sdk", "tools", runtime.GOOS, "bin")
374 ctx.ModuleBuild(pctx, android.ModuleBuildParams{
375 Rule: apexRule,
376 Implicits: implicitInputs,
377 Output: a.outputFile,
378 Args: map[string]string{
379 "tool_path": outHostBinDir + ":" + prebuiltSdkToolsBinDir,
380 "image_dir": android.PathForModuleOut(ctx, "image").String(),
381 "copy_commands": strings.Join(copyCommands, " && "),
382 "manifest": manifest.String(),
383 "file_contexts": fileContexts.String(),
384 "canned_fs_config": cannedFsConfig.String(),
Jiyong Parkff1458f2018-10-12 21:49:38 +0900385 "key": keyFile.String(),
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900386 },
387 })
388
389 a.installDir = android.PathForModuleInstall(ctx, "apex")
390}
391
392func (a *apexBundle) AndroidMk() android.AndroidMkData {
393 return android.AndroidMkData{
394 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
395 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
396 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
397 fmt.Fprintln(w, "LOCAL_MODULE :=", name)
398 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC") // do we need a new class?
399 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", a.outputFile.String())
400 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", filepath.Join("$(OUT_DIR)", a.installDir.RelPathString()))
401 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name+apexSuffix)
Jiyong Parkff1458f2018-10-12 21:49:38 +0900402 fmt.Fprintln(w, "LOCAL_REQUIRED_MODULES :=", String(a.properties.Key))
Jiyong Park48ca7dc2018-10-10 14:01:00 +0900403 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
404 }}
405}
406
407func apexBundleFactory() android.Module {
408 module := &apexBundle{}
409 module.AddProperties(&module.properties)
410 android.InitAndroidMultiTargetsArchModule(module, android.DeviceSupported, android.MultilibCommon)
411 android.InitDefaultableModule(module)
412 return module
413}