blob: f280de96d1f6e4593bceaaa68bb329eebdeec407 [file] [log] [blame]
Tom Cherryad54d092017-04-19 16:18:50 -07001/*
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
Bart Van Assche878560d2023-02-14 07:54:58 -080017#include <fstream>
Tom Cherryad54d092017-04-19 16:18:50 -070018#include <functional>
Deyao Ren07595e12022-07-15 22:02:14 +000019#include <string_view>
Daniel Rosenberged8178c2023-01-03 18:28:34 -080020#include <thread>
Deyao Ren07595e12022-07-15 22:02:14 +000021#include <type_traits>
Tom Cherryad54d092017-04-19 16:18:50 -070022
23#include <android-base/file.h>
Nikita Ioffe9e4b1112020-12-11 17:59:38 +000024#include <android-base/logging.h>
Tom Cherry0e40ba32020-07-09 08:47:24 -070025#include <android-base/properties.h>
Bart Van Assche878560d2023-02-14 07:54:58 -080026#include <android-base/stringprintf.h>
Carlos Galo14471202022-12-07 23:39:05 +000027#include <android/api-level.h>
Tom Cherryad54d092017-04-19 16:18:50 -070028#include <gtest/gtest.h>
Deyao Ren07595e12022-07-15 22:02:14 +000029#include <selinux/selinux.h>
Carlos Galo14471202022-12-07 23:39:05 +000030#include <sys/resource.h>
Tom Cherryad54d092017-04-19 16:18:50 -070031
32#include "action.h"
Tom Cherry7fd3bc22018-02-13 15:36:14 -080033#include "action_manager.h"
Tom Cherry0f6417f2018-02-13 15:25:29 -080034#include "action_parser.h"
Tom Cherryd52a5b32019-07-22 16:05:36 -070035#include "builtin_arguments.h"
Tom Cherryad54d092017-04-19 16:18:50 -070036#include "builtins.h"
37#include "import_parser.h"
Deyao Ren07595e12022-07-15 22:02:14 +000038#include "init.h"
Tom Cherryad54d092017-04-19 16:18:50 -070039#include "keyword_map.h"
Tom Cherry67dee622017-07-27 12:54:48 -070040#include "parser.h"
Steven Moreland6f5333a2017-11-13 15:31:54 -080041#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070042#include "service_list.h"
43#include "service_parser.h"
Tom Cherryad54d092017-04-19 16:18:50 -070044#include "util.h"
45
Tom Cherry0e40ba32020-07-09 08:47:24 -070046using android::base::GetIntProperty;
Jooyung Han678f0b42022-07-07 15:25:02 +090047using android::base::GetProperty;
48using android::base::SetProperty;
Bart Van Assche878560d2023-02-14 07:54:58 -080049using android::base::StringPrintf;
Deyao Ren07595e12022-07-15 22:02:14 +000050using android::base::StringReplace;
Jooyung Han678f0b42022-07-07 15:25:02 +090051using android::base::WaitForProperty;
52using namespace std::literals;
Tom Cherry0e40ba32020-07-09 08:47:24 -070053
Tom Cherry81f5d3e2017-06-22 12:53:17 -070054namespace android {
55namespace init {
56
Tom Cherryad54d092017-04-19 16:18:50 -070057using ActionManagerCommand = std::function<void(ActionManager&)>;
58
Tom Cherryd52a5b32019-07-22 16:05:36 -070059void TestInit(const std::string& init_script_file, const BuiltinFunctionMap& test_function_map,
Jooyung Hanbadb7de2022-05-10 03:16:51 +090060 const std::vector<ActionManagerCommand>& commands, ActionManager* action_manager,
61 ServiceList* service_list) {
Tom Cherryad54d092017-04-19 16:18:50 -070062 Action::set_function_map(&test_function_map);
63
64 Parser parser;
Jooyung Hand51fb542024-08-21 16:25:10 +090065 parser.AddSectionParser("service", std::make_unique<ServiceParser>(service_list, nullptr));
Jooyung Hanbadb7de2022-05-10 03:16:51 +090066 parser.AddSectionParser("on", std::make_unique<ActionParser>(action_manager, nullptr));
Tom Cherryad54d092017-04-19 16:18:50 -070067 parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
68
69 ASSERT_TRUE(parser.ParseConfig(init_script_file));
70
71 for (const auto& command : commands) {
Jooyung Hanbadb7de2022-05-10 03:16:51 +090072 command(*action_manager);
Tom Cherryad54d092017-04-19 16:18:50 -070073 }
74
Jooyung Hanbadb7de2022-05-10 03:16:51 +090075 while (action_manager->HasMoreCommands()) {
76 action_manager->ExecuteOneCommand();
Tom Cherryad54d092017-04-19 16:18:50 -070077 }
78}
79
Tom Cherryd52a5b32019-07-22 16:05:36 -070080void TestInitText(const std::string& init_script, const BuiltinFunctionMap& test_function_map,
Jooyung Hanbadb7de2022-05-10 03:16:51 +090081 const std::vector<ActionManagerCommand>& commands, ActionManager* action_manager,
82 ServiceList* service_list) {
Tom Cherryad54d092017-04-19 16:18:50 -070083 TemporaryFile tf;
84 ASSERT_TRUE(tf.fd != -1);
85 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
Jooyung Hanbadb7de2022-05-10 03:16:51 +090086 TestInit(tf.path, test_function_map, commands, action_manager, service_list);
Tom Cherryad54d092017-04-19 16:18:50 -070087}
88
89TEST(init, SimpleEventTrigger) {
90 bool expect_true = false;
91 std::string init_script =
92 R"init(
93on boot
94pass_test
95)init";
96
Tom Cherryd52a5b32019-07-22 16:05:36 -070097 auto do_pass_test = [&expect_true](const BuiltinArguments&) {
98 expect_true = true;
99 return Result<void>{};
100 };
101 BuiltinFunctionMap test_function_map = {
102 {"pass_test", {0, 0, {false, do_pass_test}}},
103 };
Tom Cherryad54d092017-04-19 16:18:50 -0700104
105 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
106 std::vector<ActionManagerCommand> commands{trigger_boot};
107
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900108 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800109 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900110 TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
Tom Cherryad54d092017-04-19 16:18:50 -0700111
112 EXPECT_TRUE(expect_true);
113}
114
Nikita Ioffeaaab5962019-10-10 20:42:37 +0100115TEST(init, WrongEventTrigger) {
116 std::string init_script =
117 R"init(
118on boot:
119pass_test
120)init";
121
122 TemporaryFile tf;
123 ASSERT_TRUE(tf.fd != -1);
124 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
125
126 ActionManager am;
127
128 Parser parser;
129 parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
130
131 ASSERT_TRUE(parser.ParseConfig(tf.path));
132 ASSERT_EQ(1u, parser.parse_error_count());
133}
134
Tom Cherryad54d092017-04-19 16:18:50 -0700135TEST(init, EventTriggerOrder) {
136 std::string init_script =
137 R"init(
138on boot
139execute_first
140
141on boot && property:ro.hardware=*
142execute_second
143
144on boot
145execute_third
146
147)init";
148
149 int num_executed = 0;
Tom Cherryd52a5b32019-07-22 16:05:36 -0700150 auto do_execute_first = [&num_executed](const BuiltinArguments&) {
151 EXPECT_EQ(0, num_executed++);
152 return Result<void>{};
153 };
154 auto do_execute_second = [&num_executed](const BuiltinArguments&) {
155 EXPECT_EQ(1, num_executed++);
156 return Result<void>{};
157 };
158 auto do_execute_third = [&num_executed](const BuiltinArguments&) {
159 EXPECT_EQ(2, num_executed++);
160 return Result<void>{};
161 };
162
163 BuiltinFunctionMap test_function_map = {
164 {"execute_first", {0, 0, {false, do_execute_first}}},
165 {"execute_second", {0, 0, {false, do_execute_second}}},
166 {"execute_third", {0, 0, {false, do_execute_third}}},
167 };
Tom Cherryad54d092017-04-19 16:18:50 -0700168
169 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
170 std::vector<ActionManagerCommand> commands{trigger_boot};
171
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900172 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800173 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900174 TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
Florian Mayer6268f6a2022-05-11 01:02:01 +0000175 EXPECT_EQ(3, num_executed);
Steven Moreland6f5333a2017-11-13 15:31:54 -0800176}
177
178TEST(init, OverrideService) {
179 std::string init_script = R"init(
180service A something
181 class first
Steven Morelande5349192023-04-24 23:54:59 +0000182 user nobody
Steven Moreland6f5333a2017-11-13 15:31:54 -0800183
184service A something
185 class second
Steven Morelande5349192023-04-24 23:54:59 +0000186 user nobody
Steven Moreland6f5333a2017-11-13 15:31:54 -0800187 override
188
189)init";
190
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900191 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800192 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900193 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
Steven Moreland6f5333a2017-11-13 15:31:54 -0800194 ASSERT_EQ(1, std::distance(service_list.begin(), service_list.end()));
195
196 auto service = service_list.begin()->get();
197 ASSERT_NE(nullptr, service);
198 EXPECT_EQ(std::set<std::string>({"second"}), service->classnames());
199 EXPECT_EQ("A", service->name());
200 EXPECT_TRUE(service->is_override());
Tom Cherryad54d092017-04-19 16:18:50 -0700201}
202
Bart Van Assche5d188912022-11-14 09:30:51 -0800203TEST(init, StartConsole) {
Jiyong Park5b7a51a2022-12-20 09:18:49 +0900204 if (GetProperty("ro.build.type", "") == "user") {
205 GTEST_SKIP() << "Must run on userdebug/eng builds. b/262090304";
206 return;
207 }
Daniel Rosenbergb8baa8d2023-04-07 13:02:42 -0700208 if (getuid() != 0) {
209 GTEST_SKIP() << "Must be run as root.";
210 return;
211 }
Bart Van Assche5d188912022-11-14 09:30:51 -0800212 std::string init_script = R"init(
213service console /system/bin/sh
214 class core
Jiyong Parkae412802022-12-15 16:29:01 +0900215 console null
Bart Van Assche5d188912022-11-14 09:30:51 -0800216 disabled
217 user root
218 group root shell log readproc
Bart Van Assche3b21d952022-11-22 16:53:05 -0800219 seclabel u:r:shell:s0
Bart Van Assche5d188912022-11-14 09:30:51 -0800220 setenv HOSTNAME console
221)init";
222
223 ActionManager action_manager;
224 ServiceList service_list;
225 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
226 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
227
228 auto service = service_list.begin()->get();
229 ASSERT_NE(service, nullptr);
230 ASSERT_RESULT_OK(service->Start());
231 const pid_t pid = service->pid();
232 ASSERT_GT(pid, 0);
Bart Van Assche3b21d952022-11-22 16:53:05 -0800233 EXPECT_NE(getsid(pid), 0);
Bart Van Assche5d188912022-11-14 09:30:51 -0800234 service->Stop();
235}
236
Deyao Ren07595e12022-07-15 22:02:14 +0000237static std::string GetSecurityContext() {
238 char* ctx;
239 if (getcon(&ctx) == -1) {
240 ADD_FAILURE() << "Failed to call getcon : " << strerror(errno);
241 }
242 std::string result = std::string(ctx);
243 freecon(ctx);
244 return result;
245}
246
247void TestStartApexServices(const std::vector<std::string>& service_names,
248 const std::string& apex_name) {
249 for (auto const& svc : service_names) {
250 auto service = ServiceList::GetInstance().FindService(svc);
251 ASSERT_NE(nullptr, service);
252 ASSERT_RESULT_OK(service->Start());
253 ASSERT_TRUE(service->IsRunning());
254 LOG(INFO) << "Service " << svc << " is running";
255 if (!apex_name.empty()) {
256 service->set_filename("/apex/" + apex_name + "/init_test.rc");
257 } else {
258 service->set_filename("");
259 }
260 }
261 if (!apex_name.empty()) {
262 auto apex_services = ServiceList::GetInstance().FindServicesByApexName(apex_name);
263 EXPECT_EQ(service_names.size(), apex_services.size());
264 }
265}
266
267void TestStopApexServices(const std::vector<std::string>& service_names, bool expect_to_run) {
268 for (auto const& svc : service_names) {
269 auto service = ServiceList::GetInstance().FindService(svc);
270 ASSERT_NE(nullptr, service);
271 EXPECT_EQ(expect_to_run, service->IsRunning());
272 }
Deyao Ren238e9092022-07-21 23:05:13 +0000273}
274
275void TestRemoveApexService(const std::vector<std::string>& service_names, bool exist) {
276 for (auto const& svc : service_names) {
277 auto service = ServiceList::GetInstance().FindService(svc);
278 ASSERT_EQ(exist, service != nullptr);
279 }
Deyao Ren07595e12022-07-15 22:02:14 +0000280}
281
282void InitApexService(const std::string_view& init_template) {
283 std::string init_script = StringReplace(init_template, "$selabel",
284 GetSecurityContext(), true);
285
Deyao Ren238e9092022-07-21 23:05:13 +0000286 TestInitText(init_script, BuiltinFunctionMap(), {}, &ActionManager::GetInstance(),
Deyao Ren07595e12022-07-15 22:02:14 +0000287 &ServiceList::GetInstance());
288}
289
deyaoren@google.com909bc472022-09-07 22:25:44 +0000290void CleanupApexServices() {
291 std::vector<std::string> names;
292 for (const auto& s : ServiceList::GetInstance()) {
293 names.push_back(s->name());
294 }
295
296 for (const auto& name : names) {
297 auto s = ServiceList::GetInstance().FindService(name);
298 auto pid = s->pid();
299 ServiceList::GetInstance().RemoveService(*s);
300 if (pid > 0) {
301 kill(pid, SIGTERM);
302 kill(pid, SIGKILL);
303 }
304 }
305
306 ActionManager::GetInstance().RemoveActionIf([&](const std::unique_ptr<Action>& s) -> bool {
307 return true;
308 });
309}
310
Deyao Ren07595e12022-07-15 22:02:14 +0000311void TestApexServicesInit(const std::vector<std::string>& apex_services,
312 const std::vector<std::string>& other_apex_services,
313 const std::vector<std::string> non_apex_services) {
314 auto num_svc = apex_services.size() + other_apex_services.size() + non_apex_services.size();
Deyao Ren238e9092022-07-21 23:05:13 +0000315 ASSERT_EQ(num_svc, ServiceList::GetInstance().size());
Deyao Ren07595e12022-07-15 22:02:14 +0000316
317 TestStartApexServices(apex_services, "com.android.apex.test_service");
318 TestStartApexServices(other_apex_services, "com.android.other_apex.test_service");
319 TestStartApexServices(non_apex_services, /*apex_anme=*/ "");
320
321 StopServicesFromApex("com.android.apex.test_service");
322 TestStopApexServices(apex_services, /*expect_to_run=*/ false);
323 TestStopApexServices(other_apex_services, /*expect_to_run=*/ true);
324 TestStopApexServices(non_apex_services, /*expect_to_run=*/ true);
325
Deyao Ren238e9092022-07-21 23:05:13 +0000326 RemoveServiceAndActionFromApex("com.android.apex.test_service");
327 ASSERT_EQ(other_apex_services.size() + non_apex_services.size(),
328 ServiceList::GetInstance().size());
329
330 // TODO(b/244232142): Add test to check if actions are removed
331 TestRemoveApexService(apex_services, /*exist*/ false);
332 TestRemoveApexService(other_apex_services, /*exist*/ true);
333 TestRemoveApexService(non_apex_services, /*exist*/ true);
334
deyaoren@google.com909bc472022-09-07 22:25:44 +0000335 CleanupApexServices();
Deyao Ren07595e12022-07-15 22:02:14 +0000336}
337
338TEST(init, StopServiceByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900339 if (getuid() != 0) {
340 GTEST_SKIP() << "Must be run as root.";
341 return;
342 }
Deyao Ren07595e12022-07-15 22:02:14 +0000343 std::string_view script_template = R"init(
344service apex_test_service /system/bin/yes
345 user shell
346 group shell
347 seclabel $selabel
348)init";
349 InitApexService(script_template);
350 TestApexServicesInit({"apex_test_service"}, {}, {});
351}
352
353TEST(init, StopMultipleServicesByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900354 if (getuid() != 0) {
355 GTEST_SKIP() << "Must be run as root.";
356 return;
357 }
Deyao Ren07595e12022-07-15 22:02:14 +0000358 std::string_view script_template = R"init(
359service apex_test_service_multiple_a /system/bin/yes
360 user shell
361 group shell
362 seclabel $selabel
363service apex_test_service_multiple_b /system/bin/id
364 user shell
365 group shell
366 seclabel $selabel
367)init";
368 InitApexService(script_template);
369 TestApexServicesInit({"apex_test_service_multiple_a",
370 "apex_test_service_multiple_b"}, {}, {});
371}
372
373TEST(init, StopServicesFromMultipleApexes) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900374 if (getuid() != 0) {
375 GTEST_SKIP() << "Must be run as root.";
376 return;
377 }
Deyao Ren07595e12022-07-15 22:02:14 +0000378 std::string_view apex_script_template = R"init(
379service apex_test_service_multi_apex_a /system/bin/yes
380 user shell
381 group shell
382 seclabel $selabel
383service apex_test_service_multi_apex_b /system/bin/id
384 user shell
385 group shell
386 seclabel $selabel
387)init";
388 InitApexService(apex_script_template);
389
390 std::string_view other_apex_script_template = R"init(
391service apex_test_service_multi_apex_c /system/bin/yes
392 user shell
393 group shell
394 seclabel $selabel
395)init";
396 InitApexService(other_apex_script_template);
397
398 TestApexServicesInit({"apex_test_service_multi_apex_a",
399 "apex_test_service_multi_apex_b"}, {"apex_test_service_multi_apex_c"}, {});
400}
401
402TEST(init, StopServicesFromApexAndNonApex) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900403 if (getuid() != 0) {
404 GTEST_SKIP() << "Must be run as root.";
405 return;
406 }
Deyao Ren07595e12022-07-15 22:02:14 +0000407 std::string_view apex_script_template = R"init(
408service apex_test_service_apex_a /system/bin/yes
409 user shell
410 group shell
411 seclabel $selabel
412service apex_test_service_apex_b /system/bin/id
413 user shell
414 group shell
415 seclabel $selabel
416)init";
417 InitApexService(apex_script_template);
418
419 std::string_view non_apex_script_template = R"init(
420service apex_test_service_non_apex /system/bin/yes
421 user shell
422 group shell
423 seclabel $selabel
424)init";
425 InitApexService(non_apex_script_template);
426
427 TestApexServicesInit({"apex_test_service_apex_a",
428 "apex_test_service_apex_b"}, {}, {"apex_test_service_non_apex"});
429}
430
431TEST(init, StopServicesFromApexMixed) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900432 if (getuid() != 0) {
433 GTEST_SKIP() << "Must be run as root.";
434 return;
435 }
Deyao Ren07595e12022-07-15 22:02:14 +0000436 std::string_view script_template = R"init(
437service apex_test_service_mixed_a /system/bin/yes
438 user shell
439 group shell
440 seclabel $selabel
441)init";
442 InitApexService(script_template);
443
444 std::string_view other_apex_script_template = R"init(
445service apex_test_service_mixed_b /system/bin/yes
446 user shell
447 group shell
448 seclabel $selabel
449)init";
450 InitApexService(other_apex_script_template);
451
452 std::string_view non_apex_script_template = R"init(
453service apex_test_service_mixed_c /system/bin/yes
454 user shell
455 group shell
456 seclabel $selabel
457)init";
458 InitApexService(non_apex_script_template);
459
460 TestApexServicesInit({"apex_test_service_mixed_a"},
461 {"apex_test_service_mixed_b"}, {"apex_test_service_mixed_c"});
462}
463
Tom Cherryad54d092017-04-19 16:18:50 -0700464TEST(init, EventTriggerOrderMultipleFiles) {
465 // 6 total files, which should have their triggers executed in the following order:
466 // 1: start - original script parsed
467 // 2: first_import - immediately imported by first_script
468 // 3: dir_a - file named 'a.rc' in dir; dir is imported after first_import
469 // 4: a_import - file imported by dir_a
470 // 5: dir_b - file named 'b.rc' in dir
471 // 6: last_import - imported after dir is imported
472
473 TemporaryFile first_import;
474 ASSERT_TRUE(first_import.fd != -1);
475 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", first_import.fd));
476
477 TemporaryFile dir_a_import;
478 ASSERT_TRUE(dir_a_import.fd != -1);
479 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 4", dir_a_import.fd));
480
481 TemporaryFile last_import;
482 ASSERT_TRUE(last_import.fd != -1);
483 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 6", last_import.fd));
484
485 TemporaryDir dir;
486 // clang-format off
487 std::string dir_a_script = "import " + std::string(dir_a_import.path) + "\n"
488 "on boot\n"
489 "execute 3";
490 // clang-format on
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700491 // WriteFile() ensures the right mode is set
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900492 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
Tom Cherryad54d092017-04-19 16:18:50 -0700493
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900494 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
Tom Cherryad54d092017-04-19 16:18:50 -0700495
496 // clang-format off
497 std::string start_script = "import " + std::string(first_import.path) + "\n"
498 "import " + std::string(dir.path) + "\n"
499 "import " + std::string(last_import.path) + "\n"
500 "on boot\n"
501 "execute 1";
502 // clang-format on
503 TemporaryFile start;
504 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
505
506 int num_executed = 0;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700507 auto execute_command = [&num_executed](const BuiltinArguments& args) {
Tom Cherryad54d092017-04-19 16:18:50 -0700508 EXPECT_EQ(2U, args.size());
509 EXPECT_EQ(++num_executed, std::stoi(args[1]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700510 return Result<void>{};
Tom Cherryad54d092017-04-19 16:18:50 -0700511 };
512
Tom Cherryd52a5b32019-07-22 16:05:36 -0700513 BuiltinFunctionMap test_function_map = {
514 {"execute", {1, 1, {false, execute_command}}},
515 };
Tom Cherryad54d092017-04-19 16:18:50 -0700516
517 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
518 std::vector<ActionManagerCommand> commands{trigger_boot};
519
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900520 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800521 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900522 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
Tom Cherryad54d092017-04-19 16:18:50 -0700523
524 EXPECT_EQ(6, num_executed);
525}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700526
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900527BuiltinFunctionMap GetTestFunctionMapForLazyLoad(int& num_executed, ActionManager& action_manager) {
528 auto execute_command = [&num_executed](const BuiltinArguments& args) {
529 EXPECT_EQ(2U, args.size());
530 EXPECT_EQ(++num_executed, std::stoi(args[1]));
531 return Result<void>{};
532 };
533 auto load_command = [&action_manager](const BuiltinArguments& args) -> Result<void> {
534 EXPECT_EQ(2U, args.size());
535 Parser parser;
536 parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, nullptr));
537 if (!parser.ParseConfig(args[1])) {
538 return Error() << "Failed to load";
539 }
540 return Result<void>{};
541 };
542 auto trigger_command = [&action_manager](const BuiltinArguments& args) {
543 EXPECT_EQ(2U, args.size());
544 LOG(INFO) << "Queue event trigger: " << args[1];
545 action_manager.QueueEventTrigger(args[1]);
546 return Result<void>{};
547 };
548 BuiltinFunctionMap test_function_map = {
549 {"execute", {1, 1, {false, execute_command}}},
550 {"load", {1, 1, {false, load_command}}},
551 {"trigger", {1, 1, {false, trigger_command}}},
552 };
553 return test_function_map;
554}
555
556TEST(init, LazilyLoadedActionsCantBeTriggeredByTheSameTrigger) {
557 // "start" script loads "lazy" script. Even though "lazy" scripts
558 // defines "on boot" action, it's not executed by the current "boot"
559 // event because it's already processed.
560 TemporaryFile lazy;
561 ASSERT_TRUE(lazy.fd != -1);
562 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", lazy.fd));
563
564 TemporaryFile start;
565 // clang-format off
566 std::string start_script = "on boot\n"
567 "load " + std::string(lazy.path) + "\n"
568 "execute 1";
569 // clang-format on
570 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
571
572 int num_executed = 0;
573 ActionManager action_manager;
574 ServiceList service_list;
575 BuiltinFunctionMap test_function_map =
576 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
577
578 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
579 std::vector<ActionManagerCommand> commands{trigger_boot};
580 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
581
582 EXPECT_EQ(1, num_executed);
583}
584
585TEST(init, LazilyLoadedActionsCanBeTriggeredByTheNextTrigger) {
586 // "start" script loads "lazy" script and then triggers "next" event
587 // which executes "on next" action loaded by the previous command.
588 TemporaryFile lazy;
589 ASSERT_TRUE(lazy.fd != -1);
590 ASSERT_TRUE(android::base::WriteStringToFd("on next\nexecute 2", lazy.fd));
591
592 TemporaryFile start;
593 // clang-format off
594 std::string start_script = "on boot\n"
595 "load " + std::string(lazy.path) + "\n"
596 "execute 1\n"
597 "trigger next";
598 // clang-format on
599 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
600
601 int num_executed = 0;
602 ActionManager action_manager;
603 ServiceList service_list;
604 BuiltinFunctionMap test_function_map =
605 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
606
607 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
608 std::vector<ActionManagerCommand> commands{trigger_boot};
609 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
610
611 EXPECT_EQ(2, num_executed);
612}
613
Steven Morelande5349192023-04-24 23:54:59 +0000614TEST(init, RejectsNoUserStartingInV) {
615 std::string init_script =
616 R"init(
617service A something
618 class first
619)init";
620
621 TemporaryFile tf;
622 ASSERT_TRUE(tf.fd != -1);
623 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
624
625 ServiceList service_list;
626 Parser parser;
Jooyung Hand51fb542024-08-21 16:25:10 +0900627 parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, nullptr));
Steven Morelande5349192023-04-24 23:54:59 +0000628
629 ASSERT_TRUE(parser.ParseConfig(tf.path));
630
Steven Moreland5088e582024-05-29 00:03:19 +0000631 if (GetIntProperty("ro.vendor.api_level", 0) > 202404) {
Steven Morelande5349192023-04-24 23:54:59 +0000632 ASSERT_EQ(1u, parser.parse_error_count());
633 } else {
634 ASSERT_EQ(0u, parser.parse_error_count());
635 }
636}
637
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100638TEST(init, RejectsCriticalAndOneshotService) {
Tom Cherry0e40ba32020-07-09 08:47:24 -0700639 if (GetIntProperty("ro.product.first_api_level", 10000) < 30) {
640 GTEST_SKIP() << "Test only valid for devices launching with R or later";
641 }
642
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100643 std::string init_script =
644 R"init(
645service A something
646 class first
Steven Morelande5349192023-04-24 23:54:59 +0000647 user root
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100648 critical
649 oneshot
650)init";
651
652 TemporaryFile tf;
653 ASSERT_TRUE(tf.fd != -1);
654 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
655
656 ServiceList service_list;
657 Parser parser;
Jooyung Hand51fb542024-08-21 16:25:10 +0900658 parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, nullptr));
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100659
660 ASSERT_TRUE(parser.ParseConfig(tf.path));
661 ASSERT_EQ(1u, parser.parse_error_count());
662}
663
Carlos Galo14471202022-12-07 23:39:05 +0000664TEST(init, MemLockLimit) {
665 // Test is enforced only for U+ devices
666 if (android::base::GetIntProperty("ro.vendor.api_level", 0) < __ANDROID_API_U__) {
667 GTEST_SKIP();
668 }
669
670 // Verify we are running memlock at, or under, 64KB
671 const unsigned long max_limit = 65536;
672 struct rlimit curr_limit;
673 ASSERT_EQ(getrlimit(RLIMIT_MEMLOCK, &curr_limit), 0);
674 ASSERT_LE(curr_limit.rlim_cur, max_limit);
675 ASSERT_LE(curr_limit.rlim_max, max_limit);
676}
677
Bart Van Assche468067a2023-02-14 09:52:31 -0800678void CloseAllFds() {
679 DIR* dir;
680 struct dirent* ent;
681 int fd;
682
683 if ((dir = opendir("/proc/self/fd"))) {
684 while ((ent = readdir(dir))) {
685 if (sscanf(ent->d_name, "%d", &fd) == 1) {
686 close(fd);
687 }
688 }
689 closedir(dir);
690 }
691}
692
Bart Van Assche947d75f2023-02-14 07:44:54 -0800693pid_t ForkExecvpAsync(const char* argv[]) {
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800694 pid_t pid = fork();
695 if (pid == 0) {
Bart Van Assche947d75f2023-02-14 07:44:54 -0800696 // Child process.
Bart Van Assche468067a2023-02-14 09:52:31 -0800697 CloseAllFds();
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800698
Bart Van Assche947d75f2023-02-14 07:44:54 -0800699 execvp(argv[0], const_cast<char**>(argv));
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800700 PLOG(ERROR) << "exec in ForkExecvpAsync init test";
701 _exit(EXIT_FAILURE);
702 }
Bart Van Assche947d75f2023-02-14 07:44:54 -0800703 // Parent process.
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800704 if (pid == -1) {
705 PLOG(ERROR) << "fork in ForkExecvpAsync init test";
706 return -1;
707 }
708 return pid;
709}
710
Bart Van Assche878560d2023-02-14 07:54:58 -0800711pid_t TracerPid(pid_t pid) {
712 static constexpr std::string_view prefix{"TracerPid:"};
713 std::ifstream is(StringPrintf("/proc/%d/status", pid));
714 std::string line;
715 while (std::getline(is, line)) {
716 if (line.find(prefix) == 0) {
717 return atoi(line.substr(prefix.length()).c_str());
718 }
719 }
720 return -1;
721}
722
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800723TEST(init, GentleKill) {
Daniel Rosenberg2f050862023-02-08 17:25:47 -0800724 if (getuid() != 0) {
725 GTEST_SKIP() << "Must be run as root.";
726 return;
727 }
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800728 std::string init_script = R"init(
729service test_gentle_kill /system/bin/sleep 1000
730 disabled
731 oneshot
732 gentle_kill
733 user root
734 group root
735 seclabel u:r:toolbox:s0
736)init";
737
738 ActionManager action_manager;
739 ServiceList service_list;
740 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
741 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
742
743 auto service = service_list.begin()->get();
744 ASSERT_NE(service, nullptr);
745 ASSERT_RESULT_OK(service->Start());
746 const pid_t pid = service->pid();
747 ASSERT_GT(pid, 0);
748 EXPECT_NE(getsid(pid), 0);
749
750 TemporaryFile logfile;
751 logfile.DoNotRemove();
752 ASSERT_TRUE(logfile.fd != -1);
753
Bart Van Assche947d75f2023-02-14 07:44:54 -0800754 std::string pid_str = std::to_string(pid);
755 const char* argv[] = {"/system/bin/strace", "-o", logfile.path, "-e", "signal", "-p",
756 pid_str.c_str(), nullptr};
757 pid_t strace_pid = ForkExecvpAsync(argv);
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800758
Bart Van Assche878560d2023-02-14 07:54:58 -0800759 // Give strace the chance to connect
760 while (TracerPid(pid) == 0) {
761 std::this_thread::sleep_for(10ms);
762 }
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800763 service->Stop();
764
765 int status;
766 waitpid(strace_pid, &status, 0);
767
768 std::string logs;
769 android::base::ReadFdToString(logfile.fd, &logs);
Bart Van Assche947d75f2023-02-14 07:44:54 -0800770 ASSERT_NE(logs.find("killed by SIGTERM"), std::string::npos);
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800771}
772
Nikita Ioffe9e4b1112020-12-11 17:59:38 +0000773class TestCaseLogger : public ::testing::EmptyTestEventListener {
774 void OnTestStart(const ::testing::TestInfo& test_info) override {
775#ifdef __ANDROID__
776 LOG(INFO) << "===== " << test_info.test_suite_name() << "::" << test_info.name() << " ("
777 << test_info.file() << ":" << test_info.line() << ")";
778#else
779 UNUSED(test_info);
780#endif
781 }
782};
783
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700784} // namespace init
785} // namespace android
Tom Cherrydcb3d152019-08-07 16:02:28 -0700786
787int SubcontextTestChildMain(int, char**);
788int FirmwareTestChildMain(int, char**);
789
790int main(int argc, char** argv) {
791 if (argc > 1 && !strcmp(argv[1], "subcontext")) {
792 return SubcontextTestChildMain(argc, argv);
793 }
794
795 if (argc > 1 && !strcmp(argv[1], "firmware")) {
796 return FirmwareTestChildMain(argc, argv);
797 }
798
799 testing::InitGoogleTest(&argc, argv);
Nikita Ioffe9e4b1112020-12-11 17:59:38 +0000800 testing::UnitTest::GetInstance()->listeners().Append(new android::init::TestCaseLogger());
Tom Cherrydcb3d152019-08-07 16:02:28 -0700801 return RUN_ALL_TESTS();
802}