xref: /aosp_15_r20/system/core/init/init_test.cpp (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 #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", std::make_unique<ServiceParser>(service_list, nullptr));
66     parser.AddSectionParser("on", std::make_unique<ActionParser>(action_manager, nullptr));
67     parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
68 
69     ASSERT_TRUE(parser.ParseConfig(init_script_file));
70 
71     for (const auto& command : commands) {
72         command(*action_manager);
73     }
74 
75     while (action_manager->HasMoreCommands()) {
76         action_manager->ExecuteOneCommand();
77     }
78 }
79 
TestInitText(const std::string & init_script,const BuiltinFunctionMap & test_function_map,const std::vector<ActionManagerCommand> & commands,ActionManager * action_manager,ServiceList * service_list)80 void TestInitText(const std::string& init_script, const BuiltinFunctionMap& test_function_map,
81                   const std::vector<ActionManagerCommand>& commands, ActionManager* action_manager,
82                   ServiceList* service_list) {
83     TemporaryFile tf;
84     ASSERT_TRUE(tf.fd != -1);
85     ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
86     TestInit(tf.path, test_function_map, commands, action_manager, service_list);
87 }
88 
TEST(init,SimpleEventTrigger)89 TEST(init, SimpleEventTrigger) {
90     bool expect_true = false;
91     std::string init_script =
92         R"init(
93 on boot
94 pass_test
95 )init";
96 
97     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     };
104 
105     ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
106     std::vector<ActionManagerCommand> commands{trigger_boot};
107 
108     ActionManager action_manager;
109     ServiceList service_list;
110     TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
111 
112     EXPECT_TRUE(expect_true);
113 }
114 
TEST(init,WrongEventTrigger)115 TEST(init, WrongEventTrigger) {
116     std::string init_script =
117             R"init(
118 on boot:
119 pass_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 
TEST(init,EventTriggerOrder)135 TEST(init, EventTriggerOrder) {
136     std::string init_script =
137         R"init(
138 on boot
139 execute_first
140 
141 on boot && property:ro.hardware=*
142 execute_second
143 
144 on boot
145 execute_third
146 
147 )init";
148 
149     int num_executed = 0;
150     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     };
168 
169     ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
170     std::vector<ActionManagerCommand> commands{trigger_boot};
171 
172     ActionManager action_manager;
173     ServiceList service_list;
174     TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
175     EXPECT_EQ(3, num_executed);
176 }
177 
TEST(init,OverrideService)178 TEST(init, OverrideService) {
179     std::string init_script = R"init(
180 service A something
181     class first
182     user nobody
183 
184 service A something
185     class second
186     user nobody
187     override
188 
189 )init";
190 
191     ActionManager action_manager;
192     ServiceList service_list;
193     TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
194     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());
201 }
202 
TEST(init,StartConsole)203 TEST(init, StartConsole) {
204     if (GetProperty("ro.build.type", "") == "user") {
205         GTEST_SKIP() << "Must run on userdebug/eng builds. b/262090304";
206         return;
207     }
208     if (getuid() != 0) {
209         GTEST_SKIP() << "Must be run as root.";
210         return;
211     }
212     std::string init_script = R"init(
213 service console /system/bin/sh
214     class core
215     console null
216     disabled
217     user root
218     group root shell log readproc
219     seclabel u:r:shell:s0
220     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);
233     EXPECT_NE(getsid(pid), 0);
234     service->Stop();
235 }
236 
GetSecurityContext()237 static 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 
TestStartApexServices(const std::vector<std::string> & service_names,const std::string & apex_name)247 void 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 
TestStopApexServices(const std::vector<std::string> & service_names,bool expect_to_run)267 void 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     }
273 }
274 
TestRemoveApexService(const std::vector<std::string> & service_names,bool exist)275 void 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     }
280 }
281 
InitApexService(const std::string_view & init_template)282 void InitApexService(const std::string_view& init_template) {
283     std::string init_script = StringReplace(init_template, "$selabel",
284                                     GetSecurityContext(), true);
285 
286     TestInitText(init_script, BuiltinFunctionMap(), {}, &ActionManager::GetInstance(),
287             &ServiceList::GetInstance());
288 }
289 
CleanupApexServices()290 void 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 
TestApexServicesInit(const std::vector<std::string> & apex_services,const std::vector<std::string> & other_apex_services,const std::vector<std::string> non_apex_services)311 void 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();
315     ASSERT_EQ(num_svc, ServiceList::GetInstance().size());
316 
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 
326     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 
335     CleanupApexServices();
336 }
337 
TEST(init,StopServiceByApexName)338 TEST(init, StopServiceByApexName) {
339     if (getuid() != 0) {
340         GTEST_SKIP() << "Must be run as root.";
341         return;
342     }
343     std::string_view script_template = R"init(
344 service 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 
TEST(init,StopMultipleServicesByApexName)353 TEST(init, StopMultipleServicesByApexName) {
354     if (getuid() != 0) {
355         GTEST_SKIP() << "Must be run as root.";
356         return;
357     }
358     std::string_view script_template = R"init(
359 service apex_test_service_multiple_a /system/bin/yes
360     user shell
361     group shell
362     seclabel $selabel
363 service 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 
TEST(init,StopServicesFromMultipleApexes)373 TEST(init, StopServicesFromMultipleApexes) {
374     if (getuid() != 0) {
375         GTEST_SKIP() << "Must be run as root.";
376         return;
377     }
378     std::string_view apex_script_template = R"init(
379 service apex_test_service_multi_apex_a /system/bin/yes
380     user shell
381     group shell
382     seclabel $selabel
383 service 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(
391 service 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 
TEST(init,StopServicesFromApexAndNonApex)402 TEST(init, StopServicesFromApexAndNonApex) {
403     if (getuid() != 0) {
404         GTEST_SKIP() << "Must be run as root.";
405         return;
406     }
407     std::string_view apex_script_template = R"init(
408 service apex_test_service_apex_a /system/bin/yes
409     user shell
410     group shell
411     seclabel $selabel
412 service 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(
420 service 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 
TEST(init,StopServicesFromApexMixed)431 TEST(init, StopServicesFromApexMixed) {
432     if (getuid() != 0) {
433         GTEST_SKIP() << "Must be run as root.";
434         return;
435     }
436     std::string_view script_template = R"init(
437 service 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(
445 service 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(
453 service 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 
TEST(init,EventTriggerOrderMultipleFiles)464 TEST(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
491     // WriteFile() ensures the right mode is set
492     ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
493 
494     ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
495 
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;
507     auto execute_command = [&num_executed](const BuiltinArguments& args) {
508         EXPECT_EQ(2U, args.size());
509         EXPECT_EQ(++num_executed, std::stoi(args[1]));
510         return Result<void>{};
511     };
512 
513     BuiltinFunctionMap test_function_map = {
514             {"execute", {1, 1, {false, execute_command}}},
515     };
516 
517     ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
518     std::vector<ActionManagerCommand> commands{trigger_boot};
519 
520     ActionManager action_manager;
521     ServiceList service_list;
522     TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
523 
524     EXPECT_EQ(6, num_executed);
525 }
526 
GetTestFunctionMapForLazyLoad(int & num_executed,ActionManager & action_manager)527 BuiltinFunctionMap 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 
TEST(init,LazilyLoadedActionsCantBeTriggeredByTheSameTrigger)556 TEST(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 
TEST(init,LazilyLoadedActionsCanBeTriggeredByTheNextTrigger)585 TEST(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 
TEST(init,RejectsNoUserStartingInV)614 TEST(init, RejectsNoUserStartingInV) {
615     std::string init_script =
616             R"init(
617 service 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;
627     parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, nullptr));
628 
629     ASSERT_TRUE(parser.ParseConfig(tf.path));
630 
631     if (GetIntProperty("ro.vendor.api_level", 0) > 202404) {
632         ASSERT_EQ(1u, parser.parse_error_count());
633     } else {
634         ASSERT_EQ(0u, parser.parse_error_count());
635     }
636 }
637 
TEST(init,RejectsCriticalAndOneshotService)638 TEST(init, RejectsCriticalAndOneshotService) {
639     if (GetIntProperty("ro.product.first_api_level", 10000) < 30) {
640         GTEST_SKIP() << "Test only valid for devices launching with R or later";
641     }
642 
643     std::string init_script =
644             R"init(
645 service A something
646   class first
647   user root
648   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;
658     parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, nullptr));
659 
660     ASSERT_TRUE(parser.ParseConfig(tf.path));
661     ASSERT_EQ(1u, parser.parse_error_count());
662 }
663 
TEST(init,MemLockLimit)664 TEST(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 
CloseAllFds()678 void 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 
ForkExecvpAsync(const char * argv[])693 pid_t ForkExecvpAsync(const char* argv[]) {
694     pid_t pid = fork();
695     if (pid == 0) {
696         // Child process.
697         CloseAllFds();
698 
699         execvp(argv[0], const_cast<char**>(argv));
700         PLOG(ERROR) << "exec in ForkExecvpAsync init test";
701         _exit(EXIT_FAILURE);
702     }
703     // Parent process.
704     if (pid == -1) {
705         PLOG(ERROR) << "fork in ForkExecvpAsync init test";
706         return -1;
707     }
708     return pid;
709 }
710 
TracerPid(pid_t pid)711 pid_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 
TEST(init,GentleKill)723 TEST(init, GentleKill) {
724     if (getuid() != 0) {
725         GTEST_SKIP() << "Must be run as root.";
726         return;
727     }
728     std::string init_script = R"init(
729 service 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 
754     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);
758 
759     // Give strace the chance to connect
760     while (TracerPid(pid) == 0) {
761         std::this_thread::sleep_for(10ms);
762     }
763     service->Stop();
764 
765     int status;
766     waitpid(strace_pid, &status, 0);
767 
768     std::string logs;
769     android::base::ReadFdToString(logfile.fd, &logs);
770     ASSERT_NE(logs.find("killed by SIGTERM"), std::string::npos);
771 }
772 
773 class TestCaseLogger : public ::testing::EmptyTestEventListener {
OnTestStart(const::testing::TestInfo & test_info)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 
784 }  // namespace init
785 }  // namespace android
786 
787 int SubcontextTestChildMain(int, char**);
788 int FirmwareTestChildMain(int, char**);
789 
main(int argc,char ** argv)790 int 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);
800     testing::UnitTest::GetInstance()->listeners().Append(new android::init::TestCaseLogger());
801     return RUN_ALL_TESTS();
802 }
803