blob: 7bb5c909c14e3ed7df4ba661a8c9b8d66c6bce64 [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
17#include <functional>
Deyao Ren07595e12022-07-15 22:02:14 +000018#include <string_view>
Daniel Rosenberged8178c2023-01-03 18:28:34 -080019#include <thread>
Deyao Ren07595e12022-07-15 22:02:14 +000020#include <type_traits>
Tom Cherryad54d092017-04-19 16:18:50 -070021
22#include <android-base/file.h>
Nikita Ioffe9e4b1112020-12-11 17:59:38 +000023#include <android-base/logging.h>
Tom Cherry0e40ba32020-07-09 08:47:24 -070024#include <android-base/properties.h>
Carlos Galo14471202022-12-07 23:39:05 +000025#include <android/api-level.h>
Tom Cherryad54d092017-04-19 16:18:50 -070026#include <gtest/gtest.h>
Deyao Ren07595e12022-07-15 22:02:14 +000027#include <selinux/selinux.h>
Carlos Galo14471202022-12-07 23:39:05 +000028#include <sys/resource.h>
Tom Cherryad54d092017-04-19 16:18:50 -070029
30#include "action.h"
Tom Cherry7fd3bc22018-02-13 15:36:14 -080031#include "action_manager.h"
Tom Cherry0f6417f2018-02-13 15:25:29 -080032#include "action_parser.h"
Tom Cherryd52a5b32019-07-22 16:05:36 -070033#include "builtin_arguments.h"
Tom Cherryad54d092017-04-19 16:18:50 -070034#include "builtins.h"
35#include "import_parser.h"
Deyao Ren07595e12022-07-15 22:02:14 +000036#include "init.h"
Tom Cherryad54d092017-04-19 16:18:50 -070037#include "keyword_map.h"
Tom Cherry67dee622017-07-27 12:54:48 -070038#include "parser.h"
Steven Moreland6f5333a2017-11-13 15:31:54 -080039#include "service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070040#include "service_list.h"
41#include "service_parser.h"
Tom Cherryad54d092017-04-19 16:18:50 -070042#include "util.h"
43
Tom Cherry0e40ba32020-07-09 08:47:24 -070044using android::base::GetIntProperty;
Jooyung Han678f0b42022-07-07 15:25:02 +090045using android::base::GetProperty;
46using android::base::SetProperty;
Deyao Ren07595e12022-07-15 22:02:14 +000047using android::base::StringReplace;
Jooyung Han678f0b42022-07-07 15:25:02 +090048using android::base::WaitForProperty;
49using namespace std::literals;
Tom Cherry0e40ba32020-07-09 08:47:24 -070050
Tom Cherry81f5d3e2017-06-22 12:53:17 -070051namespace android {
52namespace init {
53
Tom Cherryad54d092017-04-19 16:18:50 -070054using ActionManagerCommand = std::function<void(ActionManager&)>;
55
Tom Cherryd52a5b32019-07-22 16:05:36 -070056void TestInit(const std::string& init_script_file, const BuiltinFunctionMap& test_function_map,
Jooyung Hanbadb7de2022-05-10 03:16:51 +090057 const std::vector<ActionManagerCommand>& commands, ActionManager* action_manager,
58 ServiceList* service_list) {
Tom Cherryad54d092017-04-19 16:18:50 -070059 Action::set_function_map(&test_function_map);
60
61 Parser parser;
Daniel Norman3df8dc52019-06-27 12:18:08 -070062 parser.AddSectionParser("service",
63 std::make_unique<ServiceParser>(service_list, nullptr, std::nullopt));
Jooyung Hanbadb7de2022-05-10 03:16:51 +090064 parser.AddSectionParser("on", std::make_unique<ActionParser>(action_manager, nullptr));
Tom Cherryad54d092017-04-19 16:18:50 -070065 parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
66
67 ASSERT_TRUE(parser.ParseConfig(init_script_file));
68
69 for (const auto& command : commands) {
Jooyung Hanbadb7de2022-05-10 03:16:51 +090070 command(*action_manager);
Tom Cherryad54d092017-04-19 16:18:50 -070071 }
72
Jooyung Hanbadb7de2022-05-10 03:16:51 +090073 while (action_manager->HasMoreCommands()) {
74 action_manager->ExecuteOneCommand();
Tom Cherryad54d092017-04-19 16:18:50 -070075 }
76}
77
Tom Cherryd52a5b32019-07-22 16:05:36 -070078void TestInitText(const std::string& init_script, const BuiltinFunctionMap& test_function_map,
Jooyung Hanbadb7de2022-05-10 03:16:51 +090079 const std::vector<ActionManagerCommand>& commands, ActionManager* action_manager,
80 ServiceList* service_list) {
Tom Cherryad54d092017-04-19 16:18:50 -070081 TemporaryFile tf;
82 ASSERT_TRUE(tf.fd != -1);
83 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
Jooyung Hanbadb7de2022-05-10 03:16:51 +090084 TestInit(tf.path, test_function_map, commands, action_manager, service_list);
Tom Cherryad54d092017-04-19 16:18:50 -070085}
86
87TEST(init, SimpleEventTrigger) {
88 bool expect_true = false;
89 std::string init_script =
90 R"init(
91on boot
92pass_test
93)init";
94
Tom Cherryd52a5b32019-07-22 16:05:36 -070095 auto do_pass_test = [&expect_true](const BuiltinArguments&) {
96 expect_true = true;
97 return Result<void>{};
98 };
99 BuiltinFunctionMap test_function_map = {
100 {"pass_test", {0, 0, {false, do_pass_test}}},
101 };
Tom Cherryad54d092017-04-19 16:18:50 -0700102
103 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
104 std::vector<ActionManagerCommand> commands{trigger_boot};
105
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900106 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800107 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900108 TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
Tom Cherryad54d092017-04-19 16:18:50 -0700109
110 EXPECT_TRUE(expect_true);
111}
112
Nikita Ioffeaaab5962019-10-10 20:42:37 +0100113TEST(init, WrongEventTrigger) {
114 std::string init_script =
115 R"init(
116on boot:
117pass_test
118)init";
119
120 TemporaryFile tf;
121 ASSERT_TRUE(tf.fd != -1);
122 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
123
124 ActionManager am;
125
126 Parser parser;
127 parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
128
129 ASSERT_TRUE(parser.ParseConfig(tf.path));
130 ASSERT_EQ(1u, parser.parse_error_count());
131}
132
Tom Cherryad54d092017-04-19 16:18:50 -0700133TEST(init, EventTriggerOrder) {
134 std::string init_script =
135 R"init(
136on boot
137execute_first
138
139on boot && property:ro.hardware=*
140execute_second
141
142on boot
143execute_third
144
145)init";
146
147 int num_executed = 0;
Tom Cherryd52a5b32019-07-22 16:05:36 -0700148 auto do_execute_first = [&num_executed](const BuiltinArguments&) {
149 EXPECT_EQ(0, num_executed++);
150 return Result<void>{};
151 };
152 auto do_execute_second = [&num_executed](const BuiltinArguments&) {
153 EXPECT_EQ(1, num_executed++);
154 return Result<void>{};
155 };
156 auto do_execute_third = [&num_executed](const BuiltinArguments&) {
157 EXPECT_EQ(2, num_executed++);
158 return Result<void>{};
159 };
160
161 BuiltinFunctionMap test_function_map = {
162 {"execute_first", {0, 0, {false, do_execute_first}}},
163 {"execute_second", {0, 0, {false, do_execute_second}}},
164 {"execute_third", {0, 0, {false, do_execute_third}}},
165 };
Tom Cherryad54d092017-04-19 16:18:50 -0700166
167 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
168 std::vector<ActionManagerCommand> commands{trigger_boot};
169
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900170 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800171 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900172 TestInitText(init_script, test_function_map, commands, &action_manager, &service_list);
Florian Mayer6268f6a2022-05-11 01:02:01 +0000173 EXPECT_EQ(3, num_executed);
Steven Moreland6f5333a2017-11-13 15:31:54 -0800174}
175
176TEST(init, OverrideService) {
177 std::string init_script = R"init(
178service A something
179 class first
180
181service A something
182 class second
183 override
184
185)init";
186
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900187 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800188 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900189 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
Steven Moreland6f5333a2017-11-13 15:31:54 -0800190 ASSERT_EQ(1, std::distance(service_list.begin(), service_list.end()));
191
192 auto service = service_list.begin()->get();
193 ASSERT_NE(nullptr, service);
194 EXPECT_EQ(std::set<std::string>({"second"}), service->classnames());
195 EXPECT_EQ("A", service->name());
196 EXPECT_TRUE(service->is_override());
Tom Cherryad54d092017-04-19 16:18:50 -0700197}
198
Bart Van Assche5d188912022-11-14 09:30:51 -0800199TEST(init, StartConsole) {
Jiyong Park5b7a51a2022-12-20 09:18:49 +0900200 if (GetProperty("ro.build.type", "") == "user") {
201 GTEST_SKIP() << "Must run on userdebug/eng builds. b/262090304";
202 return;
203 }
Bart Van Assche5d188912022-11-14 09:30:51 -0800204 std::string init_script = R"init(
205service console /system/bin/sh
206 class core
Jiyong Parkae412802022-12-15 16:29:01 +0900207 console null
Bart Van Assche5d188912022-11-14 09:30:51 -0800208 disabled
209 user root
210 group root shell log readproc
Bart Van Assche3b21d952022-11-22 16:53:05 -0800211 seclabel u:r:shell:s0
Bart Van Assche5d188912022-11-14 09:30:51 -0800212 setenv HOSTNAME console
213)init";
214
215 ActionManager action_manager;
216 ServiceList service_list;
217 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
218 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
219
220 auto service = service_list.begin()->get();
221 ASSERT_NE(service, nullptr);
222 ASSERT_RESULT_OK(service->Start());
223 const pid_t pid = service->pid();
224 ASSERT_GT(pid, 0);
Bart Van Assche3b21d952022-11-22 16:53:05 -0800225 EXPECT_NE(getsid(pid), 0);
Bart Van Assche5d188912022-11-14 09:30:51 -0800226 service->Stop();
227}
228
Deyao Ren07595e12022-07-15 22:02:14 +0000229static std::string GetSecurityContext() {
230 char* ctx;
231 if (getcon(&ctx) == -1) {
232 ADD_FAILURE() << "Failed to call getcon : " << strerror(errno);
233 }
234 std::string result = std::string(ctx);
235 freecon(ctx);
236 return result;
237}
238
239void TestStartApexServices(const std::vector<std::string>& service_names,
240 const std::string& apex_name) {
241 for (auto const& svc : service_names) {
242 auto service = ServiceList::GetInstance().FindService(svc);
243 ASSERT_NE(nullptr, service);
244 ASSERT_RESULT_OK(service->Start());
245 ASSERT_TRUE(service->IsRunning());
246 LOG(INFO) << "Service " << svc << " is running";
247 if (!apex_name.empty()) {
248 service->set_filename("/apex/" + apex_name + "/init_test.rc");
249 } else {
250 service->set_filename("");
251 }
252 }
253 if (!apex_name.empty()) {
254 auto apex_services = ServiceList::GetInstance().FindServicesByApexName(apex_name);
255 EXPECT_EQ(service_names.size(), apex_services.size());
256 }
257}
258
259void TestStopApexServices(const std::vector<std::string>& service_names, bool expect_to_run) {
260 for (auto const& svc : service_names) {
261 auto service = ServiceList::GetInstance().FindService(svc);
262 ASSERT_NE(nullptr, service);
263 EXPECT_EQ(expect_to_run, service->IsRunning());
264 }
Deyao Ren238e9092022-07-21 23:05:13 +0000265}
266
267void TestRemoveApexService(const std::vector<std::string>& service_names, bool exist) {
268 for (auto const& svc : service_names) {
269 auto service = ServiceList::GetInstance().FindService(svc);
270 ASSERT_EQ(exist, service != nullptr);
271 }
Deyao Ren07595e12022-07-15 22:02:14 +0000272}
273
274void InitApexService(const std::string_view& init_template) {
275 std::string init_script = StringReplace(init_template, "$selabel",
276 GetSecurityContext(), true);
277
Deyao Ren238e9092022-07-21 23:05:13 +0000278 TestInitText(init_script, BuiltinFunctionMap(), {}, &ActionManager::GetInstance(),
Deyao Ren07595e12022-07-15 22:02:14 +0000279 &ServiceList::GetInstance());
280}
281
deyaoren@google.com909bc472022-09-07 22:25:44 +0000282void CleanupApexServices() {
283 std::vector<std::string> names;
284 for (const auto& s : ServiceList::GetInstance()) {
285 names.push_back(s->name());
286 }
287
288 for (const auto& name : names) {
289 auto s = ServiceList::GetInstance().FindService(name);
290 auto pid = s->pid();
291 ServiceList::GetInstance().RemoveService(*s);
292 if (pid > 0) {
293 kill(pid, SIGTERM);
294 kill(pid, SIGKILL);
295 }
296 }
297
298 ActionManager::GetInstance().RemoveActionIf([&](const std::unique_ptr<Action>& s) -> bool {
299 return true;
300 });
301}
302
Deyao Ren07595e12022-07-15 22:02:14 +0000303void TestApexServicesInit(const std::vector<std::string>& apex_services,
304 const std::vector<std::string>& other_apex_services,
305 const std::vector<std::string> non_apex_services) {
306 auto num_svc = apex_services.size() + other_apex_services.size() + non_apex_services.size();
Deyao Ren238e9092022-07-21 23:05:13 +0000307 ASSERT_EQ(num_svc, ServiceList::GetInstance().size());
Deyao Ren07595e12022-07-15 22:02:14 +0000308
309 TestStartApexServices(apex_services, "com.android.apex.test_service");
310 TestStartApexServices(other_apex_services, "com.android.other_apex.test_service");
311 TestStartApexServices(non_apex_services, /*apex_anme=*/ "");
312
313 StopServicesFromApex("com.android.apex.test_service");
314 TestStopApexServices(apex_services, /*expect_to_run=*/ false);
315 TestStopApexServices(other_apex_services, /*expect_to_run=*/ true);
316 TestStopApexServices(non_apex_services, /*expect_to_run=*/ true);
317
Deyao Ren238e9092022-07-21 23:05:13 +0000318 RemoveServiceAndActionFromApex("com.android.apex.test_service");
319 ASSERT_EQ(other_apex_services.size() + non_apex_services.size(),
320 ServiceList::GetInstance().size());
321
322 // TODO(b/244232142): Add test to check if actions are removed
323 TestRemoveApexService(apex_services, /*exist*/ false);
324 TestRemoveApexService(other_apex_services, /*exist*/ true);
325 TestRemoveApexService(non_apex_services, /*exist*/ true);
326
deyaoren@google.com909bc472022-09-07 22:25:44 +0000327 CleanupApexServices();
Deyao Ren07595e12022-07-15 22:02:14 +0000328}
329
330TEST(init, StopServiceByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900331 if (getuid() != 0) {
332 GTEST_SKIP() << "Must be run as root.";
333 return;
334 }
Deyao Ren07595e12022-07-15 22:02:14 +0000335 std::string_view script_template = R"init(
336service apex_test_service /system/bin/yes
337 user shell
338 group shell
339 seclabel $selabel
340)init";
341 InitApexService(script_template);
342 TestApexServicesInit({"apex_test_service"}, {}, {});
343}
344
345TEST(init, StopMultipleServicesByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900346 if (getuid() != 0) {
347 GTEST_SKIP() << "Must be run as root.";
348 return;
349 }
Deyao Ren07595e12022-07-15 22:02:14 +0000350 std::string_view script_template = R"init(
351service apex_test_service_multiple_a /system/bin/yes
352 user shell
353 group shell
354 seclabel $selabel
355service apex_test_service_multiple_b /system/bin/id
356 user shell
357 group shell
358 seclabel $selabel
359)init";
360 InitApexService(script_template);
361 TestApexServicesInit({"apex_test_service_multiple_a",
362 "apex_test_service_multiple_b"}, {}, {});
363}
364
365TEST(init, StopServicesFromMultipleApexes) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900366 if (getuid() != 0) {
367 GTEST_SKIP() << "Must be run as root.";
368 return;
369 }
Deyao Ren07595e12022-07-15 22:02:14 +0000370 std::string_view apex_script_template = R"init(
371service apex_test_service_multi_apex_a /system/bin/yes
372 user shell
373 group shell
374 seclabel $selabel
375service apex_test_service_multi_apex_b /system/bin/id
376 user shell
377 group shell
378 seclabel $selabel
379)init";
380 InitApexService(apex_script_template);
381
382 std::string_view other_apex_script_template = R"init(
383service apex_test_service_multi_apex_c /system/bin/yes
384 user shell
385 group shell
386 seclabel $selabel
387)init";
388 InitApexService(other_apex_script_template);
389
390 TestApexServicesInit({"apex_test_service_multi_apex_a",
391 "apex_test_service_multi_apex_b"}, {"apex_test_service_multi_apex_c"}, {});
392}
393
394TEST(init, StopServicesFromApexAndNonApex) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900395 if (getuid() != 0) {
396 GTEST_SKIP() << "Must be run as root.";
397 return;
398 }
Deyao Ren07595e12022-07-15 22:02:14 +0000399 std::string_view apex_script_template = R"init(
400service apex_test_service_apex_a /system/bin/yes
401 user shell
402 group shell
403 seclabel $selabel
404service apex_test_service_apex_b /system/bin/id
405 user shell
406 group shell
407 seclabel $selabel
408)init";
409 InitApexService(apex_script_template);
410
411 std::string_view non_apex_script_template = R"init(
412service apex_test_service_non_apex /system/bin/yes
413 user shell
414 group shell
415 seclabel $selabel
416)init";
417 InitApexService(non_apex_script_template);
418
419 TestApexServicesInit({"apex_test_service_apex_a",
420 "apex_test_service_apex_b"}, {}, {"apex_test_service_non_apex"});
421}
422
423TEST(init, StopServicesFromApexMixed) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900424 if (getuid() != 0) {
425 GTEST_SKIP() << "Must be run as root.";
426 return;
427 }
Deyao Ren07595e12022-07-15 22:02:14 +0000428 std::string_view script_template = R"init(
429service apex_test_service_mixed_a /system/bin/yes
430 user shell
431 group shell
432 seclabel $selabel
433)init";
434 InitApexService(script_template);
435
436 std::string_view other_apex_script_template = R"init(
437service apex_test_service_mixed_b /system/bin/yes
438 user shell
439 group shell
440 seclabel $selabel
441)init";
442 InitApexService(other_apex_script_template);
443
444 std::string_view non_apex_script_template = R"init(
445service apex_test_service_mixed_c /system/bin/yes
446 user shell
447 group shell
448 seclabel $selabel
449)init";
450 InitApexService(non_apex_script_template);
451
452 TestApexServicesInit({"apex_test_service_mixed_a"},
453 {"apex_test_service_mixed_b"}, {"apex_test_service_mixed_c"});
454}
455
Tom Cherryad54d092017-04-19 16:18:50 -0700456TEST(init, EventTriggerOrderMultipleFiles) {
457 // 6 total files, which should have their triggers executed in the following order:
458 // 1: start - original script parsed
459 // 2: first_import - immediately imported by first_script
460 // 3: dir_a - file named 'a.rc' in dir; dir is imported after first_import
461 // 4: a_import - file imported by dir_a
462 // 5: dir_b - file named 'b.rc' in dir
463 // 6: last_import - imported after dir is imported
464
465 TemporaryFile first_import;
466 ASSERT_TRUE(first_import.fd != -1);
467 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", first_import.fd));
468
469 TemporaryFile dir_a_import;
470 ASSERT_TRUE(dir_a_import.fd != -1);
471 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 4", dir_a_import.fd));
472
473 TemporaryFile last_import;
474 ASSERT_TRUE(last_import.fd != -1);
475 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 6", last_import.fd));
476
477 TemporaryDir dir;
478 // clang-format off
479 std::string dir_a_script = "import " + std::string(dir_a_import.path) + "\n"
480 "on boot\n"
481 "execute 3";
482 // clang-format on
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700483 // WriteFile() ensures the right mode is set
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900484 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
Tom Cherryad54d092017-04-19 16:18:50 -0700485
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900486 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
Tom Cherryad54d092017-04-19 16:18:50 -0700487
488 // clang-format off
489 std::string start_script = "import " + std::string(first_import.path) + "\n"
490 "import " + std::string(dir.path) + "\n"
491 "import " + std::string(last_import.path) + "\n"
492 "on boot\n"
493 "execute 1";
494 // clang-format on
495 TemporaryFile start;
496 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
497
498 int num_executed = 0;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700499 auto execute_command = [&num_executed](const BuiltinArguments& args) {
Tom Cherryad54d092017-04-19 16:18:50 -0700500 EXPECT_EQ(2U, args.size());
501 EXPECT_EQ(++num_executed, std::stoi(args[1]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700502 return Result<void>{};
Tom Cherryad54d092017-04-19 16:18:50 -0700503 };
504
Tom Cherryd52a5b32019-07-22 16:05:36 -0700505 BuiltinFunctionMap test_function_map = {
506 {"execute", {1, 1, {false, execute_command}}},
507 };
Tom Cherryad54d092017-04-19 16:18:50 -0700508
509 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
510 std::vector<ActionManagerCommand> commands{trigger_boot};
511
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900512 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800513 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900514 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
Tom Cherryad54d092017-04-19 16:18:50 -0700515
516 EXPECT_EQ(6, num_executed);
517}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700518
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900519BuiltinFunctionMap GetTestFunctionMapForLazyLoad(int& num_executed, ActionManager& action_manager) {
520 auto execute_command = [&num_executed](const BuiltinArguments& args) {
521 EXPECT_EQ(2U, args.size());
522 EXPECT_EQ(++num_executed, std::stoi(args[1]));
523 return Result<void>{};
524 };
525 auto load_command = [&action_manager](const BuiltinArguments& args) -> Result<void> {
526 EXPECT_EQ(2U, args.size());
527 Parser parser;
528 parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, nullptr));
529 if (!parser.ParseConfig(args[1])) {
530 return Error() << "Failed to load";
531 }
532 return Result<void>{};
533 };
534 auto trigger_command = [&action_manager](const BuiltinArguments& args) {
535 EXPECT_EQ(2U, args.size());
536 LOG(INFO) << "Queue event trigger: " << args[1];
537 action_manager.QueueEventTrigger(args[1]);
538 return Result<void>{};
539 };
540 BuiltinFunctionMap test_function_map = {
541 {"execute", {1, 1, {false, execute_command}}},
542 {"load", {1, 1, {false, load_command}}},
543 {"trigger", {1, 1, {false, trigger_command}}},
544 };
545 return test_function_map;
546}
547
548TEST(init, LazilyLoadedActionsCantBeTriggeredByTheSameTrigger) {
549 // "start" script loads "lazy" script. Even though "lazy" scripts
550 // defines "on boot" action, it's not executed by the current "boot"
551 // event because it's already processed.
552 TemporaryFile lazy;
553 ASSERT_TRUE(lazy.fd != -1);
554 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", lazy.fd));
555
556 TemporaryFile start;
557 // clang-format off
558 std::string start_script = "on boot\n"
559 "load " + std::string(lazy.path) + "\n"
560 "execute 1";
561 // clang-format on
562 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
563
564 int num_executed = 0;
565 ActionManager action_manager;
566 ServiceList service_list;
567 BuiltinFunctionMap test_function_map =
568 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
569
570 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
571 std::vector<ActionManagerCommand> commands{trigger_boot};
572 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
573
574 EXPECT_EQ(1, num_executed);
575}
576
577TEST(init, LazilyLoadedActionsCanBeTriggeredByTheNextTrigger) {
578 // "start" script loads "lazy" script and then triggers "next" event
579 // which executes "on next" action loaded by the previous command.
580 TemporaryFile lazy;
581 ASSERT_TRUE(lazy.fd != -1);
582 ASSERT_TRUE(android::base::WriteStringToFd("on next\nexecute 2", lazy.fd));
583
584 TemporaryFile start;
585 // clang-format off
586 std::string start_script = "on boot\n"
587 "load " + std::string(lazy.path) + "\n"
588 "execute 1\n"
589 "trigger next";
590 // clang-format on
591 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
592
593 int num_executed = 0;
594 ActionManager action_manager;
595 ServiceList service_list;
596 BuiltinFunctionMap test_function_map =
597 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
598
599 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
600 std::vector<ActionManagerCommand> commands{trigger_boot};
601 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
602
603 EXPECT_EQ(2, num_executed);
604}
605
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100606TEST(init, RejectsCriticalAndOneshotService) {
Tom Cherry0e40ba32020-07-09 08:47:24 -0700607 if (GetIntProperty("ro.product.first_api_level", 10000) < 30) {
608 GTEST_SKIP() << "Test only valid for devices launching with R or later";
609 }
610
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100611 std::string init_script =
612 R"init(
613service A something
614 class first
615 critical
616 oneshot
617)init";
618
619 TemporaryFile tf;
620 ASSERT_TRUE(tf.fd != -1);
621 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
622
623 ServiceList service_list;
624 Parser parser;
625 parser.AddSectionParser("service",
626 std::make_unique<ServiceParser>(&service_list, nullptr, std::nullopt));
627
628 ASSERT_TRUE(parser.ParseConfig(tf.path));
629 ASSERT_EQ(1u, parser.parse_error_count());
630}
631
Carlos Galo14471202022-12-07 23:39:05 +0000632TEST(init, MemLockLimit) {
633 // Test is enforced only for U+ devices
634 if (android::base::GetIntProperty("ro.vendor.api_level", 0) < __ANDROID_API_U__) {
635 GTEST_SKIP();
636 }
637
638 // Verify we are running memlock at, or under, 64KB
639 const unsigned long max_limit = 65536;
640 struct rlimit curr_limit;
641 ASSERT_EQ(getrlimit(RLIMIT_MEMLOCK, &curr_limit), 0);
642 ASSERT_LE(curr_limit.rlim_cur, max_limit);
643 ASSERT_LE(curr_limit.rlim_max, max_limit);
644}
645
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800646static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
647 std::vector<const char*> argv;
648 argv.reserve(args.size() + 1);
649 for (const auto& arg : args) {
650 if (argv.empty()) {
651 LOG(DEBUG) << arg;
652 } else {
653 LOG(DEBUG) << " " << arg;
654 }
655 argv.emplace_back(arg.data());
656 }
657 argv.emplace_back(nullptr);
658 return argv;
659}
660
661pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
662 auto argv = ConvertToArgv(args);
663
664 pid_t pid = fork();
665 if (pid == 0) {
666 close(STDIN_FILENO);
667 close(STDOUT_FILENO);
668 close(STDERR_FILENO);
669
670 execvp(argv[0], const_cast<char**>(argv.data()));
671 PLOG(ERROR) << "exec in ForkExecvpAsync init test";
672 _exit(EXIT_FAILURE);
673 }
674 if (pid == -1) {
675 PLOG(ERROR) << "fork in ForkExecvpAsync init test";
676 return -1;
677 }
678 return pid;
679}
680
681TEST(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
712 std::vector<std::string> cmd;
713 cmd.push_back("system/bin/strace");
714 cmd.push_back("-o");
715 cmd.push_back(logfile.path);
716 cmd.push_back("-e");
717 cmd.push_back("signal");
718 cmd.push_back("-p");
719 cmd.push_back(std::to_string(pid));
720 pid_t strace_pid = ForkExecvpAsync(cmd);
721
722 // Give strace a moment to connect
723 std::this_thread::sleep_for(1s);
724 service->Stop();
725
726 int status;
727 waitpid(strace_pid, &status, 0);
728
729 std::string logs;
730 android::base::ReadFdToString(logfile.fd, &logs);
731 int pos = logs.find("killed by SIGTERM");
732 ASSERT_NE(pos, (int)std::string::npos);
733}
734
Nikita Ioffe9e4b1112020-12-11 17:59:38 +0000735class TestCaseLogger : public ::testing::EmptyTestEventListener {
736 void OnTestStart(const ::testing::TestInfo& test_info) override {
737#ifdef __ANDROID__
738 LOG(INFO) << "===== " << test_info.test_suite_name() << "::" << test_info.name() << " ("
739 << test_info.file() << ":" << test_info.line() << ")";
740#else
741 UNUSED(test_info);
742#endif
743 }
744};
745
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700746} // namespace init
747} // namespace android
Tom Cherrydcb3d152019-08-07 16:02:28 -0700748
749int SubcontextTestChildMain(int, char**);
750int FirmwareTestChildMain(int, char**);
751
752int main(int argc, char** argv) {
753 if (argc > 1 && !strcmp(argv[1], "subcontext")) {
754 return SubcontextTestChildMain(argc, argv);
755 }
756
757 if (argc > 1 && !strcmp(argv[1], "firmware")) {
758 return FirmwareTestChildMain(argc, argv);
759 }
760
761 testing::InitGoogleTest(&argc, argv);
Nikita Ioffe9e4b1112020-12-11 17:59:38 +0000762 testing::UnitTest::GetInstance()->listeners().Append(new android::init::TestCaseLogger());
Tom Cherrydcb3d152019-08-07 16:02:28 -0700763 return RUN_ALL_TESTS();
764}