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