blob: 635ebdae34bfcfec5b92159d74120627bc99f09d [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)
95
96 android.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
97 ctx.BottomUp("selinux_contexts", selinuxContextsMutator).Parallel()
98 })
99}
100
101func (m *selinuxContextsModule) inRecovery() bool {
102 return m.properties.InRecovery || m.ModuleBase.InstallInRecovery()
103}
104
105func (m *selinuxContextsModule) onlyInRecovery() bool {
106 return m.ModuleBase.InstallInRecovery()
107}
108
109func (m *selinuxContextsModule) InstallInRecovery() bool {
110 return m.inRecovery()
111}
112
Colin Cross040f1512019-10-02 10:36:09 -0700113func (m *selinuxContextsModule) InstallInRoot() bool {
114 return m.inRecovery()
115}
116
Inseob Kimcd616492020-03-24 23:06:40 +0900117func (m *selinuxContextsModule) DepsMutator(ctx android.BottomUpMutatorContext) {
118 if m.deps != nil {
119 m.deps(ctx)
120 }
121}
122
123func (m *selinuxContextsModule) propertyContextsDeps(ctx android.BottomUpMutatorContext) {
124 for _, lib := range sysprop.SyspropLibraries(ctx.Config()) {
125 ctx.AddFarVariationDependencies([]blueprint.Variation{}, syspropLibraryDepTag, lib)
126 }
127}
128
Inseob Kimb554e592019-04-15 20:10:46 +0900129func (m *selinuxContextsModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Colin Cross040f1512019-10-02 10:36:09 -0700130 if m.inRecovery() {
131 // Installing context files at the root of the recovery partition
132 m.installPath = android.PathForModuleInstall(ctx)
Inseob Kimb554e592019-04-15 20:10:46 +0900133 } else {
134 m.installPath = android.PathForModuleInstall(ctx, "etc", "selinux")
135 }
136
137 if m.inRecovery() && !m.onlyInRecovery() {
138 dep := ctx.GetDirectDepWithTag(m.Name(), reuseContextsDepTag)
139
140 if reuseDeps, ok := dep.(*selinuxContextsModule); ok {
141 m.outputPath = reuseDeps.outputPath
142 ctx.InstallFile(m.installPath, m.Name(), m.outputPath)
143 return
144 }
145 }
146
147 var inputs android.Paths
148
149 ctx.VisitDirectDepsWithTag(android.SourceDepTag, func(dep android.Module) {
150 segroup, ok := dep.(*fileGroup)
151 if !ok {
152 ctx.ModuleErrorf("srcs dependency %q is not an selinux filegroup",
153 ctx.OtherModuleName(dep))
154 return
155 }
156
157 if ctx.ProductSpecific() {
158 inputs = append(inputs, segroup.ProductPrivateSrcs()...)
159 } else if ctx.SocSpecific() {
160 inputs = append(inputs, segroup.SystemVendorSrcs()...)
161 inputs = append(inputs, segroup.VendorSrcs()...)
162 } else if ctx.DeviceSpecific() {
163 inputs = append(inputs, segroup.OdmSrcs()...)
Bowgo Tsai86a048d2019-09-09 22:04:06 +0800164 } else if ctx.SystemExtSpecific() {
165 inputs = append(inputs, segroup.SystemExtPrivateSrcs()...)
Inseob Kimb554e592019-04-15 20:10:46 +0900166 } else {
167 inputs = append(inputs, segroup.SystemPrivateSrcs()...)
Felix342b58a2020-03-02 16:13:12 +0100168 inputs = append(inputs, segroup.SystemPublicSrcs()...)
Inseob Kimb554e592019-04-15 20:10:46 +0900169 }
170
171 if proptools.Bool(m.properties.Reqd_mask) {
172 inputs = append(inputs, segroup.SystemReqdMaskSrcs()...)
173 }
174 })
175
176 for _, src := range m.properties.Srcs {
177 // Module sources are handled above with VisitDirectDepsWithTag
178 if android.SrcIsModule(src) == "" {
179 inputs = append(inputs, android.PathForModuleSrc(ctx, src))
180 }
181 }
182
Inseob Kimcd616492020-03-24 23:06:40 +0900183 m.outputPath = m.build(ctx, inputs)
184 ctx.InstallFile(m.installPath, ctx.ModuleName(), m.outputPath)
Inseob Kimb554e592019-04-15 20:10:46 +0900185}
186
187func newModule() *selinuxContextsModule {
188 m := &selinuxContextsModule{}
189 m.AddProperties(
190 &m.properties,
191 )
192 android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibCommon)
193 android.AddLoadHook(m, func(ctx android.LoadHookContext) {
194 m.selinuxContextsHook(ctx)
195 })
196 return m
197}
198
199func (m *selinuxContextsModule) selinuxContextsHook(ctx android.LoadHookContext) {
200 // TODO: clean this up to use build/soong/android/variable.go after b/79249983
201 var srcs []string
202
203 if ctx.Config().Debuggable() {
204 srcs = append(srcs, m.properties.Product_variables.Debuggable.Srcs...)
205 }
206
207 for _, sanitize := range ctx.Config().SanitizeDevice() {
208 if sanitize == "address" {
209 srcs = append(srcs, m.properties.Product_variables.Address_sanitize.Srcs...)
210 break
211 }
212 }
213
214 m.properties.Srcs = append(m.properties.Srcs, srcs...)
215}
216
217func (m *selinuxContextsModule) AndroidMk() android.AndroidMkData {
218 return android.AndroidMkData{
219 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
220 nameSuffix := ""
221 if m.inRecovery() && !m.onlyInRecovery() {
222 nameSuffix = ".recovery"
223 }
224 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
225 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
226 fmt.Fprintln(w, "LOCAL_MODULE :=", name+nameSuffix)
227 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC")
228 if m.Owner() != "" {
229 fmt.Fprintln(w, "LOCAL_MODULE_OWNER :=", m.Owner())
230 }
231 fmt.Fprintln(w, "LOCAL_MODULE_TAGS := optional")
232 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", m.outputPath.String())
Colin Cross040f1512019-10-02 10:36:09 -0700233 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", m.installPath.ToMakePath().String())
Inseob Kimb554e592019-04-15 20:10:46 +0900234 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name)
235 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
236 },
237 }
238}
239
240func selinuxContextsMutator(ctx android.BottomUpMutatorContext) {
241 m, ok := ctx.Module().(*selinuxContextsModule)
242 if !ok {
243 return
244 }
245
246 var coreVariantNeeded bool = true
247 var recoveryVariantNeeded bool = false
248 if proptools.Bool(m.properties.Recovery_available) {
249 recoveryVariantNeeded = true
250 }
251
252 if m.ModuleBase.InstallInRecovery() {
253 recoveryVariantNeeded = true
254 coreVariantNeeded = false
255 }
256
257 var variants []string
258 if coreVariantNeeded {
259 variants = append(variants, coreMode)
260 }
261 if recoveryVariantNeeded {
262 variants = append(variants, recoveryMode)
263 }
264 mod := ctx.CreateVariations(variants...)
265
266 for i, v := range variants {
267 if v == recoveryMode {
268 m := mod[i].(*selinuxContextsModule)
269 m.properties.InRecovery = true
270
271 if coreVariantNeeded {
272 ctx.AddInterVariantDependency(reuseContextsDepTag, m, mod[i-1])
273 }
274 }
275 }
276}
277
Inseob Kimcd616492020-03-24 23:06:40 +0900278func (m *selinuxContextsModule) buildGeneralContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
279 ret := android.PathForModuleGen(ctx, ctx.ModuleName()+"_m4out")
Inseob Kimb554e592019-04-15 20:10:46 +0900280
281 rule := android.NewRuleBuilder()
282
283 rule.Command().
Dan Willemsen3c3e59b2019-06-19 10:52:50 -0700284 Tool(ctx.Config().PrebuiltBuildTool(ctx, "m4")).
285 Text("--fatal-warnings -s").
Inseob Kimb554e592019-04-15 20:10:46 +0900286 FlagForEachArg("-D", ctx.DeviceConfig().SepolicyM4Defs()).
287 Inputs(inputs).
Inseob Kimcd616492020-03-24 23:06:40 +0900288 FlagWithOutput("> ", ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900289
290 if proptools.Bool(m.properties.Remove_comment) {
Inseob Kimcd616492020-03-24 23:06:40 +0900291 rule.Temporary(ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900292
293 remove_comment_output := android.PathForModuleGen(ctx, ctx.ModuleName()+"_remove_comment")
294
295 rule.Command().
296 Text("sed -e 's/#.*$//' -e '/^$/d'").
Inseob Kimcd616492020-03-24 23:06:40 +0900297 Input(ret).
Inseob Kimb554e592019-04-15 20:10:46 +0900298 FlagWithOutput("> ", remove_comment_output)
299
Inseob Kimcd616492020-03-24 23:06:40 +0900300 ret = remove_comment_output
Inseob Kimb554e592019-04-15 20:10:46 +0900301 }
302
303 if proptools.Bool(m.properties.Fc_sort) {
Inseob Kimcd616492020-03-24 23:06:40 +0900304 rule.Temporary(ret)
Inseob Kimb554e592019-04-15 20:10:46 +0900305
306 sorted_output := android.PathForModuleGen(ctx, ctx.ModuleName()+"_sorted")
307
308 rule.Command().
309 Tool(ctx.Config().HostToolPath(ctx, "fc_sort")).
Inseob Kimcd616492020-03-24 23:06:40 +0900310 FlagWithInput("-i ", ret).
Inseob Kimb554e592019-04-15 20:10:46 +0900311 FlagWithOutput("-o ", sorted_output)
312
Inseob Kimcd616492020-03-24 23:06:40 +0900313 ret = sorted_output
Inseob Kimb554e592019-04-15 20:10:46 +0900314 }
315
Inseob Kimcd616492020-03-24 23:06:40 +0900316 rule.Build(pctx, ctx, "selinux_contexts", "building contexts: "+m.Name())
Inseob Kimb554e592019-04-15 20:10:46 +0900317
318 rule.DeleteTemporaryFiles()
319
Inseob Kimcd616492020-03-24 23:06:40 +0900320 return ret
Inseob Kimb554e592019-04-15 20:10:46 +0900321}
322
Inseob Kimcd616492020-03-24 23:06:40 +0900323func (m *selinuxContextsModule) buildFileContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
Inseob Kimb554e592019-04-15 20:10:46 +0900324 if m.properties.Fc_sort == nil {
325 m.properties.Fc_sort = proptools.BoolPtr(true)
326 }
327
328 rule := android.NewRuleBuilder()
329
330 if ctx.Config().FlattenApex() {
331 for _, src := range m.fileContextsProperties.Flatten_apex.Srcs {
332 if m := android.SrcIsModule(src); m != "" {
333 ctx.ModuleErrorf(
334 "Module srcs dependency %q is not supported for flatten_apex.srcs", m)
Inseob Kimcd616492020-03-24 23:06:40 +0900335 return nil
Inseob Kimb554e592019-04-15 20:10:46 +0900336 }
337 for _, path := range android.PathsForModuleSrcExcludes(ctx, []string{src}, nil) {
338 out := android.PathForModuleGen(ctx, "flattened_apex", path.Rel())
339 apex_path := "/system/apex/" + strings.Replace(
340 strings.TrimSuffix(path.Base(), "-file_contexts"),
341 ".", "\\\\.", -1)
342
343 rule.Command().
344 Text("awk '/object_r/{printf(\""+apex_path+"%s\\n\",$0)}'").
345 Input(path).
346 FlagWithOutput("> ", out)
347
348 inputs = append(inputs, out)
349 }
350 }
351 }
352
353 rule.Build(pctx, ctx, m.Name(), "flattened_apex_file_contexts")
Inseob Kimcd616492020-03-24 23:06:40 +0900354 return m.buildGeneralContexts(ctx, inputs)
Inseob Kimb554e592019-04-15 20:10:46 +0900355}
356
357func fileFactory() android.Module {
358 m := newModule()
359 m.AddProperties(&m.fileContextsProperties)
360 m.build = m.buildFileContexts
361 return m
362}
363
Inseob Kimcd616492020-03-24 23:06:40 +0900364func (m *selinuxContextsModule) buildHwServiceContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
Inseob Kimb554e592019-04-15 20:10:46 +0900365 if m.properties.Remove_comment == nil {
366 m.properties.Remove_comment = proptools.BoolPtr(true)
367 }
368
Inseob Kimcd616492020-03-24 23:06:40 +0900369 return m.buildGeneralContexts(ctx, inputs)
370}
371
372func (m *selinuxContextsModule) buildPropertyContexts(ctx android.ModuleContext, inputs android.Paths) android.Path {
373 builtCtxFile := m.buildGeneralContexts(ctx, inputs)
374
375 var apiFiles android.Paths
376 ctx.VisitDirectDepsWithTag(syspropLibraryDepTag, func(c android.Module) {
377 i, ok := c.(interface{ CurrentSyspropApiFile() android.Path })
378 if !ok {
379 panic(fmt.Errorf("unknown dependency %q for %q", ctx.OtherModuleName(c), ctx.ModuleName()))
380 }
381 apiFiles = append(apiFiles, i.CurrentSyspropApiFile())
382 })
383
384 // check compatibility with sysprop_library
385 if len(apiFiles) > 0 {
386 out := android.PathForModuleGen(ctx, ctx.ModuleName()+"_api_checked")
387 rule := android.NewRuleBuilder()
388
389 msg := `\n******************************\n` +
390 `API of sysprop_library doesn't match with property_contexts\n` +
391 `Please fix the breakage and rebuild.\n` +
392 `******************************\n`
393
394 rule.Command().
395 Text("( ").
396 BuiltTool(ctx, "sysprop_type_checker").
397 FlagForEachInput("--api ", apiFiles).
398 FlagWithInput("--context ", builtCtxFile).
399 Text(" || ( echo").Flag("-e").
400 Flag(`"` + msg + `"`).
401 Text("; exit 38) )")
402
403 rule.Command().Text("cp -f").Input(builtCtxFile).Output(out)
404 rule.Build(pctx, ctx, "property_contexts_check_api", "checking API: "+m.Name())
405 builtCtxFile = out
406 }
407
408 return builtCtxFile
Inseob Kimb554e592019-04-15 20:10:46 +0900409}
410
411func hwServiceFactory() android.Module {
412 m := newModule()
413 m.build = m.buildHwServiceContexts
414 return m
415}
416
417func propertyFactory() android.Module {
418 m := newModule()
Inseob Kimcd616492020-03-24 23:06:40 +0900419 m.build = m.buildPropertyContexts
420 m.deps = m.propertyContextsDeps
Inseob Kimb554e592019-04-15 20:10:46 +0900421 return m
422}
423
424func serviceFactory() android.Module {
425 m := newModule()
426 m.build = m.buildGeneralContexts
427 return m
428}