blob: 4a7bac2ca945899e4acd9e18006928a7c65aa8fe [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;
Daniel Norman3df8dc52019-06-27 12:18:08 -070065 parser.AddSectionParser("service",
66 std::make_unique<ServiceParser>(service_list, nullptr, std::nullopt));
Jooyung Hanbadb7de2022-05-10 03:16:51 +090067 parser.AddSectionParser("on", std::make_unique<ActionParser>(action_manager, nullptr));
Tom Cherryad54d092017-04-19 16:18:50 -070068 parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
69
70 ASSERT_TRUE(parser.ParseConfig(init_script_file));
71
72 for (const auto& command : commands) {
Jooyung Hanbadb7de2022-05-10 03:16:51 +090073 command(*action_manager);
Tom Cherryad54d092017-04-19 16:18:50 -070074 }
75
Jooyung Hanbadb7de2022-05-10 03:16:51 +090076 while (action_manager->HasMoreCommands()) {
77 action_manager->ExecuteOneCommand();
Tom Cherryad54d092017-04-19 16:18:50 -070078 }
79}
80
Tom Cherryd52a5b32019-07-22 16:05:36 -070081void TestInitText(const std::string& init_script, const BuiltinFunctionMap& test_function_map,
Jooyung Hanbadb7de2022-05-10 03:16:51 +090082 const std::vector<ActionManagerCommand>& commands, ActionManager* action_manager,
83 ServiceList* service_list) {
Tom Cherryad54d092017-04-19 16:18:50 -070084 TemporaryFile tf;
85 ASSERT_TRUE(tf.fd != -1);
86 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
Jooyung Hanbadb7de2022-05-10 03:16:51 +090087 TestInit(tf.path, test_function_map, commands, action_manager, service_list);
Tom Cherryad54d092017-04-19 16:18:50 -070088}
89
90TEST(init, SimpleEventTrigger) {
91 bool expect_true = false;
92 std::string init_script =
93 R"init(
94on boot
95pass_test
96)init";
97
Tom Cherryd52a5b32019-07-22 16:05:36 -070098 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 };
Tom Cherryad54d092017-04-19 16:18:50 -0700105
106 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
107 std::vector<ActionManagerCommand> commands{trigger_boot};
108
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900109 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800110 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900111 TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
Tom Cherryad54d092017-04-19 16:18:50 -0700112
113 EXPECT_TRUE(expect_true);
114}
115
Nikita Ioffeaaab5962019-10-10 20:42:37 +0100116TEST(init, WrongEventTrigger) {
117 std::string init_script =
118 R"init(
119on boot:
120pass_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
Tom Cherryad54d092017-04-19 16:18:50 -0700136TEST(init, EventTriggerOrder) {
137 std::string init_script =
138 R"init(
139on boot
140execute_first
141
142on boot && property:ro.hardware=*
143execute_second
144
145on boot
146execute_third
147
148)init";
149
150 int num_executed = 0;
Tom Cherryd52a5b32019-07-22 16:05:36 -0700151 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 };
Tom Cherryad54d092017-04-19 16:18:50 -0700169
170 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
171 std::vector<ActionManagerCommand> commands{trigger_boot};
172
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900173 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800174 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900175 TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
Florian Mayer6268f6a2022-05-11 01:02:01 +0000176 EXPECT_EQ(3, num_executed);
Steven Moreland6f5333a2017-11-13 15:31:54 -0800177}
178
179TEST(init, OverrideService) {
180 std::string init_script = R"init(
181service A something
182 class first
183
184service A something
185 class second
186 override
187
188)init";
189
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900190 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800191 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900192 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
Steven Moreland6f5333a2017-11-13 15:31:54 -0800193 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());
Tom Cherryad54d092017-04-19 16:18:50 -0700200}
201
Bart Van Assche5d188912022-11-14 09:30:51 -0800202TEST(init, StartConsole) {
Jiyong Park5b7a51a2022-12-20 09:18:49 +0900203 if (GetProperty("ro.build.type", "") == "user") {
204 GTEST_SKIP() << "Must run on userdebug/eng builds. b/262090304";
205 return;
206 }
Bart Van Assche5d188912022-11-14 09:30:51 -0800207 std::string init_script = R"init(
208service console /system/bin/sh
209 class core
Jiyong Parkae412802022-12-15 16:29:01 +0900210 console null
Bart Van Assche5d188912022-11-14 09:30:51 -0800211 disabled
212 user root
213 group root shell log readproc
Bart Van Assche3b21d952022-11-22 16:53:05 -0800214 seclabel u:r:shell:s0
Bart Van Assche5d188912022-11-14 09:30:51 -0800215 setenv HOSTNAME console
216)init";
217
218 ActionManager action_manager;
219 ServiceList service_list;
220 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
221 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
222
223 auto service = service_list.begin()->get();
224 ASSERT_NE(service, nullptr);
225 ASSERT_RESULT_OK(service->Start());
226 const pid_t pid = service->pid();
227 ASSERT_GT(pid, 0);
Bart Van Assche3b21d952022-11-22 16:53:05 -0800228 EXPECT_NE(getsid(pid), 0);
Bart Van Assche5d188912022-11-14 09:30:51 -0800229 service->Stop();
230}
231
Deyao Ren07595e12022-07-15 22:02:14 +0000232static std::string GetSecurityContext() {
233 char* ctx;
234 if (getcon(&ctx) == -1) {
235 ADD_FAILURE() << "Failed to call getcon : " << strerror(errno);
236 }
237 std::string result = std::string(ctx);
238 freecon(ctx);
239 return result;
240}
241
242void TestStartApexServices(const std::vector<std::string>& service_names,
243 const std::string& apex_name) {
244 for (auto const& svc : service_names) {
245 auto service = ServiceList::GetInstance().FindService(svc);
246 ASSERT_NE(nullptr, service);
247 ASSERT_RESULT_OK(service->Start());
248 ASSERT_TRUE(service->IsRunning());
249 LOG(INFO) << "Service " << svc << " is running";
250 if (!apex_name.empty()) {
251 service->set_filename("/apex/" + apex_name + "/init_test.rc");
252 } else {
253 service->set_filename("");
254 }
255 }
256 if (!apex_name.empty()) {
257 auto apex_services = ServiceList::GetInstance().FindServicesByApexName(apex_name);
258 EXPECT_EQ(service_names.size(), apex_services.size());
259 }
260}
261
262void TestStopApexServices(const std::vector<std::string>& service_names, bool expect_to_run) {
263 for (auto const& svc : service_names) {
264 auto service = ServiceList::GetInstance().FindService(svc);
265 ASSERT_NE(nullptr, service);
266 EXPECT_EQ(expect_to_run, service->IsRunning());
267 }
Deyao Ren238e9092022-07-21 23:05:13 +0000268}
269
270void TestRemoveApexService(const std::vector<std::string>& service_names, bool exist) {
271 for (auto const& svc : service_names) {
272 auto service = ServiceList::GetInstance().FindService(svc);
273 ASSERT_EQ(exist, service != nullptr);
274 }
Deyao Ren07595e12022-07-15 22:02:14 +0000275}
276
277void InitApexService(const std::string_view& init_template) {
278 std::string init_script = StringReplace(init_template, "$selabel",
279 GetSecurityContext(), true);
280
Deyao Ren238e9092022-07-21 23:05:13 +0000281 TestInitText(init_script, BuiltinFunctionMap(), {}, &ActionManager::GetInstance(),
Deyao Ren07595e12022-07-15 22:02:14 +0000282 &ServiceList::GetInstance());
283}
284
deyaoren@google.com909bc472022-09-07 22:25:44 +0000285void CleanupApexServices() {
286 std::vector<std::string> names;
287 for (const auto& s : ServiceList::GetInstance()) {
288 names.push_back(s->name());
289 }
290
291 for (const auto& name : names) {
292 auto s = ServiceList::GetInstance().FindService(name);
293 auto pid = s->pid();
294 ServiceList::GetInstance().RemoveService(*s);
295 if (pid > 0) {
296 kill(pid, SIGTERM);
297 kill(pid, SIGKILL);
298 }
299 }
300
301 ActionManager::GetInstance().RemoveActionIf([&](const std::unique_ptr<Action>& s) -> bool {
302 return true;
303 });
304}
305
Deyao Ren07595e12022-07-15 22:02:14 +0000306void TestApexServicesInit(const std::vector<std::string>& apex_services,
307 const std::vector<std::string>& other_apex_services,
308 const std::vector<std::string> non_apex_services) {
309 auto num_svc = apex_services.size() + other_apex_services.size() + non_apex_services.size();
Deyao Ren238e9092022-07-21 23:05:13 +0000310 ASSERT_EQ(num_svc, ServiceList::GetInstance().size());
Deyao Ren07595e12022-07-15 22:02:14 +0000311
312 TestStartApexServices(apex_services, "com.android.apex.test_service");
313 TestStartApexServices(other_apex_services, "com.android.other_apex.test_service");
314 TestStartApexServices(non_apex_services, /*apex_anme=*/ "");
315
316 StopServicesFromApex("com.android.apex.test_service");
317 TestStopApexServices(apex_services, /*expect_to_run=*/ false);
318 TestStopApexServices(other_apex_services, /*expect_to_run=*/ true);
319 TestStopApexServices(non_apex_services, /*expect_to_run=*/ true);
320
Deyao Ren238e9092022-07-21 23:05:13 +0000321 RemoveServiceAndActionFromApex("com.android.apex.test_service");
322 ASSERT_EQ(other_apex_services.size() + non_apex_services.size(),
323 ServiceList::GetInstance().size());
324
325 // TODO(b/244232142): Add test to check if actions are removed
326 TestRemoveApexService(apex_services, /*exist*/ false);
327 TestRemoveApexService(other_apex_services, /*exist*/ true);
328 TestRemoveApexService(non_apex_services, /*exist*/ true);
329
deyaoren@google.com909bc472022-09-07 22:25:44 +0000330 CleanupApexServices();
Deyao Ren07595e12022-07-15 22:02:14 +0000331}
332
333TEST(init, StopServiceByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900334 if (getuid() != 0) {
335 GTEST_SKIP() << "Must be run as root.";
336 return;
337 }
Deyao Ren07595e12022-07-15 22:02:14 +0000338 std::string_view script_template = R"init(
339service apex_test_service /system/bin/yes
340 user shell
341 group shell
342 seclabel $selabel
343)init";
344 InitApexService(script_template);
345 TestApexServicesInit({"apex_test_service"}, {}, {});
346}
347
348TEST(init, StopMultipleServicesByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900349 if (getuid() != 0) {
350 GTEST_SKIP() << "Must be run as root.";
351 return;
352 }
Deyao Ren07595e12022-07-15 22:02:14 +0000353 std::string_view script_template = R"init(
354service apex_test_service_multiple_a /system/bin/yes
355 user shell
356 group shell
357 seclabel $selabel
358service apex_test_service_multiple_b /system/bin/id
359 user shell
360 group shell
361 seclabel $selabel
362)init";
363 InitApexService(script_template);
364 TestApexServicesInit({"apex_test_service_multiple_a",
365 "apex_test_service_multiple_b"}, {}, {});
366}
367
368TEST(init, StopServicesFromMultipleApexes) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900369 if (getuid() != 0) {
370 GTEST_SKIP() << "Must be run as root.";
371 return;
372 }
Deyao Ren07595e12022-07-15 22:02:14 +0000373 std::string_view apex_script_template = R"init(
374service apex_test_service_multi_apex_a /system/bin/yes
375 user shell
376 group shell
377 seclabel $selabel
378service apex_test_service_multi_apex_b /system/bin/id
379 user shell
380 group shell
381 seclabel $selabel
382)init";
383 InitApexService(apex_script_template);
384
385 std::string_view other_apex_script_template = R"init(
386service apex_test_service_multi_apex_c /system/bin/yes
387 user shell
388 group shell
389 seclabel $selabel
390)init";
391 InitApexService(other_apex_script_template);
392
393 TestApexServicesInit({"apex_test_service_multi_apex_a",
394 "apex_test_service_multi_apex_b"}, {"apex_test_service_multi_apex_c"}, {});
395}
396
397TEST(init, StopServicesFromApexAndNonApex) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900398 if (getuid() != 0) {
399 GTEST_SKIP() << "Must be run as root.";
400 return;
401 }
Deyao Ren07595e12022-07-15 22:02:14 +0000402 std::string_view apex_script_template = R"init(
403service apex_test_service_apex_a /system/bin/yes
404 user shell
405 group shell
406 seclabel $selabel
407service apex_test_service_apex_b /system/bin/id
408 user shell
409 group shell
410 seclabel $selabel
411)init";
412 InitApexService(apex_script_template);
413
414 std::string_view non_apex_script_template = R"init(
415service apex_test_service_non_apex /system/bin/yes
416 user shell
417 group shell
418 seclabel $selabel
419)init";
420 InitApexService(non_apex_script_template);
421
422 TestApexServicesInit({"apex_test_service_apex_a",
423 "apex_test_service_apex_b"}, {}, {"apex_test_service_non_apex"});
424}
425
426TEST(init, StopServicesFromApexMixed) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900427 if (getuid() != 0) {
428 GTEST_SKIP() << "Must be run as root.";
429 return;
430 }
Deyao Ren07595e12022-07-15 22:02:14 +0000431 std::string_view script_template = R"init(
432service apex_test_service_mixed_a /system/bin/yes
433 user shell
434 group shell
435 seclabel $selabel
436)init";
437 InitApexService(script_template);
438
439 std::string_view other_apex_script_template = R"init(
440service apex_test_service_mixed_b /system/bin/yes
441 user shell
442 group shell
443 seclabel $selabel
444)init";
445 InitApexService(other_apex_script_template);
446
447 std::string_view non_apex_script_template = R"init(
448service apex_test_service_mixed_c /system/bin/yes
449 user shell
450 group shell
451 seclabel $selabel
452)init";
453 InitApexService(non_apex_script_template);
454
455 TestApexServicesInit({"apex_test_service_mixed_a"},
456 {"apex_test_service_mixed_b"}, {"apex_test_service_mixed_c"});
457}
458
Tom Cherryad54d092017-04-19 16:18:50 -0700459TEST(init, EventTriggerOrderMultipleFiles) {
460 // 6 total files, which should have their triggers executed in the following order:
461 // 1: start - original script parsed
462 // 2: first_import - immediately imported by first_script
463 // 3: dir_a - file named 'a.rc' in dir; dir is imported after first_import
464 // 4: a_import - file imported by dir_a
465 // 5: dir_b - file named 'b.rc' in dir
466 // 6: last_import - imported after dir is imported
467
468 TemporaryFile first_import;
469 ASSERT_TRUE(first_import.fd != -1);
470 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", first_import.fd));
471
472 TemporaryFile dir_a_import;
473 ASSERT_TRUE(dir_a_import.fd != -1);
474 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 4", dir_a_import.fd));
475
476 TemporaryFile last_import;
477 ASSERT_TRUE(last_import.fd != -1);
478 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 6", last_import.fd));
479
480 TemporaryDir dir;
481 // clang-format off
482 std::string dir_a_script = "import " + std::string(dir_a_import.path) + "\n"
483 "on boot\n"
484 "execute 3";
485 // clang-format on
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700486 // WriteFile() ensures the right mode is set
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900487 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
Tom Cherryad54d092017-04-19 16:18:50 -0700488
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900489 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
Tom Cherryad54d092017-04-19 16:18:50 -0700490
491 // clang-format off
492 std::string start_script = "import " + std::string(first_import.path) + "\n"
493 "import " + std::string(dir.path) + "\n"
494 "import " + std::string(last_import.path) + "\n"
495 "on boot\n"
496 "execute 1";
497 // clang-format on
498 TemporaryFile start;
499 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
500
501 int num_executed = 0;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700502 auto execute_command = [&num_executed](const BuiltinArguments& args) {
Tom Cherryad54d092017-04-19 16:18:50 -0700503 EXPECT_EQ(2U, args.size());
504 EXPECT_EQ(++num_executed, std::stoi(args[1]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700505 return Result<void>{};
Tom Cherryad54d092017-04-19 16:18:50 -0700506 };
507
Tom Cherryd52a5b32019-07-22 16:05:36 -0700508 BuiltinFunctionMap test_function_map = {
509 {"execute", {1, 1, {false, execute_command}}},
510 };
Tom Cherryad54d092017-04-19 16:18:50 -0700511
512 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
513 std::vector<ActionManagerCommand> commands{trigger_boot};
514
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900515 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800516 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900517 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
Tom Cherryad54d092017-04-19 16:18:50 -0700518
519 EXPECT_EQ(6, num_executed);
520}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700521
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900522BuiltinFunctionMap GetTestFunctionMapForLazyLoad(int& num_executed, ActionManager& action_manager) {
523 auto execute_command = [&num_executed](const BuiltinArguments& args) {
524 EXPECT_EQ(2U, args.size());
525 EXPECT_EQ(++num_executed, std::stoi(args[1]));
526 return Result<void>{};
527 };
528 auto load_command = [&action_manager](const BuiltinArguments& args) -> Result<void> {
529 EXPECT_EQ(2U, args.size());
530 Parser parser;
531 parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, nullptr));
532 if (!parser.ParseConfig(args[1])) {
533 return Error() << "Failed to load";
534 }
535 return Result<void>{};
536 };
537 auto trigger_command = [&action_manager](const BuiltinArguments& args) {
538 EXPECT_EQ(2U, args.size());
539 LOG(INFO) << "Queue event trigger: " << args[1];
540 action_manager.QueueEventTrigger(args[1]);
541 return Result<void>{};
542 };
543 BuiltinFunctionMap test_function_map = {
544 {"execute", {1, 1, {false, execute_command}}},
545 {"load", {1, 1, {false, load_command}}},
546 {"trigger", {1, 1, {false, trigger_command}}},
547 };
548 return test_function_map;
549}
550
551TEST(init, LazilyLoadedActionsCantBeTriggeredByTheSameTrigger) {
552 // "start" script loads "lazy" script. Even though "lazy" scripts
553 // defines "on boot" action, it's not executed by the current "boot"
554 // event because it's already processed.
555 TemporaryFile lazy;
556 ASSERT_TRUE(lazy.fd != -1);
557 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", lazy.fd));
558
559 TemporaryFile start;
560 // clang-format off
561 std::string start_script = "on boot\n"
562 "load " + std::string(lazy.path) + "\n"
563 "execute 1";
564 // clang-format on
565 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
566
567 int num_executed = 0;
568 ActionManager action_manager;
569 ServiceList service_list;
570 BuiltinFunctionMap test_function_map =
571 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
572
573 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
574 std::vector<ActionManagerCommand> commands{trigger_boot};
575 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
576
577 EXPECT_EQ(1, num_executed);
578}
579
580TEST(init, LazilyLoadedActionsCanBeTriggeredByTheNextTrigger) {
581 // "start" script loads "lazy" script and then triggers "next" event
582 // which executes "on next" action loaded by the previous command.
583 TemporaryFile lazy;
584 ASSERT_TRUE(lazy.fd != -1);
585 ASSERT_TRUE(android::base::WriteStringToFd("on next\nexecute 2", lazy.fd));
586
587 TemporaryFile start;
588 // clang-format off
589 std::string start_script = "on boot\n"
590 "load " + std::string(lazy.path) + "\n"
591 "execute 1\n"
592 "trigger next";
593 // clang-format on
594 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
595
596 int num_executed = 0;
597 ActionManager action_manager;
598 ServiceList service_list;
599 BuiltinFunctionMap test_function_map =
600 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
601
602 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
603 std::vector<ActionManagerCommand> commands{trigger_boot};
604 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
605
606 EXPECT_EQ(2, num_executed);
607}
608
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100609TEST(init, RejectsCriticalAndOneshotService) {
Tom Cherry0e40ba32020-07-09 08:47:24 -0700610 if (GetIntProperty("ro.product.first_api_level", 10000) < 30) {
611 GTEST_SKIP() << "Test only valid for devices launching with R or later";
612 }
613
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100614 std::string init_script =
615 R"init(
616service A something
617 class first
618 critical
619 oneshot
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 ASSERT_EQ(1u, parser.parse_error_count());
633}
634
Carlos Galo14471202022-12-07 23:39:05 +0000635TEST(init, MemLockLimit) {
636 // Test is enforced only for U+ devices
637 if (android::base::GetIntProperty("ro.vendor.api_level", 0) < __ANDROID_API_U__) {
638 GTEST_SKIP();
639 }
640
641 // Verify we are running memlock at, or under, 64KB
642 const unsigned long max_limit = 65536;
643 struct rlimit curr_limit;
644 ASSERT_EQ(getrlimit(RLIMIT_MEMLOCK, &curr_limit), 0);
645 ASSERT_LE(curr_limit.rlim_cur, max_limit);
646 ASSERT_LE(curr_limit.rlim_max, max_limit);
647}
648
Bart Van Assche947d75f2023-02-14 07:44:54 -0800649pid_t ForkExecvpAsync(const char* argv[]) {
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800650 pid_t pid = fork();
651 if (pid == 0) {
Bart Van Assche947d75f2023-02-14 07:44:54 -0800652 // Child process.
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800653 close(STDIN_FILENO);
654 close(STDOUT_FILENO);
655 close(STDERR_FILENO);
656
Bart Van Assche947d75f2023-02-14 07:44:54 -0800657 execvp(argv[0], const_cast<char**>(argv));
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800658 PLOG(ERROR) << "exec in ForkExecvpAsync init test";
659 _exit(EXIT_FAILURE);
660 }
Bart Van Assche947d75f2023-02-14 07:44:54 -0800661 // Parent process.
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800662 if (pid == -1) {
663 PLOG(ERROR) << "fork in ForkExecvpAsync init test";
664 return -1;
665 }
666 return pid;
667}
668
Bart Van Assche878560d2023-02-14 07:54:58 -0800669pid_t TracerPid(pid_t pid) {
670 static constexpr std::string_view prefix{"TracerPid:"};
671 std::ifstream is(StringPrintf("/proc/%d/status", pid));
672 std::string line;
673 while (std::getline(is, line)) {
674 if (line.find(prefix) == 0) {
675 return atoi(line.substr(prefix.length()).c_str());
676 }
677 }
678 return -1;
679}
680
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800681TEST(init, GentleKill) {
Daniel Rosenberg2f050862023-02-08 17:25:47 -0800682 if (getuid() != 0) {
683 GTEST_SKIP() << "Must be run as root.";
684 return;
685 }
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800686 std::string init_script = R"init(
687service test_gentle_kill /system/bin/sleep 1000
688 disabled
689 oneshot
690 gentle_kill
691 user root
692 group root
693 seclabel u:r:toolbox:s0
694)init";
695
696 ActionManager action_manager;
697 ServiceList service_list;
698 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
699 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
700
701 auto service = service_list.begin()->get();
702 ASSERT_NE(service, nullptr);
703 ASSERT_RESULT_OK(service->Start());
704 const pid_t pid = service->pid();
705 ASSERT_GT(pid, 0);
706 EXPECT_NE(getsid(pid), 0);
707
708 TemporaryFile logfile;
709 logfile.DoNotRemove();
710 ASSERT_TRUE(logfile.fd != -1);
711
Bart Van Assche947d75f2023-02-14 07:44:54 -0800712 std::string pid_str = std::to_string(pid);
713 const char* argv[] = {"/system/bin/strace", "-o", logfile.path, "-e", "signal", "-p",
714 pid_str.c_str(), nullptr};
715 pid_t strace_pid = ForkExecvpAsync(argv);
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800716
Bart Van Assche878560d2023-02-14 07:54:58 -0800717 // Give strace the chance to connect
718 while (TracerPid(pid) == 0) {
719 std::this_thread::sleep_for(10ms);
720 }
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800721 service->Stop();
722
723 int status;
724 waitpid(strace_pid, &status, 0);
725
726 std::string logs;
727 android::base::ReadFdToString(logfile.fd, &logs);
Bart Van Assche947d75f2023-02-14 07:44:54 -0800728 ASSERT_NE(logs.find("killed by SIGTERM"), std::string::npos);
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800729}
730
Nikita Ioffe9e4b1112020-12-11 17:59:38 +0000731class TestCaseLogger : public ::testing::EmptyTestEventListener {
732 void OnTestStart(const ::testing::TestInfo& test_info) override {
733#ifdef __ANDROID__
734 LOG(INFO) << "===== " << test_info.test_suite_name() << "::" << test_info.name() << " ("
735 << test_info.file() << ":" << test_info.line() << ")";
736#else
737 UNUSED(test_info);
738#endif
739 }
740};
741
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700742} // namespace init
743} // namespace android
Tom Cherrydcb3d152019-08-07 16:02:28 -0700744
745int SubcontextTestChildMain(int, char**);
746int FirmwareTestChildMain(int, char**);
747
748int main(int argc, char** argv) {
749 if (argc > 1 && !strcmp(argv[1], "subcontext")) {
750 return SubcontextTestChildMain(argc, argv);
751 }
752
753 if (argc > 1 && !strcmp(argv[1], "firmware")) {
754 return FirmwareTestChildMain(argc, argv);
755 }
756
757 testing::InitGoogleTest(&argc, argv);
Nikita Ioffe9e4b1112020-12-11 17:59:38 +0000758 testing::UnitTest::GetInstance()->listeners().Append(new android::init::TestCaseLogger());
Tom Cherrydcb3d152019-08-07 16:02:28 -0700759 return RUN_ALL_TESTS();
760}