xref: /aosp_15_r20/system/core/init/subcontext.h (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <signal.h>
20 
21 #include <string>
22 #include <vector>
23 
24 #include <android-base/unique_fd.h>
25 
26 #include "builtins.h"
27 #include "result.h"
28 #include "system/core/init/subcontext.pb.h"
29 
30 namespace android {
31 namespace init {
32 
33 static constexpr const char kInitContext[] = "u:r:init:s0";
34 static constexpr const char kVendorContext[] = "u:r:vendor_init:s0";
35 static constexpr const char kTestContext[] = "test-test-test";
36 
37 class Subcontext {
38   public:
39     Subcontext(std::vector<std::string> path_prefixes, std::vector<std::string> partitions,
40                std::string_view context, bool host = false)
path_prefixes_(std::move (path_prefixes))41         : path_prefixes_(std::move(path_prefixes)),
42           partitions_(std::move(partitions)),
43           context_(context.begin(), context.end()),
44           pid_(0) {
45         if (!host) {
46             Fork();
47         }
48     }
49 
50     Result<void> Execute(const std::vector<std::string>& args);
51     Result<std::vector<std::string>> ExpandArgs(const std::vector<std::string>& args);
52     void Restart();
53     bool PathMatchesSubcontext(const std::string& path) const;
54     bool PartitionMatchesSubcontext(const std::string& partition) const;
55     void SetApexList(std::vector<std::string>&& apex_list);
56 
context()57     const std::string& context() const { return context_; }
pid()58     pid_t pid() const { return pid_; }
59 
60   private:
61     void Fork();
62     Result<SubcontextReply> TransmitMessage(const SubcontextCommand& subcontext_command);
63 
64     std::vector<std::string> path_prefixes_;
65     std::vector<std::string> partitions_;
66     std::vector<std::string> apex_list_;
67     std::string context_;
68     pid_t pid_;
69     android::base::unique_fd socket_;
70 };
71 
72 int SubcontextMain(int argc, char** argv, const BuiltinFunctionMap* function_map);
73 void InitializeSubcontext();
74 void InitializeHostSubcontext(std::vector<std::string> vendor_prefixes);
75 Subcontext* GetSubcontext();
76 bool SubcontextChildReap(pid_t pid);
77 void SubcontextTerminate();
78 
79 }  // namespace init
80 }  // namespace android
81