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 #include <fstream>
18 #include <functional>
19 #include <string_view>
20 #include <thread>
21 #include <type_traits>
22
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/properties.h>
26 #include <android-base/stringprintf.h>
27 #include <android/api-level.h>
28 #include <gtest/gtest.h>
29 #include <selinux/selinux.h>
30 #include <sys/resource.h>
31
32 #include "action.h"
33 #include "action_manager.h"
34 #include "action_parser.h"
35 #include "builtin_arguments.h"
36 #include "builtins.h"
37 #include "import_parser.h"
38 #include "init.h"
39 #include "keyword_map.h"
40 #include "parser.h"
41 #include "service.h"
42 #include "service_list.h"
43 #include "service_parser.h"
44 #include "util.h"
45
46 using android::base::GetIntProperty;
47 using android::base::GetProperty;
48 using android::base::SetProperty;
49 using android::base::StringPrintf;
50 using android::base::StringReplace;
51 using android::base::WaitForProperty;
52 using namespace std::literals;
53
54 namespace android {
55 namespace init {
56
57 using ActionManagerCommand = std::function<void(ActionManager&)>;
58
TestInit(const std::string & init_script_file,const BuiltinFunctionMap & test_function_map,const std::vector<ActionManagerCommand> & commands,ActionManager * action_manager,ServiceList * service_list)59 void TestInit(const std::string& init_script_file, const BuiltinFunctionMap& test_function_map,
60 const std::vector<ActionManagerCommand>& commands, ActionManager* action_manager,
61 ServiceList* service_list) {
62 Action::set_function_map(&test_function_map);
63
64 Parser parser;
65 parser.AddSectionParser("service",
66 std::make_unique<ServiceParser>(service_list, nullptr, std::nullopt));
67 parser.AddSectionParser("on", std::make_unique<ActionParser>(action_manager, nullptr));
68 parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
69
70 ASSERT_TRUE(parser.ParseConfig(init_script_file));
71
72 for (const auto& command : commands) {
73 command(*action_manager);
74 }
75
76 while (action_manager->HasMoreCommands()) {
77 action_manager->ExecuteOneCommand();
78 }
79 }
80
TestInitText(const std::string & init_script,const BuiltinFunctionMap & test_function_map,const std::vector<ActionManagerCommand> & commands,ActionManager * action_manager,ServiceList * service_list)81 void TestInitText(const std::string& init_script, const BuiltinFunctionMap& test_function_map,
82 const std::vector<ActionManagerCommand>& commands, ActionManager* action_manager,
83 ServiceList* service_list) {
84 TemporaryFile tf;
85 ASSERT_TRUE(tf.fd != -1);
86 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
87 TestInit(tf.path, test_function_map, commands, action_manager, service_list);
88 }
89
TEST(init,SimpleEventTrigger)90 TEST(init, SimpleEventTrigger) {
91 bool expect_true = false;
92 std::string init_script =
93 R"init(
94 on boot
95 pass_test
96 )init";
97
98 auto do_pass_test = [&expect_true](const BuiltinArguments&) {
99 expect_true = true;
100 return Result<void>{};
101 };
102 BuiltinFunctionMap test_function_map = {
103 {"pass_test", {0, 0, {false, do_pass_test}}},
104 };
105
106 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
107 std::vector<ActionManagerCommand> commands{trigger_boot};
108
109 ActionManager action_manager;
110 ServiceList service_list;
111 TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
112
113 EXPECT_TRUE(expect_true);
114 }
115
TEST(init,WrongEventTrigger)116 TEST(init, WrongEventTrigger) {
117 std::string init_script =
118 R"init(
119 on boot:
120 pass_test
121 )init";
122
123 TemporaryFile tf;
124 ASSERT_TRUE(tf.fd != -1);
125 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
126
127 ActionManager am;
128
129 Parser parser;
130 parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
131
132 ASSERT_TRUE(parser.ParseConfig(tf.path));
133 ASSERT_EQ(1u, parser.parse_error_count());
134 }
135
TEST(init,EventTriggerOrder)136 TEST(init, EventTriggerOrder) {
137 std::string init_script =
138 R"init(
139 on boot
140 execute_first
141
142 on boot && property:ro.hardware=*
143 execute_second
144
145 on boot
146 execute_third
147
148 )init";
149
150 int num_executed = 0;
151 auto do_execute_first = [&num_executed](const BuiltinArguments&) {
152 EXPECT_EQ(0, num_executed++);
153 return Result<void>{};
154 };
155 auto do_execute_second = [&num_executed](const BuiltinArguments&) {
156 EXPECT_EQ(1, num_executed++);
157 return Result<void>{};
158 };
159 auto do_execute_third = [&num_executed](const BuiltinArguments&) {
160 EXPECT_EQ(2, num_executed++);
161 return Result<void>{};
162 };
163
164 BuiltinFunctionMap test_function_map = {
165 {"execute_first", {0, 0, {false, do_execute_first}}},
166 {"execute_second", {0, 0, {false, do_execute_second}}},
167 {"execute_third", {0, 0, {false, do_execute_third}}},
168 };
169
170 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
171 std::vector<ActionManagerCommand> commands{trigger_boot};
172
173 ActionManager action_manager;
174 ServiceList service_list;
175 TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
176 EXPECT_EQ(3, num_executed);
177 }
178
TEST(init,OverrideService)179 TEST(init, OverrideService) {
180 std::string init_script = R"init(
181 service A something
182 class first
183 user nobody
184
185 service A something
186 class second
187 user nobody
188 override
189
190 )init";
191
192 ActionManager action_manager;
193 ServiceList service_list;
194 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
195 ASSERT_EQ(1, std::distance(service_list.begin(), service_list.end()));
196
197 auto service = service_list.begin()->get();
198 ASSERT_NE(nullptr, service);
199 EXPECT_EQ(std::set<std::string>({"second"}), service->classnames());
200 EXPECT_EQ("A", service->name());
201 EXPECT_TRUE(service->is_override());
202 }
203
TEST(init,StartConsole)204 TEST(init, StartConsole) {
205 if (GetProperty("ro.build.type", "") == "user") {
206 GTEST_SKIP() << "Must run on userdebug/eng builds. b/262090304";
207 return;
208 }
209 if (getuid() != 0) {
210 GTEST_SKIP() << "Must be run as root.";
211 return;
212 }
213 std::string init_script = R"init(
214 service console /system/bin/sh
215 class core
216 console null
217 disabled
218 user root
219 group root shell log readproc
220 seclabel u:r:shell:s0
221 setenv HOSTNAME console
222 )init";
223
224 ActionManager action_manager;
225 ServiceList service_list;
226 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
227 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
228
229 auto service = service_list.begin()->get();
230 ASSERT_NE(service, nullptr);
231 ASSERT_RESULT_OK(service->Start());
232 const pid_t pid = service->pid();
233 ASSERT_GT(pid, 0);
234 EXPECT_NE(getsid(pid), 0);
235 service->Stop();
236 }
237
GetSecurityContext()238 static std::string GetSecurityContext() {
239 char* ctx;
240 if (getcon(&ctx) == -1) {
241 ADD_FAILURE() << "Failed to call getcon : " << strerror(errno);
242 }
243 std::string result = std::string(ctx);
244 freecon(ctx);
245 return result;
246 }
247
TestStartApexServices(const std::vector<std::string> & service_names,const std::string & apex_name)248 void TestStartApexServices(const std::vector<std::string>& service_names,
249 const std::string& apex_name) {
250 for (auto const& svc : service_names) {
251 auto service = ServiceList::GetInstance().FindService(svc);
252 ASSERT_NE(nullptr, service);
253 ASSERT_RESULT_OK(service->Start());
254 ASSERT_TRUE(service->IsRunning());
255 LOG(INFO) << "Service " << svc << " is running";
256 if (!apex_name.empty()) {
257 service->set_filename("/apex/" + apex_name + "/init_test.rc");
258 } else {
259 service->set_filename("");
260 }
261 }
262 if (!apex_name.empty()) {
263 auto apex_services = ServiceList::GetInstance().FindServicesByApexName(apex_name);
264 EXPECT_EQ(service_names.size(), apex_services.size());
265 }
266 }
267
TestStopApexServices(const std::vector<std::string> & service_names,bool expect_to_run)268 void TestStopApexServices(const std::vector<std::string>& service_names, bool expect_to_run) {
269 for (auto const& svc : service_names) {
270 auto service = ServiceList::GetInstance().FindService(svc);
271 ASSERT_NE(nullptr, service);
272 EXPECT_EQ(expect_to_run, service->IsRunning());
273 }
274 }
275
TestRemoveApexService(const std::vector<std::string> & service_names,bool exist)276 void TestRemoveApexService(const std::vector<std::string>& service_names, bool exist) {
277 for (auto const& svc : service_names) {
278 auto service = ServiceList::GetInstance().FindService(svc);
279 ASSERT_EQ(exist, service != nullptr);
280 }
281 }
282
InitApexService(const std::string_view & init_template)283 void InitApexService(const std::string_view& init_template) {
284 std::string init_script = StringReplace(init_template, "$selabel",
285 GetSecurityContext(), true);
286
287 TestInitText(init_script, BuiltinFunctionMap(), {}, &ActionManager::GetInstance(),
288 &ServiceList::GetInstance());
289 }
290
CleanupApexServices()291 void CleanupApexServices() {
292 std::vector<std::string> names;
293 for (const auto& s : ServiceList::GetInstance()) {
294 names.push_back(s->name());
295 }
296
297 for (const auto& name : names) {
298 auto s = ServiceList::GetInstance().FindService(name);
299 auto pid = s->pid();
300 ServiceList::GetInstance().RemoveService(*s);
301 if (pid > 0) {
302 kill(pid, SIGTERM);
303 kill(pid, SIGKILL);
304 }
305 }
306
307 ActionManager::GetInstance().RemoveActionIf([&](const std::unique_ptr<Action>& s) -> bool {
308 return true;
309 });
310 }
311
TestApexServicesInit(const std::vector<std::string> & apex_services,const std::vector<std::string> & other_apex_services,const std::vector<std::string> non_apex_services)312 void TestApexServicesInit(const std::vector<std::string>& apex_services,
313 const std::vector<std::string>& other_apex_services,
314 const std::vector<std::string> non_apex_services) {
315 auto num_svc = apex_services.size() + other_apex_services.size() + non_apex_services.size();
316 ASSERT_EQ(num_svc, ServiceList::GetInstance().size());
317
318 TestStartApexServices(apex_services, "com.android.apex.test_service");
319 TestStartApexServices(other_apex_services, "com.android.other_apex.test_service");
320 TestStartApexServices(non_apex_services, /*apex_anme=*/ "");
321
322 StopServicesFromApex("com.android.apex.test_service");
323 TestStopApexServices(apex_services, /*expect_to_run=*/ false);
324 TestStopApexServices(other_apex_services, /*expect_to_run=*/ true);
325 TestStopApexServices(non_apex_services, /*expect_to_run=*/ true);
326
327 RemoveServiceAndActionFromApex("com.android.apex.test_service");
328 ASSERT_EQ(other_apex_services.size() + non_apex_services.size(),
329 ServiceList::GetInstance().size());
330
331 // TODO(b/244232142): Add test to check if actions are removed
332 TestRemoveApexService(apex_services, /*exist*/ false);
333 TestRemoveApexService(other_apex_services, /*exist*/ true);
334 TestRemoveApexService(non_apex_services, /*exist*/ true);
335
336 CleanupApexServices();
337 }
338
TEST(init,StopServiceByApexName)339 TEST(init, StopServiceByApexName) {
340 if (getuid() != 0) {
341 GTEST_SKIP() << "Must be run as root.";
342 return;
343 }
344 std::string_view script_template = R"init(
345 service apex_test_service /system/bin/yes
346 user shell
347 group shell
348 seclabel $selabel
349 )init";
350 InitApexService(script_template);
351 TestApexServicesInit({"apex_test_service"}, {}, {});
352 }
353
TEST(init,StopMultipleServicesByApexName)354 TEST(init, StopMultipleServicesByApexName) {
355 if (getuid() != 0) {
356 GTEST_SKIP() << "Must be run as root.";
357 return;
358 }
359 std::string_view script_template = R"init(
360 service apex_test_service_multiple_a /system/bin/yes
361 user shell
362 group shell
363 seclabel $selabel
364 service apex_test_service_multiple_b /system/bin/id
365 user shell
366 group shell
367 seclabel $selabel
368 )init";
369 InitApexService(script_template);
370 TestApexServicesInit({"apex_test_service_multiple_a",
371 "apex_test_service_multiple_b"}, {}, {});
372 }
373
TEST(init,StopServicesFromMultipleApexes)374 TEST(init, StopServicesFromMultipleApexes) {
375 if (getuid() != 0) {
376 GTEST_SKIP() << "Must be run as root.";
377 return;
378 }
379 std::string_view apex_script_template = R"init(
380 service apex_test_service_multi_apex_a /system/bin/yes
381 user shell
382 group shell
383 seclabel $selabel
384 service apex_test_service_multi_apex_b /system/bin/id
385 user shell
386 group shell
387 seclabel $selabel
388 )init";
389 InitApexService(apex_script_template);
390
391 std::string_view other_apex_script_template = R"init(
392 service apex_test_service_multi_apex_c /system/bin/yes
393 user shell
394 group shell
395 seclabel $selabel
396 )init";
397 InitApexService(other_apex_script_template);
398
399 TestApexServicesInit({"apex_test_service_multi_apex_a",
400 "apex_test_service_multi_apex_b"}, {"apex_test_service_multi_apex_c"}, {});
401 }
402
TEST(init,StopServicesFromApexAndNonApex)403 TEST(init, StopServicesFromApexAndNonApex) {
404 if (getuid() != 0) {
405 GTEST_SKIP() << "Must be run as root.";
406 return;
407 }
408 std::string_view apex_script_template = R"init(
409 service apex_test_service_apex_a /system/bin/yes
410 user shell
411 group shell
412 seclabel $selabel
413 service apex_test_service_apex_b /system/bin/id
414 user shell
415 group shell
416 seclabel $selabel
417 )init";
418 InitApexService(apex_script_template);
419
420 std::string_view non_apex_script_template = R"init(
421 service apex_test_service_non_apex /system/bin/yes
422 user shell
423 group shell
424 seclabel $selabel
425 )init";
426 InitApexService(non_apex_script_template);
427
428 TestApexServicesInit({"apex_test_service_apex_a",
429 "apex_test_service_apex_b"}, {}, {"apex_test_service_non_apex"});
430 }
431
TEST(init,StopServicesFromApexMixed)432 TEST(init, StopServicesFromApexMixed) {
433 if (getuid() != 0) {
434 GTEST_SKIP() << "Must be run as root.";
435 return;
436 }
437 std::string_view script_template = R"init(
438 service apex_test_service_mixed_a /system/bin/yes
439 user shell
440 group shell
441 seclabel $selabel
442 )init";
443 InitApexService(script_template);
444
445 std::string_view other_apex_script_template = R"init(
446 service apex_test_service_mixed_b /system/bin/yes
447 user shell
448 group shell
449 seclabel $selabel
450 )init";
451 InitApexService(other_apex_script_template);
452
453 std::string_view non_apex_script_template = R"init(
454 service apex_test_service_mixed_c /system/bin/yes
455 user shell
456 group shell
457 seclabel $selabel
458 )init";
459 InitApexService(non_apex_script_template);
460
461 TestApexServicesInit({"apex_test_service_mixed_a"},
462 {"apex_test_service_mixed_b"}, {"apex_test_service_mixed_c"});
463 }
464
TEST(init,EventTriggerOrderMultipleFiles)465 TEST(init, EventTriggerOrderMultipleFiles) {
466 // 6 total files, which should have their triggers executed in the following order:
467 // 1: start - original script parsed
468 // 2: first_import - immediately imported by first_script
469 // 3: dir_a - file named 'a.rc' in dir; dir is imported after first_import
470 // 4: a_import - file imported by dir_a
471 // 5: dir_b - file named 'b.rc' in dir
472 // 6: last_import - imported after dir is imported
473
474 TemporaryFile first_import;
475 ASSERT_TRUE(first_import.fd != -1);
476 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", first_import.fd));
477
478 TemporaryFile dir_a_import;
479 ASSERT_TRUE(dir_a_import.fd != -1);
480 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 4", dir_a_import.fd));
481
482 TemporaryFile last_import;
483 ASSERT_TRUE(last_import.fd != -1);
484 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 6", last_import.fd));
485
486 TemporaryDir dir;
487 // clang-format off
488 std::string dir_a_script = "import " + std::string(dir_a_import.path) + "\n"
489 "on boot\n"
490 "execute 3";
491 // clang-format on
492 // WriteFile() ensures the right mode is set
493 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
494
495 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
496
497 // clang-format off
498 std::string start_script = "import " + std::string(first_import.path) + "\n"
499 "import " + std::string(dir.path) + "\n"
500 "import " + std::string(last_import.path) + "\n"
501 "on boot\n"
502 "execute 1";
503 // clang-format on
504 TemporaryFile start;
505 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
506
507 int num_executed = 0;
508 auto execute_command = [&num_executed](const BuiltinArguments& args) {
509 EXPECT_EQ(2U, args.size());
510 EXPECT_EQ(++num_executed, std::stoi(args[1]));
511 return Result<void>{};
512 };
513
514 BuiltinFunctionMap test_function_map = {
515 {"execute", {1, 1, {false, execute_command}}},
516 };
517
518 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
519 std::vector<ActionManagerCommand> commands{trigger_boot};
520
521 ActionManager action_manager;
522 ServiceList service_list;
523 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
524
525 EXPECT_EQ(6, num_executed);
526 }
527
GetTestFunctionMapForLazyLoad(int & num_executed,ActionManager & action_manager)528 BuiltinFunctionMap GetTestFunctionMapForLazyLoad(int& num_executed, ActionManager& action_manager) {
529 auto execute_command = [&num_executed](const BuiltinArguments& args) {
530 EXPECT_EQ(2U, args.size());
531 EXPECT_EQ(++num_executed, std::stoi(args[1]));
532 return Result<void>{};
533 };
534 auto load_command = [&action_manager](const BuiltinArguments& args) -> Result<void> {
535 EXPECT_EQ(2U, args.size());
536 Parser parser;
537 parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, nullptr));
538 if (!parser.ParseConfig(args[1])) {
539 return Error() << "Failed to load";
540 }
541 return Result<void>{};
542 };
543 auto trigger_command = [&action_manager](const BuiltinArguments& args) {
544 EXPECT_EQ(2U, args.size());
545 LOG(INFO) << "Queue event trigger: " << args[1];
546 action_manager.QueueEventTrigger(args[1]);
547 return Result<void>{};
548 };
549 BuiltinFunctionMap test_function_map = {
550 {"execute", {1, 1, {false, execute_command}}},
551 {"load", {1, 1, {false, load_command}}},
552 {"trigger", {1, 1, {false, trigger_command}}},
553 };
554 return test_function_map;
555 }
556
TEST(init,LazilyLoadedActionsCantBeTriggeredByTheSameTrigger)557 TEST(init, LazilyLoadedActionsCantBeTriggeredByTheSameTrigger) {
558 // "start" script loads "lazy" script. Even though "lazy" scripts
559 // defines "on boot" action, it's not executed by the current "boot"
560 // event because it's already processed.
561 TemporaryFile lazy;
562 ASSERT_TRUE(lazy.fd != -1);
563 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", lazy.fd));
564
565 TemporaryFile start;
566 // clang-format off
567 std::string start_script = "on boot\n"
568 "load " + std::string(lazy.path) + "\n"
569 "execute 1";
570 // clang-format on
571 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
572
573 int num_executed = 0;
574 ActionManager action_manager;
575 ServiceList service_list;
576 BuiltinFunctionMap test_function_map =
577 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
578
579 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
580 std::vector<ActionManagerCommand> commands{trigger_boot};
581 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
582
583 EXPECT_EQ(1, num_executed);
584 }
585
TEST(init,LazilyLoadedActionsCanBeTriggeredByTheNextTrigger)586 TEST(init, LazilyLoadedActionsCanBeTriggeredByTheNextTrigger) {
587 // "start" script loads "lazy" script and then triggers "next" event
588 // which executes "on next" action loaded by the previous command.
589 TemporaryFile lazy;
590 ASSERT_TRUE(lazy.fd != -1);
591 ASSERT_TRUE(android::base::WriteStringToFd("on next\nexecute 2", lazy.fd));
592
593 TemporaryFile start;
594 // clang-format off
595 std::string start_script = "on boot\n"
596 "load " + std::string(lazy.path) + "\n"
597 "execute 1\n"
598 "trigger next";
599 // clang-format on
600 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
601
602 int num_executed = 0;
603 ActionManager action_manager;
604 ServiceList service_list;
605 BuiltinFunctionMap test_function_map =
606 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
607
608 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
609 std::vector<ActionManagerCommand> commands{trigger_boot};
610 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
611
612 EXPECT_EQ(2, num_executed);
613 }
614
TEST(init,RejectsNoUserStartingInV)615 TEST(init, RejectsNoUserStartingInV) {
616 std::string init_script =
617 R"init(
618 service A something
619 class first
620 )init";
621
622 TemporaryFile tf;
623 ASSERT_TRUE(tf.fd != -1);
624 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
625
626 ServiceList service_list;
627 Parser parser;
628 parser.AddSectionParser("service",
629 std::make_unique<ServiceParser>(&service_list, nullptr, std::nullopt));
630
631 ASSERT_TRUE(parser.ParseConfig(tf.path));
632
633 if (GetIntProperty("ro.vendor.api_level", 0) > 202404) {
634 ASSERT_EQ(1u, parser.parse_error_count());
635 } else {
636 ASSERT_EQ(0u, parser.parse_error_count());
637 }
638 }
639
TEST(init,RejectsCriticalAndOneshotService)640 TEST(init, RejectsCriticalAndOneshotService) {
641 if (GetIntProperty("ro.product.first_api_level", 10000) < 30) {
642 GTEST_SKIP() << "Test only valid for devices launching with R or later";
643 }
644
645 std::string init_script =
646 R"init(
647 service A something
648 class first
649 user root
650 critical
651 oneshot
652 )init";
653
654 TemporaryFile tf;
655 ASSERT_TRUE(tf.fd != -1);
656 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
657
658 ServiceList service_list;
659 Parser parser;
660 parser.AddSectionParser("service",
661 std::make_unique<ServiceParser>(&service_list, nullptr, std::nullopt));
662
663 ASSERT_TRUE(parser.ParseConfig(tf.path));
664 ASSERT_EQ(1u, parser.parse_error_count());
665 }
666
TEST(init,MemLockLimit)667 TEST(init, MemLockLimit) {
668 // Test is enforced only for U+ devices
669 if (android::base::GetIntProperty("ro.vendor.api_level", 0) < __ANDROID_API_U__) {
670 GTEST_SKIP();
671 }
672
673 // Verify we are running memlock at, or under, 64KB
674 const unsigned long max_limit = 65536;
675 struct rlimit curr_limit;
676 ASSERT_EQ(getrlimit(RLIMIT_MEMLOCK, &curr_limit), 0);
677 ASSERT_LE(curr_limit.rlim_cur, max_limit);
678 ASSERT_LE(curr_limit.rlim_max, max_limit);
679 }
680
CloseAllFds()681 void CloseAllFds() {
682 DIR* dir;
683 struct dirent* ent;
684 int fd;
685
686 if ((dir = opendir("/proc/self/fd"))) {
687 while ((ent = readdir(dir))) {
688 if (sscanf(ent->d_name, "%d", &fd) == 1) {
689 close(fd);
690 }
691 }
692 closedir(dir);
693 }
694 }
695
ForkExecvpAsync(const char * argv[])696 pid_t ForkExecvpAsync(const char* argv[]) {
697 pid_t pid = fork();
698 if (pid == 0) {
699 // Child process.
700 CloseAllFds();
701
702 execvp(argv[0], const_cast<char**>(argv));
703 PLOG(ERROR) << "exec in ForkExecvpAsync init test";
704 _exit(EXIT_FAILURE);
705 }
706 // Parent process.
707 if (pid == -1) {
708 PLOG(ERROR) << "fork in ForkExecvpAsync init test";
709 return -1;
710 }
711 return pid;
712 }
713
TracerPid(pid_t pid)714 pid_t TracerPid(pid_t pid) {
715 static constexpr std::string_view prefix{"TracerPid:"};
716 std::ifstream is(StringPrintf("/proc/%d/status", pid));
717 std::string line;
718 while (std::getline(is, line)) {
719 if (line.find(prefix) == 0) {
720 return atoi(line.substr(prefix.length()).c_str());
721 }
722 }
723 return -1;
724 }
725
TEST(init,GentleKill)726 TEST(init, GentleKill) {
727 if (getuid() != 0) {
728 GTEST_SKIP() << "Must be run as root.";
729 return;
730 }
731 std::string init_script = R"init(
732 service test_gentle_kill /system/bin/sleep 1000
733 disabled
734 oneshot
735 gentle_kill
736 user root
737 group root
738 seclabel u:r:toolbox:s0
739 )init";
740
741 ActionManager action_manager;
742 ServiceList service_list;
743 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
744 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
745
746 auto service = service_list.begin()->get();
747 ASSERT_NE(service, nullptr);
748 ASSERT_RESULT_OK(service->Start());
749 const pid_t pid = service->pid();
750 ASSERT_GT(pid, 0);
751 EXPECT_NE(getsid(pid), 0);
752
753 TemporaryFile logfile;
754 logfile.DoNotRemove();
755 ASSERT_TRUE(logfile.fd != -1);
756
757 std::string pid_str = std::to_string(pid);
758 const char* argv[] = {"/system/bin/strace", "-o", logfile.path, "-e", "signal", "-p",
759 pid_str.c_str(), nullptr};
760 pid_t strace_pid = ForkExecvpAsync(argv);
761
762 // Give strace the chance to connect
763 while (TracerPid(pid) == 0) {
764 std::this_thread::sleep_for(10ms);
765 }
766 service->Stop();
767
768 int status;
769 waitpid(strace_pid, &status, 0);
770
771 std::string logs;
772 android::base::ReadFdToString(logfile.fd, &logs);
773 ASSERT_NE(logs.find("killed by SIGTERM"), std::string::npos);
774 }
775
776 class TestCaseLogger : public ::testing::EmptyTestEventListener {
OnTestStart(const::testing::TestInfo & test_info)777 void OnTestStart(const ::testing::TestInfo& test_info) override {
778 #ifdef __ANDROID__
779 LOG(INFO) << "===== " << test_info.test_suite_name() << "::" << test_info.name() << " ("
780 << test_info.file() << ":" << test_info.line() << ")";
781 #else
782 UNUSED(test_info);
783 #endif
784 }
785 };
786
787 } // namespace init
788 } // namespace android
789
790 int SubcontextTestChildMain(int, char**);
791 int FirmwareTestChildMain(int, char**);
792
main(int argc,char ** argv)793 int main(int argc, char** argv) {
794 if (argc > 1 && !strcmp(argv[1], "subcontext")) {
795 return SubcontextTestChildMain(argc, argv);
796 }
797
798 if (argc > 1 && !strcmp(argv[1], "firmware")) {
799 return FirmwareTestChildMain(argc, argv);
800 }
801
802 testing::InitGoogleTest(&argc, argv);
803 testing::UnitTest::GetInstance()->listeners().Append(new android::init::TestCaseLogger());
804 return RUN_ALL_TESTS();
805 }
806