blob: 020357ae866ac0593fef6ac6e55d35839fad38ea [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
22 "github.com/google/blueprint/proptools"
23
24 "android/soong/android"
25)
26
27const (
28 coreMode = "core"
29 recoveryMode = "recovery"
30)
31
32type selinuxContextsProperties struct {
33 // Filenames under sepolicy directories, which will be used to generate contexts file.
34 Srcs []string `android:"path"`
35
36 Product_variables struct {
37 Debuggable struct {
38 Srcs []string
39 }
40
41 Address_sanitize struct {
42 Srcs []string
43 }
44 }
45
46 // Whether reqd_mask directory is included to sepolicy directories or not.
47 Reqd_mask *bool
48
49 // Whether the comments in generated contexts file will be removed or not.
50 Remove_comment *bool
51
52 // Whether the result context file is sorted with fc_sort or not.
53 Fc_sort *bool
54
55 // Make this module available when building for recovery
56 Recovery_available *bool
57
58 InRecovery bool `blueprint:"mutated"`
59}
60
61type fileContextsProperties struct {
62 // flatten_apex can be used to specify additional sources of file_contexts.
63 // Apex paths, /system/apex/{apex_name}, will be amended to the paths of file_contexts
64 // entries.
65 Flatten_apex struct {
66 Srcs []string
67 }
68}
69
70type selinuxContextsModule struct {
71 android.ModuleBase
72
73 properties selinuxContextsProperties
74 fileContextsProperties fileContextsProperties
75 build func(ctx android.ModuleContext, inputs android.Paths)
76 outputPath android.ModuleGenPath
77 installPath android.OutputPath
78}
79
80var (
81 reuseContextsDepTag = dependencyTag{name: "reuseContexts"}
82)
83
84func init() {
85 pctx.HostBinToolVariable("fc_sort", "fc_sort")
86
87 android.RegisterModuleType("file_contexts", fileFactory)
88 android.RegisterModuleType("hwservice_contexts", hwServiceFactory)
89 android.RegisterModuleType("property_contexts", propertyFactory)
90 android.RegisterModuleType("service_contexts", serviceFactory)
91
92 android.PreDepsMutators(func(ctx android.RegisterMutatorsContext) {
93 ctx.BottomUp("selinux_contexts", selinuxContextsMutator).Parallel()
94 })
95}
96
97func (m *selinuxContextsModule) inRecovery() bool {
98 return m.properties.InRecovery || m.ModuleBase.InstallInRecovery()
99}
100
101func (m *selinuxContextsModule) onlyInRecovery() bool {
102 return m.ModuleBase.InstallInRecovery()
103}
104
105func (m *selinuxContextsModule) InstallInRecovery() bool {
106 return m.inRecovery()
107}
108
109func (m *selinuxContextsModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
110 if m.InstallInRecovery() {
111 // Workaround for installing context files at the root of the recovery partition
112 m.installPath = android.PathForOutput(ctx,
113 "target", "product", ctx.Config().DeviceName(), "recovery", "root")
114 } else {
115 m.installPath = android.PathForModuleInstall(ctx, "etc", "selinux")
116 }
117
118 if m.inRecovery() && !m.onlyInRecovery() {
119 dep := ctx.GetDirectDepWithTag(m.Name(), reuseContextsDepTag)
120
121 if reuseDeps, ok := dep.(*selinuxContextsModule); ok {
122 m.outputPath = reuseDeps.outputPath
123 ctx.InstallFile(m.installPath, m.Name(), m.outputPath)
124 return
125 }
126 }
127
128 var inputs android.Paths
129
130 ctx.VisitDirectDepsWithTag(android.SourceDepTag, func(dep android.Module) {
131 segroup, ok := dep.(*fileGroup)
132 if !ok {
133 ctx.ModuleErrorf("srcs dependency %q is not an selinux filegroup",
134 ctx.OtherModuleName(dep))
135 return
136 }
137
138 if ctx.ProductSpecific() {
139 inputs = append(inputs, segroup.ProductPrivateSrcs()...)
140 } else if ctx.SocSpecific() {
141 inputs = append(inputs, segroup.SystemVendorSrcs()...)
142 inputs = append(inputs, segroup.VendorSrcs()...)
143 } else if ctx.DeviceSpecific() {
144 inputs = append(inputs, segroup.OdmSrcs()...)
145 } else {
146 inputs = append(inputs, segroup.SystemPrivateSrcs()...)
147 inputs = append(inputs, segroup.SystemExtPrivateSrcs()...)
148
149 if ctx.Config().ProductCompatibleProperty() {
150 inputs = append(inputs, segroup.SystemPublicSrcs()...)
151 }
152 }
153
154 if proptools.Bool(m.properties.Reqd_mask) {
155 inputs = append(inputs, segroup.SystemReqdMaskSrcs()...)
156 }
157 })
158
159 for _, src := range m.properties.Srcs {
160 // Module sources are handled above with VisitDirectDepsWithTag
161 if android.SrcIsModule(src) == "" {
162 inputs = append(inputs, android.PathForModuleSrc(ctx, src))
163 }
164 }
165
166 m.build(ctx, inputs)
167}
168
169func newModule() *selinuxContextsModule {
170 m := &selinuxContextsModule{}
171 m.AddProperties(
172 &m.properties,
173 )
174 android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibCommon)
175 android.AddLoadHook(m, func(ctx android.LoadHookContext) {
176 m.selinuxContextsHook(ctx)
177 })
178 return m
179}
180
181func (m *selinuxContextsModule) selinuxContextsHook(ctx android.LoadHookContext) {
182 // TODO: clean this up to use build/soong/android/variable.go after b/79249983
183 var srcs []string
184
185 if ctx.Config().Debuggable() {
186 srcs = append(srcs, m.properties.Product_variables.Debuggable.Srcs...)
187 }
188
189 for _, sanitize := range ctx.Config().SanitizeDevice() {
190 if sanitize == "address" {
191 srcs = append(srcs, m.properties.Product_variables.Address_sanitize.Srcs...)
192 break
193 }
194 }
195
196 m.properties.Srcs = append(m.properties.Srcs, srcs...)
197}
198
199func (m *selinuxContextsModule) AndroidMk() android.AndroidMkData {
200 return android.AndroidMkData{
201 Custom: func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
202 nameSuffix := ""
203 if m.inRecovery() && !m.onlyInRecovery() {
204 nameSuffix = ".recovery"
205 }
206 fmt.Fprintln(w, "\ninclude $(CLEAR_VARS)")
207 fmt.Fprintln(w, "LOCAL_PATH :=", moduleDir)
208 fmt.Fprintln(w, "LOCAL_MODULE :=", name+nameSuffix)
209 fmt.Fprintln(w, "LOCAL_MODULE_CLASS := ETC")
210 if m.Owner() != "" {
211 fmt.Fprintln(w, "LOCAL_MODULE_OWNER :=", m.Owner())
212 }
213 fmt.Fprintln(w, "LOCAL_MODULE_TAGS := optional")
214 fmt.Fprintln(w, "LOCAL_PREBUILT_MODULE_FILE :=", m.outputPath.String())
215 fmt.Fprintln(w, "LOCAL_MODULE_PATH :=", "$(OUT_DIR)/"+m.installPath.RelPathString())
216 fmt.Fprintln(w, "LOCAL_INSTALLED_MODULE_STEM :=", name)
217 fmt.Fprintln(w, "include $(BUILD_PREBUILT)")
218 },
219 }
220}
221
222func selinuxContextsMutator(ctx android.BottomUpMutatorContext) {
223 m, ok := ctx.Module().(*selinuxContextsModule)
224 if !ok {
225 return
226 }
227
228 var coreVariantNeeded bool = true
229 var recoveryVariantNeeded bool = false
230 if proptools.Bool(m.properties.Recovery_available) {
231 recoveryVariantNeeded = true
232 }
233
234 if m.ModuleBase.InstallInRecovery() {
235 recoveryVariantNeeded = true
236 coreVariantNeeded = false
237 }
238
239 var variants []string
240 if coreVariantNeeded {
241 variants = append(variants, coreMode)
242 }
243 if recoveryVariantNeeded {
244 variants = append(variants, recoveryMode)
245 }
246 mod := ctx.CreateVariations(variants...)
247
248 for i, v := range variants {
249 if v == recoveryMode {
250 m := mod[i].(*selinuxContextsModule)
251 m.properties.InRecovery = true
252
253 if coreVariantNeeded {
254 ctx.AddInterVariantDependency(reuseContextsDepTag, m, mod[i-1])
255 }
256 }
257 }
258}
259
260func (m *selinuxContextsModule) buildGeneralContexts(ctx android.ModuleContext, inputs android.Paths) {
261 m.outputPath = android.PathForModuleGen(ctx, ctx.ModuleName()+"_m4out")
262
263 rule := android.NewRuleBuilder()
264
265 rule.Command().
Dan Willemsen3c3e59b2019-06-19 10:52:50 -0700266 Tool(ctx.Config().PrebuiltBuildTool(ctx, "m4")).
267 Text("--fatal-warnings -s").
Inseob Kimb554e592019-04-15 20:10:46 +0900268 FlagForEachArg("-D", ctx.DeviceConfig().SepolicyM4Defs()).
269 Inputs(inputs).
270 FlagWithOutput("> ", m.outputPath)
271
272 if proptools.Bool(m.properties.Remove_comment) {
273 rule.Temporary(m.outputPath)
274
275 remove_comment_output := android.PathForModuleGen(ctx, ctx.ModuleName()+"_remove_comment")
276
277 rule.Command().
278 Text("sed -e 's/#.*$//' -e '/^$/d'").
279 Input(m.outputPath).
280 FlagWithOutput("> ", remove_comment_output)
281
282 m.outputPath = remove_comment_output
283 }
284
285 if proptools.Bool(m.properties.Fc_sort) {
286 rule.Temporary(m.outputPath)
287
288 sorted_output := android.PathForModuleGen(ctx, ctx.ModuleName()+"_sorted")
289
290 rule.Command().
291 Tool(ctx.Config().HostToolPath(ctx, "fc_sort")).
292 FlagWithInput("-i ", m.outputPath).
293 FlagWithOutput("-o ", sorted_output)
294
295 m.outputPath = sorted_output
296 }
297
298 rule.Build(pctx, ctx, "selinux_contexts", m.Name())
299
300 rule.DeleteTemporaryFiles()
301
302 ctx.InstallFile(m.installPath, ctx.ModuleName(), m.outputPath)
303}
304
305func (m *selinuxContextsModule) buildFileContexts(ctx android.ModuleContext, inputs android.Paths) {
306 if m.properties.Fc_sort == nil {
307 m.properties.Fc_sort = proptools.BoolPtr(true)
308 }
309
310 rule := android.NewRuleBuilder()
311
312 if ctx.Config().FlattenApex() {
313 for _, src := range m.fileContextsProperties.Flatten_apex.Srcs {
314 if m := android.SrcIsModule(src); m != "" {
315 ctx.ModuleErrorf(
316 "Module srcs dependency %q is not supported for flatten_apex.srcs", m)
317 return
318 }
319 for _, path := range android.PathsForModuleSrcExcludes(ctx, []string{src}, nil) {
320 out := android.PathForModuleGen(ctx, "flattened_apex", path.Rel())
321 apex_path := "/system/apex/" + strings.Replace(
322 strings.TrimSuffix(path.Base(), "-file_contexts"),
323 ".", "\\\\.", -1)
324
325 rule.Command().
326 Text("awk '/object_r/{printf(\""+apex_path+"%s\\n\",$0)}'").
327 Input(path).
328 FlagWithOutput("> ", out)
329
330 inputs = append(inputs, out)
331 }
332 }
333 }
334
335 rule.Build(pctx, ctx, m.Name(), "flattened_apex_file_contexts")
336 m.buildGeneralContexts(ctx, inputs)
337}
338
339func fileFactory() android.Module {
340 m := newModule()
341 m.AddProperties(&m.fileContextsProperties)
342 m.build = m.buildFileContexts
343 return m
344}
345
346func (m *selinuxContextsModule) buildHwServiceContexts(ctx android.ModuleContext, inputs android.Paths) {
347 if m.properties.Remove_comment == nil {
348 m.properties.Remove_comment = proptools.BoolPtr(true)
349 }
350
351 m.buildGeneralContexts(ctx, inputs)
352}
353
354func hwServiceFactory() android.Module {
355 m := newModule()
356 m.build = m.buildHwServiceContexts
357 return m
358}
359
360func propertyFactory() android.Module {
361 m := newModule()
362 m.build = m.buildGeneralContexts
363 return m
364}
365
366func serviceFactory() android.Module {
367 m := newModule()
368 m.build = m.buildGeneralContexts
369 return m
370}