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