blob: 8e2d1da7742de1a88dc8a82e2624f6fd81529139 [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() {
161 inputs = append(inputs, segroup.SystemVendorSrcs()...)
162 inputs = append(inputs, segroup.VendorSrcs()...)
163 } else if ctx.DeviceSpecific() {
164 inputs = append(inputs, segroup.OdmSrcs()...)
Bowgo Tsai86a048d2019-09-09 22:04:06 +0800165 } else if ctx.SystemExtSpecific() {
166 inputs = append(inputs, segroup.SystemExtPrivateSrcs()...)
Inseob Kimb554e592019-04-15 20:10:46 +0900167 } else {
168 inputs = append(inputs, segroup.SystemPrivateSrcs()...)
Felix342b58a2020-03-02 16:13:12 +0100169 inputs = append(inputs, segroup.SystemPublicSrcs()...)
Inseob Kimb554e592019-04-15 20:10:46 +0900170 }
171
172 if proptools.Bool(m.properties.Reqd_mask) {
173 inputs = append(inputs, segroup.SystemReqdMaskSrcs()...)
174 }
175 })
176
177 for _, src := range m.properties.Srcs {
178 // Module sources are handled above with VisitDirectDepsWithTag
179 if android.SrcIsModule(src) == "" {
180 inputs = append(inputs, android.PathForModuleSrc(ctx, src))
181 }
182 }
183
Inseob Kimcd616492020-03-24 23:06:40 +0900184 m.outputPath = m.build(ctx, inputs)
185 ctx.InstallFile(m.installPath, ctx.ModuleName(), m.outputPath)
Inseob Kimb554e592019-04-15 20:10:46 +0900186}
187
188func newModule() *selinuxContextsModule {
189 m := &selinuxContextsModule{}
190 m.AddProperties(
191 &m.properties,
192 )
193 android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibCommon)
194 android.AddLoadHook(m, func(ctx android.LoadHookContext) {
195 m.selinuxContextsHook(ctx)
196 })
197 return m
198}
199
200func (m *selinuxContextsModule) selinuxContextsHook(ctx android.LoadHookContext) {
201 // TODO: clean this up to use build/soong/android/variable.go after b/79249983
202 var srcs []string
203
204 if ctx.Config().Debuggable() {
205 srcs = append(srcs, m.properties.Product_variables.Debuggable.Srcs...)
206 }
207
208 for _, sanitize := range ctx.Config().SanitizeDevice() {
209 if sanitize == "address" {
210 srcs = append(srcs, m.properties.Product_variables.Address_sanitize.Srcs...)
211 break
212 }
213 }
214
215 m.properties.Srcs = append(m.properties.Srcs, srcs...)
216}
217
218func (m *selinuxContextsModule) AndroidMk() android.AndroidMkData {
219 return android.AndroidMkData{
220 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
221 nameSuffix := ""
222 if m.inRecovery() && !m.onlyInRecovery() {
223 nameSuffix = ".recovery"
224 }
225 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
226 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
227 fmt.Fprintln(w, "LOCAL_MODULE :=", name+nameSuffix)
228 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC")
229 if m.Owner() != "" {
230 fmt.Fprintln(w, "LOCAL_MODULE_OWNER :=", m.Owner())
231 }
232 fmt.Fprintln(w, "LOCAL_MODULE_TAGS := optional")
233 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", m.outputPath.String())
Colin Cross040f1512019-10-02 10:36:09 -0700234 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", m.installPath.ToMakePath().String())
Inseob Kimb554e592019-04-15 20:10:46 +0900235 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name)
236 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
237 },
238 }
239}
240
241func selinuxContextsMutator(ctx android.BottomUpMutatorContext) {
242 m, ok := ctx.Module().(*selinuxContextsModule)
243 if !ok {
244 return
245 }
246
247 var coreVariantNeeded bool = true
248 var recoveryVariantNeeded bool = false
249 if proptools.Bool(m.properties.Recovery_available) {
250 recoveryVariantNeeded = true
251 }
252
253 if m.ModuleBase.InstallInRecovery() {
254 recoveryVariantNeeded = true
255 coreVariantNeeded = false
256 }
257
258 var variants []string
259 if coreVariantNeeded {
260 variants = append(variants, coreMode)
261 }
262 if recoveryVariantNeeded {
263 variants = append(variants, recoveryMode)
264 }
265 mod := ctx.CreateVariations(variants...)
266
267 for i, v := range variants {
268 if v == recoveryMode {
269 m := mod[i].(*selinuxContextsModule)
270 m.properties.InRecovery = true
271
272 if coreVariantNeeded {
273 ctx.AddInterVariantDependency(reuseContextsDepTag, m, mod[i-1])
274 }
275 }
276 }
277}
278
Inseob Kimcd616492020-03-24 23:06:40 +0900279func (m *selinuxContextsModule) buildGeneralContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
280 ret := android.PathForModuleGen(ctx, ctx.ModuleName()+"_m4out")
Inseob Kimb554e592019-04-15 20:10:46 +0900281
Colin Cross242c8bc2020-11-16 17:58:17 -0800282 rule := android.NewRuleBuilder(pctx, ctx)
Inseob Kimb554e592019-04-15 20:10:46 +0900283
284 rule.Command().
Dan Willemsen3c3e59b2019-06-19 10:52:50 -0700285 Tool(ctx.Config().PrebuiltBuildTool(ctx, "m4")).
286 Text("--fatal-warnings -s").
Inseob Kimb554e592019-04-15 20:10:46 +0900287 FlagForEachArg("-D", ctx.DeviceConfig().SepolicyM4Defs()).
288 Inputs(inputs).
Inseob Kimcd616492020-03-24 23:06:40 +0900289 FlagWithOutput("> ", ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900290
291 if proptools.Bool(m.properties.Remove_comment) {
Inseob Kimcd616492020-03-24 23:06:40 +0900292 rule.Temporary(ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900293
294 remove_comment_output := android.PathForModuleGen(ctx, ctx.ModuleName()+"_remove_comment")
295
296 rule.Command().
297 Text("sed -e 's/#.*$//' -e '/^$/d'").
Inseob Kimcd616492020-03-24 23:06:40 +0900298 Input(ret).
Inseob Kimb554e592019-04-15 20:10:46 +0900299 FlagWithOutput("> ", remove_comment_output)
300
Inseob Kimcd616492020-03-24 23:06:40 +0900301 ret = remove_comment_output
Inseob Kimb554e592019-04-15 20:10:46 +0900302 }
303
304 if proptools.Bool(m.properties.Fc_sort) {
Inseob Kimcd616492020-03-24 23:06:40 +0900305 rule.Temporary(ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900306
307 sorted_output := android.PathForModuleGen(ctx, ctx.ModuleName()+"_sorted")
308
309 rule.Command().
310 Tool(ctx.Config().HostToolPath(ctx, "fc_sort")).
Inseob Kimcd616492020-03-24 23:06:40 +0900311 FlagWithInput("-i ", ret).
Inseob Kimb554e592019-04-15 20:10:46 +0900312 FlagWithOutput("-o ", sorted_output)
313
Inseob Kimcd616492020-03-24 23:06:40 +0900314 ret = sorted_output
Inseob Kimb554e592019-04-15 20:10:46 +0900315 }
316
Colin Cross242c8bc2020-11-16 17:58:17 -0800317 rule.Build("selinux_contexts", "building contexts: "+m.Name())
Inseob Kimb554e592019-04-15 20:10:46 +0900318
319 rule.DeleteTemporaryFiles()
320
Inseob Kimcd616492020-03-24 23:06:40 +0900321 return ret
Inseob Kimb554e592019-04-15 20:10:46 +0900322}
323
Inseob Kimcd616492020-03-24 23:06:40 +0900324func (m *selinuxContextsModule) buildFileContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
Inseob Kimb554e592019-04-15 20:10:46 +0900325 if m.properties.Fc_sort == nil {
326 m.properties.Fc_sort = proptools.BoolPtr(true)
327 }
328
Colin Cross242c8bc2020-11-16 17:58:17 -0800329 rule := android.NewRuleBuilder(pctx, ctx)
Inseob Kimb554e592019-04-15 20:10:46 +0900330
331 if ctx.Config().FlattenApex() {
332 for _, src := range m.fileContextsProperties.Flatten_apex.Srcs {
333 if m := android.SrcIsModule(src); m != "" {
334 ctx.ModuleErrorf(
335 "Module srcs dependency %q is not supported for flatten_apex.srcs", m)
Inseob Kimcd616492020-03-24 23:06:40 +0900336 return nil
Inseob Kimb554e592019-04-15 20:10:46 +0900337 }
338 for _, path := range android.PathsForModuleSrcExcludes(ctx, []string{src}, nil) {
339 out := android.PathForModuleGen(ctx, "flattened_apex", path.Rel())
340 apex_path := "/system/apex/" + strings.Replace(
341 strings.TrimSuffix(path.Base(), "-file_contexts"),
342 ".", "\\\\.", -1)
343
344 rule.Command().
345 Text("awk '/object_r/{printf(\""+apex_path+"%s\\n\",$0)}'").
346 Input(path).
347 FlagWithOutput("> ", out)
348
349 inputs = append(inputs, out)
350 }
351 }
352 }
353
Colin Cross242c8bc2020-11-16 17:58:17 -0800354 rule.Build(m.Name(), "flattened_apex_file_contexts")
Inseob Kimcd616492020-03-24 23:06:40 +0900355 return m.buildGeneralContexts(ctx, inputs)
Inseob Kimb554e592019-04-15 20:10:46 +0900356}
357
358func fileFactory() android.Module {
359 m := newModule()
360 m.AddProperties(&m.fileContextsProperties)
361 m.build = m.buildFileContexts
362 return m
363}
364
Inseob Kimcd616492020-03-24 23:06:40 +0900365func (m *selinuxContextsModule) buildHwServiceContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
Inseob Kimb554e592019-04-15 20:10:46 +0900366 if m.properties.Remove_comment == nil {
367 m.properties.Remove_comment = proptools.BoolPtr(true)
368 }
369
Inseob Kimcd616492020-03-24 23:06:40 +0900370 return m.buildGeneralContexts(ctx, inputs)
371}
372
373func (m *selinuxContextsModule) buildPropertyContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
374 builtCtxFile := m.buildGeneralContexts(ctx, inputs)
375
376 var apiFiles android.Paths
377 ctx.VisitDirectDepsWithTag(syspropLibraryDepTag, func(c android.Module) {
378 i, ok := c.(interface{ CurrentSyspropApiFile() android.Path })
379 if !ok {
380 panic(fmt.Errorf("unknown dependency %q for %q", ctx.OtherModuleName(c), ctx.ModuleName()))
381 }
382 apiFiles = append(apiFiles, i.CurrentSyspropApiFile())
383 })
384
385 // check compatibility with sysprop_library
386 if len(apiFiles) > 0 {
387 out := android.PathForModuleGen(ctx, ctx.ModuleName()+"_api_checked")
Colin Cross242c8bc2020-11-16 17:58:17 -0800388 rule := android.NewRuleBuilder(pctx, ctx)
Inseob Kimcd616492020-03-24 23:06:40 +0900389
390 msg := `\n******************************\n` +
391 `API of sysprop_library doesn't match with property_contexts\n` +
392 `Please fix the breakage and rebuild.\n` +
393 `******************************\n`
394
395 rule.Command().
396 Text("( ").
Colin Cross242c8bc2020-11-16 17:58:17 -0800397 BuiltTool("sysprop_type_checker").
Inseob Kimcd616492020-03-24 23:06:40 +0900398 FlagForEachInput("--api ", apiFiles).
399 FlagWithInput("--context ", builtCtxFile).
400 Text(" || ( echo").Flag("-e").
401 Flag(`"` + msg + `"`).
402 Text("; exit 38) )")
403
404 rule.Command().Text("cp -f").Input(builtCtxFile).Output(out)
Colin Cross242c8bc2020-11-16 17:58:17 -0800405 rule.Build("property_contexts_check_api", "checking API: "+m.Name())
Inseob Kimcd616492020-03-24 23:06:40 +0900406 builtCtxFile = out
407 }
408
409 return builtCtxFile
Inseob Kimb554e592019-04-15 20:10:46 +0900410}
411
412func hwServiceFactory() android.Module {
413 m := newModule()
414 m.build = m.buildHwServiceContexts
415 return m
416}
417
418func propertyFactory() android.Module {
419 m := newModule()
Inseob Kimcd616492020-03-24 23:06:40 +0900420 m.build = m.buildPropertyContexts
421 m.deps = m.propertyContextsDeps
Inseob Kimb554e592019-04-15 20:10:46 +0900422 return m
423}
424
425func serviceFactory() android.Module {
426 m := newModule()
427 m.build = m.buildGeneralContexts
428 return m
429}
Janis Danisevskisc40681f2020-07-25 13:02:29 -0700430
431func keystoreKeyFactory() android.Module {
432 m := newModule()
433 m.build = m.buildGeneralContexts
434 return m
435}