blob: 295aad41b1a8c7658f97512c0dc9c660c4516dd7 [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 }
Daniel Rosenbergb8baa8d2023-04-07 13:02:42 -0700204 if (getuid() != 0) {
205 GTEST_SKIP() << "Must be run as root.";
206 return;
207 }
Bart Van Assche5d188912022-11-14 09:30:51 -0800208 std::string init_script = R"init(
209service console /system/bin/sh
210 class core
Jiyong Parkae412802022-12-15 16:29:01 +0900211 console null
Bart Van Assche5d188912022-11-14 09:30:51 -0800212 disabled
213 user root
214 group root shell log readproc
Bart Van Assche3b21d952022-11-22 16:53:05 -0800215 seclabel u:r:shell:s0
Bart Van Assche5d188912022-11-14 09:30:51 -0800216 setenv HOSTNAME console
217)init";
218
219 ActionManager action_manager;
220 ServiceList service_list;
221 TestInitText(init_script, BuiltinFunctionMap(), {}, &action_manager, &service_list);
222 ASSERT_EQ(std::distance(service_list.begin(), service_list.end()), 1);
223
224 auto service = service_list.begin()->get();
225 ASSERT_NE(service, nullptr);
226 ASSERT_RESULT_OK(service->Start());
227 const pid_t pid = service->pid();
228 ASSERT_GT(pid, 0);
Bart Van Assche3b21d952022-11-22 16:53:05 -0800229 EXPECT_NE(getsid(pid), 0);
Bart Van Assche5d188912022-11-14 09:30:51 -0800230 service->Stop();
231}
232
Deyao Ren07595e12022-07-15 22:02:14 +0000233static std::string GetSecurityContext() {
234 char* ctx;
235 if (getcon(&ctx) == -1) {
236 ADD_FAILURE() << "Failed to call getcon : " << strerror(errno);
237 }
238 std::string result = std::string(ctx);
239 freecon(ctx);
240 return result;
241}
242
243void TestStartApexServices(const std::vector<std::string>& service_names,
244 const std::string& apex_name) {
245 for (auto const& svc : service_names) {
246 auto service = ServiceList::GetInstance().FindService(svc);
247 ASSERT_NE(nullptr, service);
248 ASSERT_RESULT_OK(service->Start());
249 ASSERT_TRUE(service->IsRunning());
250 LOG(INFO) << "Service " << svc << " is running";
251 if (!apex_name.empty()) {
252 service->set_filename("/apex/" + apex_name + "/init_test.rc");
253 } else {
254 service->set_filename("");
255 }
256 }
257 if (!apex_name.empty()) {
258 auto apex_services = ServiceList::GetInstance().FindServicesByApexName(apex_name);
259 EXPECT_EQ(service_names.size(), apex_services.size());
260 }
261}
262
263void TestStopApexServices(const std::vector<std::string>& service_names, bool expect_to_run) {
264 for (auto const& svc : service_names) {
265 auto service = ServiceList::GetInstance().FindService(svc);
266 ASSERT_NE(nullptr, service);
267 EXPECT_EQ(expect_to_run, service->IsRunning());
268 }
Deyao Ren238e9092022-07-21 23:05:13 +0000269}
270
271void TestRemoveApexService(const std::vector<std::string>& service_names, bool exist) {
272 for (auto const& svc : service_names) {
273 auto service = ServiceList::GetInstance().FindService(svc);
274 ASSERT_EQ(exist, service != nullptr);
275 }
Deyao Ren07595e12022-07-15 22:02:14 +0000276}
277
278void InitApexService(const std::string_view& init_template) {
279 std::string init_script = StringReplace(init_template, "$selabel",
280 GetSecurityContext(), true);
281
Deyao Ren238e9092022-07-21 23:05:13 +0000282 TestInitText(init_script, BuiltinFunctionMap(), {}, &ActionManager::GetInstance(),
Deyao Ren07595e12022-07-15 22:02:14 +0000283 &ServiceList::GetInstance());
284}
285
deyaoren@google.com909bc472022-09-07 22:25:44 +0000286void CleanupApexServices() {
287 std::vector<std::string> names;
288 for (const auto& s : ServiceList::GetInstance()) {
289 names.push_back(s->name());
290 }
291
292 for (const auto& name : names) {
293 auto s = ServiceList::GetInstance().FindService(name);
294 auto pid = s->pid();
295 ServiceList::GetInstance().RemoveService(*s);
296 if (pid > 0) {
297 kill(pid, SIGTERM);
298 kill(pid, SIGKILL);
299 }
300 }
301
302 ActionManager::GetInstance().RemoveActionIf([&](const std::unique_ptr<Action>& s) -> bool {
303 return true;
304 });
305}
306
Deyao Ren07595e12022-07-15 22:02:14 +0000307void TestApexServicesInit(const std::vector<std::string>& apex_services,
308 const std::vector<std::string>& other_apex_services,
309 const std::vector<std::string> non_apex_services) {
310 auto num_svc = apex_services.size() + other_apex_services.size() + non_apex_services.size();
Deyao Ren238e9092022-07-21 23:05:13 +0000311 ASSERT_EQ(num_svc, ServiceList::GetInstance().size());
Deyao Ren07595e12022-07-15 22:02:14 +0000312
313 TestStartApexServices(apex_services, "com.android.apex.test_service");
314 TestStartApexServices(other_apex_services, "com.android.other_apex.test_service");
315 TestStartApexServices(non_apex_services, /*apex_anme=*/ "");
316
317 StopServicesFromApex("com.android.apex.test_service");
318 TestStopApexServices(apex_services, /*expect_to_run=*/ false);
319 TestStopApexServices(other_apex_services, /*expect_to_run=*/ true);
320 TestStopApexServices(non_apex_services, /*expect_to_run=*/ true);
321
Deyao Ren238e9092022-07-21 23:05:13 +0000322 RemoveServiceAndActionFromApex("com.android.apex.test_service");
323 ASSERT_EQ(other_apex_services.size() + non_apex_services.size(),
324 ServiceList::GetInstance().size());
325
326 // TODO(b/244232142): Add test to check if actions are removed
327 TestRemoveApexService(apex_services, /*exist*/ false);
328 TestRemoveApexService(other_apex_services, /*exist*/ true);
329 TestRemoveApexService(non_apex_services, /*exist*/ true);
330
deyaoren@google.com909bc472022-09-07 22:25:44 +0000331 CleanupApexServices();
Deyao Ren07595e12022-07-15 22:02:14 +0000332}
333
334TEST(init, StopServiceByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900335 if (getuid() != 0) {
336 GTEST_SKIP() << "Must be run as root.";
337 return;
338 }
Deyao Ren07595e12022-07-15 22:02:14 +0000339 std::string_view script_template = R"init(
340service apex_test_service /system/bin/yes
341 user shell
342 group shell
343 seclabel $selabel
344)init";
345 InitApexService(script_template);
346 TestApexServicesInit({"apex_test_service"}, {}, {});
347}
348
349TEST(init, StopMultipleServicesByApexName) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900350 if (getuid() != 0) {
351 GTEST_SKIP() << "Must be run as root.";
352 return;
353 }
Deyao Ren07595e12022-07-15 22:02:14 +0000354 std::string_view script_template = R"init(
355service apex_test_service_multiple_a /system/bin/yes
356 user shell
357 group shell
358 seclabel $selabel
359service apex_test_service_multiple_b /system/bin/id
360 user shell
361 group shell
362 seclabel $selabel
363)init";
364 InitApexService(script_template);
365 TestApexServicesInit({"apex_test_service_multiple_a",
366 "apex_test_service_multiple_b"}, {}, {});
367}
368
369TEST(init, StopServicesFromMultipleApexes) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900370 if (getuid() != 0) {
371 GTEST_SKIP() << "Must be run as root.";
372 return;
373 }
Deyao Ren07595e12022-07-15 22:02:14 +0000374 std::string_view apex_script_template = R"init(
375service apex_test_service_multi_apex_a /system/bin/yes
376 user shell
377 group shell
378 seclabel $selabel
379service apex_test_service_multi_apex_b /system/bin/id
380 user shell
381 group shell
382 seclabel $selabel
383)init";
384 InitApexService(apex_script_template);
385
386 std::string_view other_apex_script_template = R"init(
387service apex_test_service_multi_apex_c /system/bin/yes
388 user shell
389 group shell
390 seclabel $selabel
391)init";
392 InitApexService(other_apex_script_template);
393
394 TestApexServicesInit({"apex_test_service_multi_apex_a",
395 "apex_test_service_multi_apex_b"}, {"apex_test_service_multi_apex_c"}, {});
396}
397
398TEST(init, StopServicesFromApexAndNonApex) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900399 if (getuid() != 0) {
400 GTEST_SKIP() << "Must be run as root.";
401 return;
402 }
Deyao Ren07595e12022-07-15 22:02:14 +0000403 std::string_view apex_script_template = R"init(
404service apex_test_service_apex_a /system/bin/yes
405 user shell
406 group shell
407 seclabel $selabel
408service apex_test_service_apex_b /system/bin/id
409 user shell
410 group shell
411 seclabel $selabel
412)init";
413 InitApexService(apex_script_template);
414
415 std::string_view non_apex_script_template = R"init(
416service apex_test_service_non_apex /system/bin/yes
417 user shell
418 group shell
419 seclabel $selabel
420)init";
421 InitApexService(non_apex_script_template);
422
423 TestApexServicesInit({"apex_test_service_apex_a",
424 "apex_test_service_apex_b"}, {}, {"apex_test_service_non_apex"});
425}
426
427TEST(init, StopServicesFromApexMixed) {
Jooyung Han93c24d72022-09-06 09:58:47 +0900428 if (getuid() != 0) {
429 GTEST_SKIP() << "Must be run as root.";
430 return;
431 }
Deyao Ren07595e12022-07-15 22:02:14 +0000432 std::string_view script_template = R"init(
433service apex_test_service_mixed_a /system/bin/yes
434 user shell
435 group shell
436 seclabel $selabel
437)init";
438 InitApexService(script_template);
439
440 std::string_view other_apex_script_template = R"init(
441service apex_test_service_mixed_b /system/bin/yes
442 user shell
443 group shell
444 seclabel $selabel
445)init";
446 InitApexService(other_apex_script_template);
447
448 std::string_view non_apex_script_template = R"init(
449service apex_test_service_mixed_c /system/bin/yes
450 user shell
451 group shell
452 seclabel $selabel
453)init";
454 InitApexService(non_apex_script_template);
455
456 TestApexServicesInit({"apex_test_service_mixed_a"},
457 {"apex_test_service_mixed_b"}, {"apex_test_service_mixed_c"});
458}
459
Tom Cherryad54d092017-04-19 16:18:50 -0700460TEST(init, EventTriggerOrderMultipleFiles) {
461 // 6 total files, which should have their triggers executed in the following order:
462 // 1: start - original script parsed
463 // 2: first_import - immediately imported by first_script
464 // 3: dir_a - file named 'a.rc' in dir; dir is imported after first_import
465 // 4: a_import - file imported by dir_a
466 // 5: dir_b - file named 'b.rc' in dir
467 // 6: last_import - imported after dir is imported
468
469 TemporaryFile first_import;
470 ASSERT_TRUE(first_import.fd != -1);
471 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", first_import.fd));
472
473 TemporaryFile dir_a_import;
474 ASSERT_TRUE(dir_a_import.fd != -1);
475 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 4", dir_a_import.fd));
476
477 TemporaryFile last_import;
478 ASSERT_TRUE(last_import.fd != -1);
479 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 6", last_import.fd));
480
481 TemporaryDir dir;
482 // clang-format off
483 std::string dir_a_script = "import " + std::string(dir_a_import.path) + "\n"
484 "on boot\n"
485 "execute 3";
486 // clang-format on
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700487 // WriteFile() ensures the right mode is set
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900488 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
Tom Cherryad54d092017-04-19 16:18:50 -0700489
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900490 ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
Tom Cherryad54d092017-04-19 16:18:50 -0700491
492 // clang-format off
493 std::string start_script = "import " + std::string(first_import.path) + "\n"
494 "import " + std::string(dir.path) + "\n"
495 "import " + std::string(last_import.path) + "\n"
496 "on boot\n"
497 "execute 1";
498 // clang-format on
499 TemporaryFile start;
500 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
501
502 int num_executed = 0;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700503 auto execute_command = [&num_executed](const BuiltinArguments& args) {
Tom Cherryad54d092017-04-19 16:18:50 -0700504 EXPECT_EQ(2U, args.size());
505 EXPECT_EQ(++num_executed, std::stoi(args[1]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700506 return Result<void>{};
Tom Cherryad54d092017-04-19 16:18:50 -0700507 };
508
Tom Cherryd52a5b32019-07-22 16:05:36 -0700509 BuiltinFunctionMap test_function_map = {
510 {"execute", {1, 1, {false, execute_command}}},
511 };
Tom Cherryad54d092017-04-19 16:18:50 -0700512
513 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
514 std::vector<ActionManagerCommand> commands{trigger_boot};
515
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900516 ActionManager action_manager;
Steven Moreland6f5333a2017-11-13 15:31:54 -0800517 ServiceList service_list;
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900518 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
Tom Cherryad54d092017-04-19 16:18:50 -0700519
520 EXPECT_EQ(6, num_executed);
521}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700522
Jooyung Hanbadb7de2022-05-10 03:16:51 +0900523BuiltinFunctionMap GetTestFunctionMapForLazyLoad(int& num_executed, ActionManager& action_manager) {
524 auto execute_command = [&num_executed](const BuiltinArguments& args) {
525 EXPECT_EQ(2U, args.size());
526 EXPECT_EQ(++num_executed, std::stoi(args[1]));
527 return Result<void>{};
528 };
529 auto load_command = [&action_manager](const BuiltinArguments& args) -> Result<void> {
530 EXPECT_EQ(2U, args.size());
531 Parser parser;
532 parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, nullptr));
533 if (!parser.ParseConfig(args[1])) {
534 return Error() << "Failed to load";
535 }
536 return Result<void>{};
537 };
538 auto trigger_command = [&action_manager](const BuiltinArguments& args) {
539 EXPECT_EQ(2U, args.size());
540 LOG(INFO) << "Queue event trigger: " << args[1];
541 action_manager.QueueEventTrigger(args[1]);
542 return Result<void>{};
543 };
544 BuiltinFunctionMap test_function_map = {
545 {"execute", {1, 1, {false, execute_command}}},
546 {"load", {1, 1, {false, load_command}}},
547 {"trigger", {1, 1, {false, trigger_command}}},
548 };
549 return test_function_map;
550}
551
552TEST(init, LazilyLoadedActionsCantBeTriggeredByTheSameTrigger) {
553 // "start" script loads "lazy" script. Even though "lazy" scripts
554 // defines "on boot" action, it's not executed by the current "boot"
555 // event because it's already processed.
556 TemporaryFile lazy;
557 ASSERT_TRUE(lazy.fd != -1);
558 ASSERT_TRUE(android::base::WriteStringToFd("on boot\nexecute 2", lazy.fd));
559
560 TemporaryFile start;
561 // clang-format off
562 std::string start_script = "on boot\n"
563 "load " + std::string(lazy.path) + "\n"
564 "execute 1";
565 // clang-format on
566 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
567
568 int num_executed = 0;
569 ActionManager action_manager;
570 ServiceList service_list;
571 BuiltinFunctionMap test_function_map =
572 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
573
574 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
575 std::vector<ActionManagerCommand> commands{trigger_boot};
576 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
577
578 EXPECT_EQ(1, num_executed);
579}
580
581TEST(init, LazilyLoadedActionsCanBeTriggeredByTheNextTrigger) {
582 // "start" script loads "lazy" script and then triggers "next" event
583 // which executes "on next" action loaded by the previous command.
584 TemporaryFile lazy;
585 ASSERT_TRUE(lazy.fd != -1);
586 ASSERT_TRUE(android::base::WriteStringToFd("on next\nexecute 2", lazy.fd));
587
588 TemporaryFile start;
589 // clang-format off
590 std::string start_script = "on boot\n"
591 "load " + std::string(lazy.path) + "\n"
592 "execute 1\n"
593 "trigger next";
594 // clang-format on
595 ASSERT_TRUE(android::base::WriteStringToFd(start_script, start.fd));
596
597 int num_executed = 0;
598 ActionManager action_manager;
599 ServiceList service_list;
600 BuiltinFunctionMap test_function_map =
601 GetTestFunctionMapForLazyLoad(num_executed, action_manager);
602
603 ActionManagerCommand trigger_boot = [](ActionManager& am) { am.QueueEventTrigger("boot"); };
604 std::vector<ActionManagerCommand> commands{trigger_boot};
605 TestInit(start.path, test_function_map, commands, &action_manager, &service_list);
606
607 EXPECT_EQ(2, num_executed);
608}
609
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100610TEST(init, RejectsCriticalAndOneshotService) {
Tom Cherry0e40ba32020-07-09 08:47:24 -0700611 if (GetIntProperty("ro.product.first_api_level", 10000) < 30) {
612 GTEST_SKIP() << "Test only valid for devices launching with R or later";
613 }
614
Nikita Ioffe51c251c2020-04-30 19:40:39 +0100615 std::string init_script =
616 R"init(
617service A something
618 class first
619 critical
620 oneshot
621)init";
622
623 TemporaryFile tf;
624 ASSERT_TRUE(tf.fd != -1);
625 ASSERT_TRUE(android::base::WriteStringToFd(init_script, tf.fd));
626
627 ServiceList service_list;
628 Parser parser;
629 parser.AddSectionParser("service",
630 std::make_unique<ServiceParser>(&service_list, nullptr, std::nullopt));
631
632 ASSERT_TRUE(parser.ParseConfig(tf.path));
633 ASSERT_EQ(1u, parser.parse_error_count());
634}
635
Carlos Galo14471202022-12-07 23:39:05 +0000636TEST(init, MemLockLimit) {
637 // Test is enforced only for U+ devices
638 if (android::base::GetIntProperty("ro.vendor.api_level", 0) < __ANDROID_API_U__) {
639 GTEST_SKIP();
640 }
641
642 // Verify we are running memlock at, or under, 64KB
643 const unsigned long max_limit = 65536;
644 struct rlimit curr_limit;
645 ASSERT_EQ(getrlimit(RLIMIT_MEMLOCK, &curr_limit), 0);
646 ASSERT_LE(curr_limit.rlim_cur, max_limit);
647 ASSERT_LE(curr_limit.rlim_max, max_limit);
648}
649
Daniel Rosenberged8178c2023-01-03 18:28:34 -0800650static std::vector<const char*> ConvertToArgv(const std::vector<std::string>& args) {
651 std::vector<const char*> argv;
652 argv.reserve(args.size() + 1);
653 for (const auto& arg : args) {
654 if (argv.empty()) {
655 LOG(DEBUG) << arg;
656 } else {
657 LOG(DEBUG) << " " << arg;
658 }
659 argv.emplace_back(arg.data());
660 }
661 argv.emplace_back(nullptr);
662 return argv;
663}
664
665pid_t ForkExecvpAsync(const std::vector<std::string>& args) {
666 auto argv = ConvertToArgv(args);
667
668 pid_t pid = fork();
669 if (pid == 0) {
670 close(STDIN_FILENO);
671 close(STDOUT_FILENO);
672 close(STDERR_FILENO);
673
674 execvp(argv[0], const_cast<char**>(argv.data()));
675 PLOG(ERROR) << "exec in ForkExecvpAsync init test";
676 _exit(EXIT_FAILURE);
677 }
678 if (pid == -1) {
679 PLOG(ERROR) << "fork in ForkExecvpAsync init test";
680 return -1;
681 }
682 return pid;
683}
684
685TEST(init, GentleKill) {
686 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}