blob: a2dad9bb075f424b98489ea35fd76821c7783d0b [file] [log] [blame]
Inseob Kimb554e592019-04-15 20:10:46 +09001// Copyright (C) 2019 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 selinux
16
17import (
18 "fmt"
19 "io"
20 "strings"
21
Inseob Kimcd616492020-03-24 23:06:40 +090022 "github.com/google/blueprint"
Inseob Kimb554e592019-04-15 20:10:46 +090023 "github.com/google/blueprint/proptools"
24
25 "android/soong/android"
Inseob Kimcd616492020-03-24 23:06:40 +090026 "android/soong/sysprop"
Inseob Kimb554e592019-04-15 20:10:46 +090027)
28
29const (
30 coreMode = "core"
31 recoveryMode = "recovery"
32)
33
34type selinuxContextsProperties struct {
35 // Filenames under sepolicy directories, which will be used to generate contexts file.
36 Srcs []string `android:"path"`
37
38 Product_variables struct {
39 Debuggable struct {
40 Srcs []string
41 }
42
43 Address_sanitize struct {
44 Srcs []string
45 }
46 }
47
48 // Whether reqd_mask directory is included to sepolicy directories or not.
49 Reqd_mask *bool
50
51 // Whether the comments in generated contexts file will be removed or not.
52 Remove_comment *bool
53
54 // Whether the result context file is sorted with fc_sort or not.
55 Fc_sort *bool
56
57 // Make this module available when building for recovery
58 Recovery_available *bool
59
60 InRecovery bool `blueprint:"mutated"`
61}
62
63type fileContextsProperties struct {
64 // flatten_apex can be used to specify additional sources of file_contexts.
65 // Apex paths, /system/apex/{apex_name}, will be amended to the paths of file_contexts
66 // entries.
67 Flatten_apex struct {
68 Srcs []string
69 }
70}
71
72type selinuxContextsModule struct {
73 android.ModuleBase
74
75 properties selinuxContextsProperties
76 fileContextsProperties fileContextsProperties
Inseob Kimcd616492020-03-24 23:06:40 +090077 build func(ctx android.ModuleContext, inputs android.Paths) android.Path
78 deps func(ctx android.BottomUpMutatorContext)
79 outputPath android.Path
Colin Cross040f1512019-10-02 10:36:09 -070080 installPath android.InstallPath
Inseob Kimb554e592019-04-15 20:10:46 +090081}
82
83var (
Inseob Kimcd616492020-03-24 23:06:40 +090084 reuseContextsDepTag = dependencyTag{name: "reuseContexts"}
85 syspropLibraryDepTag = dependencyTag{name: "sysprop_library"}
Inseob Kimb554e592019-04-15 20:10:46 +090086)
87
88func init() {
89 pctx.HostBinToolVariable("fc_sort", "fc_sort")
90
91 android.RegisterModuleType("file_contexts", fileFactory)
92 android.RegisterModuleType("hwservice_contexts", hwServiceFactory)
93 android.RegisterModuleType("property_contexts", propertyFactory)
94 android.RegisterModuleType("service_contexts", serviceFactory)
Janis Danisevskisc40681f2020-07-25 13:02:29 -070095 android.RegisterModuleType("keystore2_key_contexts", keystoreKeyFactory)
Inseob Kimb554e592019-04-15 20:10:46 +090096
97 android.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
98 ctx.BottomUp("selinux_contexts", selinuxContextsMutator).Parallel()
99 })
100}
101
102func (m *selinuxContextsModule) inRecovery() bool {
103 return m.properties.InRecovery || m.ModuleBase.InstallInRecovery()
104}
105
106func (m *selinuxContextsModule) onlyInRecovery() bool {
107 return m.ModuleBase.InstallInRecovery()
108}
109
110func (m *selinuxContextsModule) InstallInRecovery() bool {
111 return m.inRecovery()
112}
113
Colin Cross040f1512019-10-02 10:36:09 -0700114func (m *selinuxContextsModule) InstallInRoot() bool {
115 return m.inRecovery()
116}
117
Inseob Kimcd616492020-03-24 23:06:40 +0900118func (m *selinuxContextsModule) DepsMutator(ctx android.BottomUpMutatorContext) {
119 if m.deps != nil {
120 m.deps(ctx)
121 }
122}
123
124func (m *selinuxContextsModule) propertyContextsDeps(ctx android.BottomUpMutatorContext) {
125 for _, lib := range sysprop.SyspropLibraries(ctx.Config()) {
126 ctx.AddFarVariationDependencies([]blueprint.Variation{}, syspropLibraryDepTag, lib)
127 }
128}
129
Inseob Kimb554e592019-04-15 20:10:46 +0900130func (m *selinuxContextsModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross040f1512019-10-02 10:36:09 -0700131 if m.inRecovery() {
132 // Installing context files at the root of the recovery partition
133 m.installPath = android.PathForModuleInstall(ctx)
Inseob Kimb554e592019-04-15 20:10:46 +0900134 } else {
135 m.installPath = android.PathForModuleInstall(ctx, "etc", "selinux")
136 }
137
138 if m.inRecovery() && !m.onlyInRecovery() {
139 dep := ctx.GetDirectDepWithTag(m.Name(), reuseContextsDepTag)
140
141 if reuseDeps, ok := dep.(*selinuxContextsModule); ok {
142 m.outputPath = reuseDeps.outputPath
143 ctx.InstallFile(m.installPath, m.Name(), m.outputPath)
144 return
145 }
146 }
147
148 var inputs android.Paths
149
150 ctx.VisitDirectDepsWithTag(android.SourceDepTag, func(dep android.Module) {
151 segroup, ok := dep.(*fileGroup)
152 if !ok {
153 ctx.ModuleErrorf("srcs dependency %q is not an selinux filegroup",
154 ctx.OtherModuleName(dep))
155 return
156 }
157
158 if ctx.ProductSpecific() {
159 inputs = append(inputs, segroup.ProductPrivateSrcs()...)
160 } else if ctx.SocSpecific() {
Inseob Kim8ada8a72020-11-09 20:58:58 +0900161 if ctx.DeviceConfig().BoardSepolicyVers() == ctx.DeviceConfig().PlatformSepolicyVersion() {
162 inputs = append(inputs, segroup.SystemVendorSrcs()...)
163 }
Inseob Kimb554e592019-04-15 20:10:46 +0900164 inputs = append(inputs, segroup.VendorSrcs()...)
165 } else if ctx.DeviceSpecific() {
166 inputs = append(inputs, segroup.OdmSrcs()...)
Bowgo Tsai86a048d2019-09-09 22:04:06 +0800167 } else if ctx.SystemExtSpecific() {
168 inputs = append(inputs, segroup.SystemExtPrivateSrcs()...)
Inseob Kimb554e592019-04-15 20:10:46 +0900169 } else {
170 inputs = append(inputs, segroup.SystemPrivateSrcs()...)
Felix342b58a2020-03-02 16:13:12 +0100171 inputs = append(inputs, segroup.SystemPublicSrcs()...)
Inseob Kimb554e592019-04-15 20:10:46 +0900172 }
173
174 if proptools.Bool(m.properties.Reqd_mask) {
Inseob Kim8ada8a72020-11-09 20:58:58 +0900175 if ctx.SocSpecific() || ctx.DeviceSpecific() {
176 inputs = append(inputs, segroup.VendorReqdMaskSrcs()...)
177 } else {
178 inputs = append(inputs, segroup.SystemReqdMaskSrcs()...)
179 }
Inseob Kimb554e592019-04-15 20:10:46 +0900180 }
181 })
182
183 for _, src := range m.properties.Srcs {
184 // Module sources are handled above with VisitDirectDepsWithTag
185 if android.SrcIsModule(src) == "" {
186 inputs = append(inputs, android.PathForModuleSrc(ctx, src))
187 }
188 }
189
Inseob Kimcd616492020-03-24 23:06:40 +0900190 m.outputPath = m.build(ctx, inputs)
191 ctx.InstallFile(m.installPath, ctx.ModuleName(), m.outputPath)
Inseob Kimb554e592019-04-15 20:10:46 +0900192}
193
194func newModule() *selinuxContextsModule {
195 m := &selinuxContextsModule{}
196 m.AddProperties(
197 &m.properties,
198 )
199 android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibCommon)
200 android.AddLoadHook(m, func(ctx android.LoadHookContext) {
201 m.selinuxContextsHook(ctx)
202 })
203 return m
204}
205
206func (m *selinuxContextsModule) selinuxContextsHook(ctx android.LoadHookContext) {
207 // TODO: clean this up to use build/soong/android/variable.go after b/79249983
208 var srcs []string
209
210 if ctx.Config().Debuggable() {
211 srcs = append(srcs, m.properties.Product_variables.Debuggable.Srcs...)
212 }
213
214 for _, sanitize := range ctx.Config().SanitizeDevice() {
215 if sanitize == "address" {
216 srcs = append(srcs, m.properties.Product_variables.Address_sanitize.Srcs...)
217 break
218 }
219 }
220
221 m.properties.Srcs = append(m.properties.Srcs, srcs...)
222}
223
224func (m *selinuxContextsModule) AndroidMk() android.AndroidMkData {
225 return android.AndroidMkData{
226 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
227 nameSuffix := ""
228 if m.inRecovery() && !m.onlyInRecovery() {
229 nameSuffix = ".recovery"
230 }
231 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
232 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
233 fmt.Fprintln(w, "LOCAL_MODULE :=", name+nameSuffix)
234 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC")
235 if m.Owner() != "" {
236 fmt.Fprintln(w, "LOCAL_MODULE_OWNER :=", m.Owner())
237 }
238 fmt.Fprintln(w, "LOCAL_MODULE_TAGS := optional")
239 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", m.outputPath.String())
Colin Cross040f1512019-10-02 10:36:09 -0700240 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", m.installPath.ToMakePath().String())
Inseob Kimb554e592019-04-15 20:10:46 +0900241 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name)
242 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
243 },
244 }
245}
246
247func selinuxContextsMutator(ctx android.BottomUpMutatorContext) {
248 m, ok := ctx.Module().(*selinuxContextsModule)
249 if !ok {
250 return
251 }
252
253 var coreVariantNeeded bool = true
254 var recoveryVariantNeeded bool = false
255 if proptools.Bool(m.properties.Recovery_available) {
256 recoveryVariantNeeded = true
257 }
258
259 if m.ModuleBase.InstallInRecovery() {
260 recoveryVariantNeeded = true
261 coreVariantNeeded = false
262 }
263
264 var variants []string
265 if coreVariantNeeded {
266 variants = append(variants, coreMode)
267 }
268 if recoveryVariantNeeded {
269 variants = append(variants, recoveryMode)
270 }
271 mod := ctx.CreateVariations(variants...)
272
273 for i, v := range variants {
274 if v == recoveryMode {
275 m := mod[i].(*selinuxContextsModule)
276 m.properties.InRecovery = true
277
278 if coreVariantNeeded {
279 ctx.AddInterVariantDependency(reuseContextsDepTag, m, mod[i-1])
280 }
281 }
282 }
283}
284
Inseob Kimcd616492020-03-24 23:06:40 +0900285func (m *selinuxContextsModule) buildGeneralContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
286 ret := android.PathForModuleGen(ctx, ctx.ModuleName()+"_m4out")
Inseob Kimb554e592019-04-15 20:10:46 +0900287
Colin Cross242c8bc2020-11-16 17:58:17 -0800288 rule := android.NewRuleBuilder(pctx, ctx)
Inseob Kimb554e592019-04-15 20:10:46 +0900289
290 rule.Command().
Dan Willemsen3c3e59b2019-06-19 10:52:50 -0700291 Tool(ctx.Config().PrebuiltBuildTool(ctx, "m4")).
292 Text("--fatal-warnings -s").
Inseob Kimb554e592019-04-15 20:10:46 +0900293 FlagForEachArg("-D", ctx.DeviceConfig().SepolicyM4Defs()).
294 Inputs(inputs).
Inseob Kimcd616492020-03-24 23:06:40 +0900295 FlagWithOutput("> ", ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900296
297 if proptools.Bool(m.properties.Remove_comment) {
Inseob Kimcd616492020-03-24 23:06:40 +0900298 rule.Temporary(ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900299
300 remove_comment_output := android.PathForModuleGen(ctx, ctx.ModuleName()+"_remove_comment")
301
302 rule.Command().
303 Text("sed -e 's/#.*$//' -e '/^$/d'").
Inseob Kimcd616492020-03-24 23:06:40 +0900304 Input(ret).
Inseob Kimb554e592019-04-15 20:10:46 +0900305 FlagWithOutput("> ", remove_comment_output)
306
Inseob Kimcd616492020-03-24 23:06:40 +0900307 ret = remove_comment_output
Inseob Kimb554e592019-04-15 20:10:46 +0900308 }
309
310 if proptools.Bool(m.properties.Fc_sort) {
Inseob Kimcd616492020-03-24 23:06:40 +0900311 rule.Temporary(ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900312
313 sorted_output := android.PathForModuleGen(ctx, ctx.ModuleName()+"_sorted")
314
315 rule.Command().
316 Tool(ctx.Config().HostToolPath(ctx, "fc_sort")).
Inseob Kimcd616492020-03-24 23:06:40 +0900317 FlagWithInput("-i ", ret).
Inseob Kimb554e592019-04-15 20:10:46 +0900318 FlagWithOutput("-o ", sorted_output)
319
Inseob Kimcd616492020-03-24 23:06:40 +0900320 ret = sorted_output
Inseob Kimb554e592019-04-15 20:10:46 +0900321 }
322
Colin Cross242c8bc2020-11-16 17:58:17 -0800323 rule.Build("selinux_contexts", "building contexts: "+m.Name())
Inseob Kimb554e592019-04-15 20:10:46 +0900324
325 rule.DeleteTemporaryFiles()
326
Inseob Kimcd616492020-03-24 23:06:40 +0900327 return ret
Inseob Kimb554e592019-04-15 20:10:46 +0900328}
329
Inseob Kimcd616492020-03-24 23:06:40 +0900330func (m *selinuxContextsModule) buildFileContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
Inseob Kimb554e592019-04-15 20:10:46 +0900331 if m.properties.Fc_sort == nil {
332 m.properties.Fc_sort = proptools.BoolPtr(true)
333 }
334
Colin Cross242c8bc2020-11-16 17:58:17 -0800335 rule := android.NewRuleBuilder(pctx, ctx)
Inseob Kimb554e592019-04-15 20:10:46 +0900336
337 if ctx.Config().FlattenApex() {
338 for _, src := range m.fileContextsProperties.Flatten_apex.Srcs {
339 if m := android.SrcIsModule(src); m != "" {
340 ctx.ModuleErrorf(
341 "Module srcs dependency %q is not supported for flatten_apex.srcs", m)
Inseob Kimcd616492020-03-24 23:06:40 +0900342 return nil
Inseob Kimb554e592019-04-15 20:10:46 +0900343 }
344 for _, path := range android.PathsForModuleSrcExcludes(ctx, []string{src}, nil) {
345 out := android.PathForModuleGen(ctx, "flattened_apex", path.Rel())
346 apex_path := "/system/apex/" + strings.Replace(
347 strings.TrimSuffix(path.Base(), "-file_contexts"),
348 ".", "\\\\.", -1)
349
350 rule.Command().
351 Text("awk '/object_r/{printf(\""+apex_path+"%s\\n\",$0)}'").
352 Input(path).
353 FlagWithOutput("> ", out)
354
355 inputs = append(inputs, out)
356 }
357 }
358 }
359
Colin Cross242c8bc2020-11-16 17:58:17 -0800360 rule.Build(m.Name(), "flattened_apex_file_contexts")
Inseob Kimcd616492020-03-24 23:06:40 +0900361 return m.buildGeneralContexts(ctx, inputs)
Inseob Kimb554e592019-04-15 20:10:46 +0900362}
363
364func fileFactory() android.Module {
365 m := newModule()
366 m.AddProperties(&m.fileContextsProperties)
367 m.build = m.buildFileContexts
368 return m
369}
370
Inseob Kimcd616492020-03-24 23:06:40 +0900371func (m *selinuxContextsModule) buildHwServiceContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
Inseob Kimb554e592019-04-15 20:10:46 +0900372 if m.properties.Remove_comment == nil {
373 m.properties.Remove_comment = proptools.BoolPtr(true)
374 }
375
Inseob Kimcd616492020-03-24 23:06:40 +0900376 return m.buildGeneralContexts(ctx, inputs)
377}
378
379func (m *selinuxContextsModule) buildPropertyContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
380 builtCtxFile := m.buildGeneralContexts(ctx, inputs)
381
382 var apiFiles android.Paths
383 ctx.VisitDirectDepsWithTag(syspropLibraryDepTag, func(c android.Module) {
384 i, ok := c.(interface{ CurrentSyspropApiFile() android.Path })
385 if !ok {
386 panic(fmt.Errorf("unknown dependency %q for %q", ctx.OtherModuleName(c), ctx.ModuleName()))
387 }
388 apiFiles = append(apiFiles, i.CurrentSyspropApiFile())
389 })
390
391 // check compatibility with sysprop_library
392 if len(apiFiles) > 0 {
393 out := android.PathForModuleGen(ctx, ctx.ModuleName()+"_api_checked")
Colin Cross242c8bc2020-11-16 17:58:17 -0800394 rule := android.NewRuleBuilder(pctx, ctx)
Inseob Kimcd616492020-03-24 23:06:40 +0900395
396 msg := `\n******************************\n` +
397 `API of sysprop_library doesn't match with property_contexts\n` +
398 `Please fix the breakage and rebuild.\n` +
399 `******************************\n`
400
401 rule.Command().
402 Text("( ").
Colin Cross242c8bc2020-11-16 17:58:17 -0800403 BuiltTool("sysprop_type_checker").
Inseob Kimcd616492020-03-24 23:06:40 +0900404 FlagForEachInput("--api ", apiFiles).
405 FlagWithInput("--context ", builtCtxFile).
406 Text(" || ( echo").Flag("-e").
407 Flag(`"` + msg + `"`).
408 Text("; exit 38) )")
409
410 rule.Command().Text("cp -f").Input(builtCtxFile).Output(out)
Colin Cross242c8bc2020-11-16 17:58:17 -0800411 rule.Build("property_contexts_check_api", "checking API: "+m.Name())
Inseob Kimcd616492020-03-24 23:06:40 +0900412 builtCtxFile = out
413 }
414
415 return builtCtxFile
Inseob Kimb554e592019-04-15 20:10:46 +0900416}
417
418func hwServiceFactory() android.Module {
419 m := newModule()
420 m.build = m.buildHwServiceContexts
421 return m
422}
423
424func propertyFactory() android.Module {
425 m := newModule()
Inseob Kimcd616492020-03-24 23:06:40 +0900426 m.build = m.buildPropertyContexts
427 m.deps = m.propertyContextsDeps
Inseob Kimb554e592019-04-15 20:10:46 +0900428 return m
429}
430
431func serviceFactory() android.Module {
432 m := newModule()
433 m.build = m.buildGeneralContexts
434 return m
435}
Janis Danisevskisc40681f2020-07-25 13:02:29 -0700436
437func keystoreKeyFactory() android.Module {
438 m := newModule()
439 m.build = m.buildGeneralContexts
440 return m
441}